<?php

use App\Base\Base;
use App\Exception\custom\LifeAccountException;
use App\Exception\custom\LifeAccountRoleException;
use App\Models\auth\mysql\Merchant;
use App\Models\auth\mysql\LifeAccountRole;
use App\Services\lifeaccount\LifeAccountService;
use Validate\UserPhoneValidate;
use App\Models\auth\mysql\LifeAccount;
use App\Exception\custom\MerchantException;
use App\Exception\custom\AuthException;
use Helpers\Aes;
use Api\PhpUtils\Http\Request;
use App\Exception\custom\DataException;
use App\Models\auth\mysql\PersionalAuthRecord;
use App\Models\auth\mysql\EnterpriseAuthRecord;
use Api\PhpUtils\Cache\CacheUtil;
use Api\PhpUtils\Redis\RedisUtil;
use Api\PhpUtils\Log\FileLog;


class AccountController extends Base
{
    /**
     * 创建未认证的个人生活号
     */
    public function create_unauthorizedAction()
    {
        // 获取手机号
        (new UserPhoneValidate())->validate();

        $params = $this->params;
        $uid    = $params['user_id'];
        $mobile = $params['mobile'];

        // 查询是否有创建资格
        if (!LifeAccountService::permission($uid)['personal']) {
            throw new LifeAccountException(['cus' => 3]);
        }
        try {
            Merchant::beginTransaction();

            LifeAccountService::unauth_account($uid, $mobile);

            Merchant::commit();
        } catch (\Exception $exception) {
            Merchant::rollback();
            throw $exception;
        }

        $this->success();
    }

    /**
     * 获取生活号详情
     *
     */
    public function get_account_infoAction()
    {
        $params = $this->params;
        $data['account_id']    = $params['account_id']; //当前用户ID
        $data['followed_id']    = $params['followed_id']; // 被关注用户ID
        $data['account_type'] = 1;
        $data['followed_type'] = 1;

        //拿粉丝、关注、赞数和是否关注
        $url = config('interface', 'interaction.index.life_detail');
        if (empty($url)) {
            throw new DataException(['cus' => 0]);
        }
        $res = (new Request())->get($url, $data);
var_dump($res);exit;
        if ($res['code'] == 0 && isset($res['response'])) {
            $this->returnResponse($res['response']);
            return;
        }
        //获取生活号角色
        $LifeAccountRole = LifeAccountRole::getRecord(['user_id' => $user_id], "*");
        if ($LifeAccountRole === false || empty($LifeAccountRole)) {
            throw new LifeAccountRoleException(['cus' => 7]);
        }
        // 查生活号与商户信息
        $lifeAccountInfo = LifeAccount::get('*', ['life_account_id' => $LifeAccountRole['life_account_id']]);
        if ($lifeAccountInfo === false || empty($lifeAccountInfo)) {
            throw new LifeAccountException(['cus' => 2]);
        }
        //tab
        if ($user_id == $lifeAccountInfo['life_account_admin_id']) {
            //主态
            $tab = array(
                1 => '服务',
                2 => '招聘',
                3 => '发布',
                4 => '参与',
                5 => '推荐'
            );
        } else {
            //客态
            $tab = array(
                1 => '服务',
                2 => '招聘',
                3 => '发布',
                4 => '参与',
                5 => '推荐'
            );
        }
        $retLifeAccount['life_account_id'] = (string)$lifeAccountInfo['life_account_id'];
        $retLifeAccount['life_account_name'] = $lifeAccountInfo['life_account_name'];
        $retLifeAccount['life_account_icon'] = $lifeAccountInfo['life_account_icon'];
        $retLifeAccount['life_account_admin_id'] = $lifeAccountInfo['life_account_admin_id'];
        $retLifeAccount['life_account_auth_status'] = $lifeAccountInfo['life_account_auth_status'];
        $retLifeAccount['life_account_status'] = $lifeAccountInfo['life_account_status'];
        $retLifeAccount['enterprise_auth_record_status'] = $lifeAccountInfo['enterprise_auth_record_status'];
        $retLifeAccount['enterprise_auth_record_id'] = $lifeAccountInfo['enterprise_auth_record_id'];
        $retLifeAccount['update_time'] = $lifeAccountInfo['update_time'];
        $retLifeAccount['create_time'] = $lifeAccountInfo['create_time'];
        $retLifeAccount['role_type'] = $LifeAccountRole['role_type'];
        $retLifeAccount['tab'] = $tab;
        $this->success(['result' => $retLifeAccount]);
    }

