<?php


namespace App\Services\marketing;

use App\Models\marketing\mysql\Distributor;
use App\Models\marketing\mysql\QyqGroupleader;
use App\Models\marketing\mysql\DistributorAuditRecord;
use Api\PhpUtils\Validate\Validate;
use Api\PhpServices\Idgen\Idgen;
use App\Exception\custom\DistributorException;
use Api\PhpServices\Sensitive\Sensitive;
use Api\PhpServices\JwUser\JwUser;
use Api\PhpUtils\Common\TimeOut;
use App\Exception\custom\CodeSpecialException;
use Api\PhpServices\ShopImage\GetImage;
use Api\PhpServices\ShopImage\QR;
use App\Exception\custom\InterfaceException;
use App\Services\goods\GoodsService;
use Api\PhpUtils\Http\Request;
use App\Exception\BaseException;

class DistributorService
{   

    public static function import()
    {
        $list = QyqGroupleader::getRecords(['status[>=]' => 0]);
        foreach ($list as $key => $value) {
            $userId = $value['userId'];

            if (empty($value['parentUserId'])) {
                $distributorType = 1;
            } else {
                $distributorType = 2;
            }
            $distributorData = [
                'parent_user_id' => $value['parentUserId'],
                'user_id' => $userId,
                'distributor_code' => '',
                'distributor_type' => $distributorType, //1申请团长，2申请二级团长
                'user_name' => $value['userName'],
                'create_time' => $value['createTime'],
                'update_time' => $value['updateTime'],

            ];
            Distributor::insertRecord($distributorData);
        }

        echo "成功";
 
    } 

    /**
     * 查询二级团长
     *
     */
    public static function secondDistributor($params)
    {
        //$params['page'] = !empty($params['page']) ? $params['page'] : 1;
        $limit = !empty($params['num']) ? $params['num'] : 20;
        //$page = ($params['page'] - 1) * $limit;

        // if (!empty($params['user_id'])) {
        //     $where['user_id'] = $params['user_id'];
        // }

        if (!empty($params['user_id'])) {
            $where['parent_user_id'] = $params['user_id'];
        }

        $totalNum = Distributor::getCount($where, "*");
        
        $countWhere = [
            'parent_user_id' => !empty($params['user_id']) ? $params['user_id'] : '',
            "create_time[<>]" => [date("Y-m-d 00:00:00"), date("Y-m-d 23:59:59")]
        ];
        $todayNum = Distributor::getCount($countWhere, "*");

        if (!empty($params['last_id'])) {
             $where['id[<]'] = $params['last_id'];
        }

        $where['LIMIT'] = $limit;
        $where['ORDER'] = ["create_time" => "DESC"];
        $list = Distributor::getRecords($where);
        $last = end($list);
        $lastId = !empty($last['id']) ? $last['id'] : '';

        $data = ['result' => $list,'last_id' => $lastId,'distributor_today_num' => $todayNum,'distributor_total_num' => $totalNum];
        return $data;
    }

    /**
     * 登陆用户申请团长
     * 一级团长申请
     *
     */
    public static function applyDistributor($params)
    {
        $userId = !empty($params['user_id']) ? $params['user_id'] : '';
        $userName = !empty($params['user_name']) ? $params['user_name'] : '';
        $distributorType = 1; //一级团长
        $info = Distributor::getRecord(['user_id' => $userId,'distributor_type' => $distributorType]);
        $shareUserId = !empty($params['share_user_id']) ? $params['share_user_id'] : '';

        if (!empty($shareUserId)) {
            $userId = $shareUserId;
        }

        if (empty($userId)) {
            throw new DistributorException(['cus'=>14]);
        }

        if (!empty($info)) {
            throw new DistributorException(['cus'=>2]);
        }

        if (empty($userName)) {
            throw new DistributorException(['cus'=>3]);
        }

        $detectParams = [
            'businessId' => 1,
            'text' => !empty($userName) ? $userName : '',
            'scene' => 1,
        ];
        $sensitive =  (new Sensitive)->detect($detectParams);
        if (!empty($sensitive['data'])) {
            throw new DistributorException(['cus'=>40]);
        }
 
        if (self::utf8Strlen($userName) > 40) {
            throw new DistributorException(['cus'=>13]);
        }

        Distributor::beginTransaction();
        $userCode = $userId . '_' . $distributorType;
        $data = [
            'user_id' => $userId,
            'user_name' => $userName,
            'update_time' => date("Y-m-d H:i:s"),
            'create_time' => date("Y-m-d H:i:s"), 
            'distributor_code' => $userCode,
            'distributor_type' => $distributorType
        ];
        $id = Distributor::insertRecord($data);

        if (empty($id)) {
            Distributor::rollback();  
            throw new DistributorException(['cus' => 5]);
        }

        //暂时默认通过，
        $auditData = [
            'user_id' => $userId,
            'user_name' => $userName,
            'distributor_type' => $distributorType,
            'status' => 2,
            'update_time' => date("Y-m-d H:i:s"),
            'create_time' => date("Y-m-d H:i:s"), 
            'distributor_code' => $userCode,
        ];
        $auditId = DistributorAuditRecord::insertRecord($auditData);
        if (!empty($auditId)) {
            Distributor::commit();
            return $auditId;
        }else{
            Distributor::rollback();  
            throw new DistributorException(['cus' => 5]);
        }
    }
    
