<?php


namespace App\Services\marketing;

use App\Models\marketing\mysql\Distributor;
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; 

class DistributorService
{    
    /**
     * 查询二级团长
     *
     */
    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'];
        }

        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];
        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]);
        if (!empty($info)) {
            throw new DistributorException(['cus'=>2]);
        }

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

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

        $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 . '_' . $type;
        $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'] : '';
        if (empty($smsCode)) {
            throw new DistributorException(['cus'=>11]);
        }

        $jwUserId = '';
        if (empty($distributorCode)) {
            throw new DistributorException(['cus'=>9]);
        }
        $info = Distributor::getRecord(['distributor_code' => $distributorCode]);

        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]);
        }
        
        $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 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' => 'hubble',
            'code' => '123456',
            'key' => 'f16bdd46292480b4b82c841d90a6ba02',
            'partner' => 'merchant-b',
            'template' =>7,
            'code_lenght' => 6,
            'ticket_expire' => 86400,
            'resend_times' => 5,
            'retry_times' => 100
        ];
    
        $sms  = (new TimeOut())->runGet($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['user_id'])) {
            throw new DistributorException(['cus' => 14]);
        }
        $where['user_id'] = $params['user_id'];
        $data = [];
        $info = Distributor::getRecord($where);

        if (!empty($info)) {
            $data['distributor_code'] = $info['distributor_code'];
            $data['is_distributor'] = 1;
        }else{
            $data['distributor_code'] = $info['distributor_code'];
            $data['is_distributor'] = 0;
        }
        return $data ;
    }




    /**
     * 查询
     * 后台管理
     */
    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 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] ?? [];
    }
}