    /**
     * 根据生活号id获取认证信息
     * 1、生活号所有字段
     * 2、职业标签(个人生活号)
     * 3、姓名、身份证号码、公司名称、统一社会信用代码、生活号类型(是个体还是普通企业)
     */
    public function get_account_by_lidAction()
    {
        $params = $this->params;
        $lid    = $params['life_account_id'];

        // 查生活号与商户信息
        $lifeAccountInfo = LifeAccount::get(['life_account_id', 'life_account_name', 'life_account_type', 'merchant_id', 'life_account_admin_id', 'life_account_auth_status', 'life_account_status', 'enterprise_auth_record_id', 'update_time', 'create_time'], ['life_account_id' => $lid]);

        if ($lifeAccountInfo === false || empty($lifeAccountInfo)) {
            throw new LifeAccountException(['cus' => 2]);
        }
        //        $this->cache = CacheUtil::getInstance('cache');
        //        $key = sprintf("life_account_info|%d",$lid);
        //        $redis_ret = $this->cache->set($key,json_encode($lifeAccountInfo),200);
        //        $redis_get = $this->cache->get($key);
        //根据商户id 查询个人认证记录id
        $merchant = Merchant::get(['owner_id', 'merchant_type'], ['merchant_id' => $lifeAccountInfo['merchant_id']]);

        if ($merchant === false || empty($merchant)) {
            throw new MerchantException(['cus' => 3]);
        }

        if ($lifeAccountInfo['enterprise_auth_record_id'] == 0) {
            //个人生活号
            if ($merchant['merchant_type'] == 1) {
                $where = ['user_id' => $merchant['owner_id']];
            } else {
                $where = ['persional_auth_record_id' => $merchant['owner_id']];
            }

            //根据个人认证记录id查询个人认证详情
            $personalInfo = PersionalAuthRecord::get(['full_name', 'occupation', 'id_card'], $where);
            if ($personalInfo === false || empty($personalInfo)) {
                throw new AuthException(['cus' => 23]);
            }
            $lifeAccountInfo['legal_person'] = $personalInfo['full_name'];
            $lifeAccountInfo['occupation'] = $personalInfo['occupation'];
            $lifeAccountInfo['id_card'] = Aes::decrypt($personalInfo['id_card']);
            $lifeAccountInfo['id_type'] = 0; //个人
        } else {
            //企业生活号
            $enterpriseInfo = EnterpriseAuthRecord::get(['legal_person', 'code', 'legal_id_card', 'name', 'data_type', 'audit_status', 'mobile'], ['life_account_id' => $lid]);
            if ($enterpriseInfo === false || empty($enterpriseInfo)) {
                throw new AuthException(['cus' => 23]);
            }
            $lifeAccountInfo['legal_person'] = $enterpriseInfo['legal_person'];
            $lifeAccountInfo['code'] = $enterpriseInfo['code'];
            $lifeAccountInfo['name'] = $enterpriseInfo['name'];
            $lifeAccountInfo['audit_status'] = $enterpriseInfo['audit_status'];
            $lifeAccountInfo['mobile'] = $enterpriseInfo['mobile'];
            $lifeAccountInfo['id_type'] = $enterpriseInfo['data_type'] == 1 ? 1 : 2;  //2：个体工商户； 3：普通企业
            $lifeAccountInfo['id_card'] = Aes::decrypt($enterpriseInfo['legal_id_card']);
        }
        $lifeTag = LifeAccountService::getLifeAccountTag($lifeAccountInfo['life_account_id']);
        $lifeAccountInfo['tag'] = $lifeTag['life_account_tag'] ?? '';
        $lifeAccountInfo['life_account_id'] = (string)$lifeAccountInfo['life_account_id'];
        $this->success(['result' => $lifeAccountInfo]);
    }

    /*
     * 批量获取生活号角色表数据
     */

    public function get_role_listAction()
    {
        $params   = $this->params;
        $params['page'] = !empty($params['page']) ? $params['page'] : 1;
        $role_id =  $params['role_id'] ?? 0;
        $limit = !empty($params['page_size']) ? $params['page_size'] : 50;
        $page = ($params['page'] - 1) * $limit;
        $data['role_id[>]'] = $role_id;
        $data['role_type'] = 1;
        $data['LIMIT'] = [$page, $limit];
        $list = LifeAccountRole::getRecordList($data);
        //var_dump(LifeAccountRole::log());exit;
        unset($data['LIMIT']);
        $count = LifeAccountRole::getCount($data);

        $this->success(['result' => ['data' => $list, 'count' => $count]]);
    }

    /*
    * 批量获取管理员对应的生活号
    */
    public function get_life_listAction()
    {
        $params   = $this->params;
        $list = [];
        if ($params) {
            $list =  LifeAccountRole::getRecordList(['user_id' => $params, 'role_type' => 1], ['role_id', 'user_id', 'life_account_id']);
        }
        $this->success(['result' =>  $list]);
    }
    /*
    * 批量获取生活号对应的管理员
    */

    public function get_user_listAction()
    {
        $params   = $this->params;
        $list = [];
        if ($params) {
            $list =  LifeAccount::getRecords(['life_account_id' => $params], ['life_account_id', 'life_account_admin_id', 'life_account_name']);
            //FileLog::info('get_user_list', json_encode(LifeAccount::log()));
        }
        $this->success(['result' =>  $list]);
    }

    /**
     * 根据uid获取生活号id
     */
    public function get_lid_by_uidAction()
    {
        $params = $this->params;
        $uid    = $params['uid'];
        $list = [];
        if ($params) {
            $list =  LifeAccountRole::getRecordList(['user_id' => $uid], ['life_account_id']);
        }
        $this->success(['result' =>  $list]);
    }
}