    /**
     * 申请二级团长
     *
     */
    public static function applySecondDistributor($params)
    {
        $userId = !empty($params['user_id']) ? $params['user_id'] : '';
        $userName = !empty($params['user_name']) ? $params['user_name'] : '';
        $mobile = !empty($params['mobile']) ? $params['mobile'] : '';
        $distributorCode = !empty($params['distributor_code']) ? $params['distributor_code'] : '';
        $smsCode = !empty($params['sms_code']) ? $params['sms_code'] : '';
        $shareUserId = !empty($params['share_user_id']) ? $params['share_user_id'] : '';

        if (empty($smsCode)) {
            throw new DistributorException(['cus'=>11]);
        }
        $sms = self::checkSmsCode($params);
        if ($sms['code'] != 0) {
            throw new BaseException(['code'=>$sms['code'],'msg' => $sms['reason']]);
        }

        $jwUserId = '';
        $info = Distributor::getRecord(['user_id' => $shareUserId]);

        if (empty($info)) {
            throw new DistributorException(['cus'=>10]);
        }
 
        $parentUserId = !empty($info['user_id']) ? $info['user_id'] : '';
        $distributorType = !empty($info['distributor_type']) ? $info['distributor_type'] : '';
        if (empty($mobile)) {
            throw new DistributorException(['cus'=>6]);
        }

        $param = [
            'mobile' => $mobile,
        ];
        $jwUser = new JwUser();
        $userInfo =  $jwUser->getUserInfo($params);

        if (!empty($userInfo) && $userInfo['result'] == 0) {
            if (!empty($userInfo['data'])) {
                 $jwUserId = !empty($userInfo['data']['userId']) ? $userInfo['data']['userId'] : '';
            }
        }else{
            throw new DistributorException(['cus'=>7]);
        }

        if ($jwUserId == $shareUserId) {
            throw new DistributorException(['cus' => 18]);
        }
        
        $info = Distributor::getRecord(['user_id' => $jwUserId]);
        if (!empty($info) && $info['parent_user_id'] > 0) {
            throw new DistributorException(['cus'=>8]);
        }

        if (empty($userName)) {
            throw new DistributorException(['cus'=>3]);
        }

        $detectParams = [
            'businessId' => 1,
            'text' => !empty($userName) ? $userName : '',
            'scene' => 1,
        ];

        $sensitive =  (new Sensitive)->detect($detectParams);
        if (!empty($sensitive['data'])) {
            throw new DistributorException(['cus'=>4]);
        }
 
        if (self::utf8Strlen($userName) > 40) {
            throw new DistributorException(['cus'=>13]);
        }
        Distributor::beginTransaction();

        $userCode = $jwUserId . '_' . $distributorType;
        if (empty($info)) {
            // $res = self::getIdgenId(1, 'goods', $count = 1);
            // $userCode = !empty($res[0]) ? $res[0] : '';
            //新增
            $data = [
                'parent_user_id' => $parentUserId,
                'user_id' => $jwUserId,
                'user_name' => $userName,
                'update_time' => date("Y-m-d H:i:s"),
                'create_time' => date("Y-m-d H:i:s"), 
                'distributor_code' => $userCode,
                'distributor_type' => $distributorType
            ];
            $id = Distributor::insertRecord($data);
            if (empty($id)) {
                Distributor::rollback();  
                throw new DistributorException(['cus' => 5]);
            }
        }else{
            //编辑二级团长
            $data = [
                'parent_user_id' => $parentUserId,
                'user_name' => $userName,
                'update_time' => date("Y-m-d H:i:s"),
                'create_time' => date("Y-m-d H:i:s"), 
            ];
            $id = Distributor::updateRecord($data, ['user_id' => $jwUserId,'distributor_type' => $distributorType]);
            if (empty($id)) {
                Distributor::rollback();  
                throw new DistributorException(['cus' => 5]);
            }
        }

        //暂时默认通过，
        $auditData = [
            'parent_user_id' => $parentUserId,
            'user_id' => $jwUserId,
            'user_name' => $userName,
            'distributor_type' => $distributorType,
            'status' => 2,
            'update_time' => date("Y-m-d H:i:s"),
            'create_time' => date("Y-m-d H:i:s"),
            'distributor_code' => $userCode,
        ];
        $auditId = DistributorAuditRecord::insertRecord($auditData);
        if (!empty($auditId)) {
            Distributor::commit();
            return $auditId;
        }else{
            Distributor::rollback();  
            throw new DistributorException(['cus' => 5]);
        }
    }

    /**
     * 发送短信验证码
     * 
     */
    public static function checkSmsCode($params)
    {
        $url = config('interface','service.user.check_sms_code');
        if(!$url){
            throw new CodeSpecialException("failed");
        }

        $params = [
            'mobile' => !empty($params['mobile']) ? $params['mobile'] : '',
            'appid' => !empty($params['appid']) ? $params['appid'] : 'hubble',
            'code' => !empty($params['sms_code']) ? $params['sms_code'] : '',
            'key' => 'f16bdd46292480b4b82c841d90a6ba02',
            'partner' => !empty($params['appid']) ? $params['appid'] : 'hubble',
            "scene" => "distributor"
        ];

        $sms  = (new Request())->get($url, $params);
        if(!$sms){
            throw new CodeSpecialException("timeout");
        }

        if (!empty($sms) && $sms['code'] == 0) {
            return $sms['response'];
        }else{
            return $sms;
        }
    }


    /**
     * 发送短信验证码
     * 
     */
    public static function sendSmsCode($params)
    {
        $url = config('interface','service.user.send_sms_code');
        if(!$url){
            throw new CodeSpecialException("failed");
        }

        if (empty($params)) {
            throw new CodeSpecialException("failed");
        }

        $params = [
            'mobile' => !empty($params['mobile']) ? $params['mobile'] : '',
            'appid' => !empty($params['appid']) ? $params['appid'] : 'hubble',
            'code' => '123456',
            'key' => 'f16bdd46292480b4b82c841d90a6ba02',
            'partner' => !empty($params['appid']) ? $params['appid'] : 'hubble',
            'template' =>7,
            'code_lenght' => 6,
            'ticket_expire' => 86400,
            'resend_times' => 5,
            'retry_times' => 100
        ];
    
        $sms  = (new Request())->get($url, $params);
        if(!$sms){
            throw new CodeSpecialException("timeout");
        }

        if (!empty($sms) && $sms['code'] == 0) {
            return $sms;
        }else{
            return $sms;
        }
    }

    /**
     * 是否是团长
     *
     */
    public static function distributor($params)
    {
        
        if (!empty($params['distributor_user_id'])) {
            $where['user_id'] = $params['distributor_user_id'];
        }else{
            if (empty($params['user_id'])) {
                throw new DistributorException(['cus' => 14]);
            }
            $where['user_id'] = $params['user_id'];
        }
       
        $data = [];
        $info = Distributor::getRecord($where);
        $data = $info;
        $param = [
            'user_id' => !empty($where['user_id']) ? $where['user_id'] : '',
        ];

        $jwUser = new JwUser();
        $userInfo =  $jwUser->getUserByUserId($param);
        if (!empty($userInfo) && $userInfo['result'] ==0) {
            $user = $userInfo['data'];
        }
        $data['avatar'] = !empty($userInfo['data']['avatar']) ? $userInfo['data']['avatar'] : '';
        $data['nick_name'] = !empty($userInfo['data']['nickName']) ? $userInfo['data']['nickName'] : '';
        if (!empty($info)) {
            $data['distributor_code'] = !empty($info['distributor_code']) ? $info['distributor_code'] : '';
            $data['is_distributor'] = 1;
        }else{
            $data['distributor_code'] = !empty($info['distributor_code']) ? $info['distributor_code'] : '';
            $data['is_distributor'] = 0;
        }
        return $data ;
    }


    public static function distributorCodeUrl($params)
    {
        if (empty($params['user_id'])) {
            throw new DistributorException(['cus' => 14]);
        }
        $where['user_id'] = $params['user_id'];
        $data = [];
        $info = Distributor::getRecord($where);

        $url = config('interface','goods.wx.appgc');
        if(empty($url)){
            throw new InterfaceException(['cus'=>0]);
        }
        $codeUrl = $url.'/#/tk/commander/?share_user_id='.$params['user_id'];
        $distributorCodeUrl = (new GetImage())->getLeaderShare($codeUrl);
    }




    /**
     * 查询
     * 后台管理
     */
    public static function distributorList($params)
    {
        $params['page'] = !empty($params['page']) ? $params['page'] : 1;
        $limit = !empty($params['page_size']) ? $params['page_size'] : 20;
        $page = ($params['page'] - 1) * $limit;

        if (!empty($params['audit_status'])) {
            $where['audit_status'] = $params['audit_status'];
        }

        if (!empty($params['audit_user_name'])) {
            $where['audit_user_name'] = $params['audit_user_name'];
        }

        $where['ORDER'] = ["create_time" => "DESC"];
        $where['LIMIT'] = [$page, $limit];
        $list = Distributor::getRecords($where);
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = Distributor::getCount($where);
        $data = ['result' => $list,'count' => $count];
        return $data;
    }

    public static function distributorInfo($params)
    {
        $where['distributor_id'] = !empty($params['distributor_id']) ? $params['distributor_id'] : '';
        $info = Distributor::getRecord($where);
        return $info;
    }


    public static function getDistributorList($params)
    {
        $where['user_id'] = !empty($params['user_id']) ? $params['user_id'] : '';
        $info = Distributor::getRecords($where);
        return $info;
    }


    

    /**
     * 更新数据
     *
     */
    public static function updateDistributor($params,$where)
    {
        $where['distributor_id'] = !empty($where['distributor_id']) ? $where['distributor_id'] : '';
        $info = Distributor::updateRecord($params, $where);
        return $info;
    }

   /**
    * 判断长度
    *
    * @param $string
    * @return array|mixed
    */
    public static function utf8Strlen($string = null) {
        // 将字符串分解为单元
        preg_match_all("/./us", $string, $match);
        // // 返回单元个数
        return count($match[0]);
    }
    
    /**
     * 通过发号器拿 id （非雪花）
     * number，获取店铺shop_id用生活号id后两位，商品相关的这里是shop_id的后两位
     *
     * @param $number
     * @param $type
     * @param int $count
     * @return array|mixed
     */
    public static function getIdgenId($number, $type, $count = 1)
    {
        $res = Idgen::get(appConfig('idgen.partner'), appConfig('idgen.key'), [], [[
            "type" => $type,
            'number' => (int)$number,
            "count" => $count]]);
        return $res['id_datetime'][$type] ?? [];
    }

    public static function getSnowIdgenId($type, $count = 1)
    {
        $res = Idgen::get(appConfig('idgen.partner'), appConfig('idgen.key'), [[
            "type" => $type,
            "count" => $count]], []);
        return $res['id_snow'][$type] ?? [];
    }

    /**
     * 获取团长信息
     * @param $userIds
     * @return array
     */
    public static function getDistributorInfo($userIds)
    {
        $list = Distributor::select(["parent_user_id", "user_id", "user_name"], ["user_id" => $userIds]);
        $data = [];
        if (!empty($list)) {
            foreach ($list as $item) {
                $data[$item["user_id"]] = $item;
            }
        }
        return $data;
    }
}