<?php

namespace App\Http\Controllers\Api\Third;

use App\Http\Controllers\Api\ApiBaseController;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
use App\Models\HukeCallback;
use App\Models\Member;
use App\Models\MemberShuobo;
use App\Services\Auth\RegisterService;

class ScrmController extends ApiBaseController
{
    /**
     * @var Client
     */
    private $httpClient;
    private $app_key;
    private $app_secret;
    private $registerService;

    /**
     * SmsService constructor.
     * @param $app_key
     * @param $app_secret
     * @param $sign_key
     */
    public function __construct(RegisterService $registerService)
    {
        $this->app_key = '817267c4c2f3476b863522525b97ac78';
        $this->app_secret = '559f778b1b4f4e47b0265fa5fbedfb54';

        $this->httpClient=new Client([
            'http_errors' => false
        ]);
        $this->registerService = $registerService;
    }

    public function pullData(Request $request)
    {
        $log = [
            'content'      =>  serialize($request->all()),
        ];
        HukeCallback::create($log);
        $data = $request->all();
        //$fields = $this->get_customer_fields();
        switch ($data['type']){
            case '1011':
                $param = json_decode($data['params']['customerEvent'],true);
                $res = $this->get_customer_query(3,[$param['cid']]);//根据返回的cid查询用户信息
                if($res){//查询成功

                    $customer = $this->format_user($res[0]);
                    $customer['cid'] = $param['cid'];
                    switch ($customer['label']){
                        case '硕博人才':
                            $user = Member::where('mobile',$customer['mobile'])->first();
                            if(!$user){
                                //手机号找不到聚才网账户,进行注册并入库
                                $user = $this->registerService->registerPersonScrm($customer);
                            }else{
                                //如果有账户,查找scrm_id字段并更新
                                if(empty($user->scrm_id)){
                                    $user->scrm_id = $param['cid'];
                                    $user->save();
                                }
                            }
                            //如果手机号在聚才网已存在账户,将信息入库
                            $shuobo_exist = MemberShuobo::where('uid',$user->id)->first();
                            $shuobo_data = array_only($customer,['uid','realname','sex','mobile','email','birthday','education','school','pro','graduation_time','address','country','weixin','company','job','come_in_time','require','trade_type','speciality']);
                            $shuobo_data['cid'] = $param['cid'];
                            if(!$shuobo_exist){
                                $shuobo_data['uid'] = $user->id;
                                MemberShuobo::create($shuobo_data);
                            }else{
                                MemberShuobo::where('uid',$user->id)->update($shuobo_data);
                            }

                            break;
                    }

                }
                break;
        }
    }

    public function get_customer_fields($update = false)
    {
        if(!$update){
            if(Cache::has("huke_customer_fields")){
                return Cache::get("huke_customer_fields");
            }
        }
        $params = [];
        $params = json_encode($params);
        $appSecret = substr(openssl_digest(openssl_digest($this->app_secret, 'sha1', true), 'sha1', true), 0, 16);
        $time = time();
        $sign = md5($params);
        $checksum = bin2hex(openssl_encrypt($this->app_key. $sign. $time, 'AES-128-ECB', $appSecret, OPENSSL_RAW_DATA));
        $headers = [
            'Content-Type' => 'application/json',
            'ur-appkey' => $this->app_key,
            'ur-sign' => $sign,
            'ur-curtime' => $time,
            'ur-checksum' => $checksum
        ];

        $response = $this->httpClient->post('https://huke.163.com/openapi/customer/fields', ['body'=>$params,'headers' => $headers]);
        $res = json_decode($response->getBody()->getContents(),true);
        $fields = [];
        foreach ($res['data'] as $k => $v){
            if(array_key_exists('options',$v)){
                $options = [];
                foreach ($v['options'] as $key => $val){
                    $options[$val['id']] = $val;
                }
                $v['options'] = $options;
            }
            $fields[$v['id']] = $v;
        }
        Cache::put('huke_customer_fields',$fields,'86400');
        return $fields;

    }

    /**
     * 查询客户列表
     * @param $start
     * @param $end
     * @param $page
     * @param $page_size
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function get_customer_list($start,$end,$page,$page_size)
    {
        $params = [
            'startTime' => str_pad(strtotime($start),13,'0',STR_PAD_RIGHT),
            'endTime' => str_pad(strtotime($end),13,'0',STR_PAD_RIGHT),
            'page'=>$page,
            'pageSize'=>$page_size
        ];
        $params = json_encode($params);
        $appSecret = substr(openssl_digest(openssl_digest($this->app_secret, 'sha1', true), 'sha1', true), 0, 16);
        $time = time();
        $sign = md5($params);
        $checksum = bin2hex(openssl_encrypt($this->app_key. $sign. $time, 'AES-128-ECB', $appSecret, OPENSSL_RAW_DATA));
        $headers = [
            'Content-Type' => 'application/json',
            'ur-appkey' => $this->app_key,
            'ur-sign' => $sign,
            'ur-curtime' => $time,
            'ur-checksum' => $checksum
        ];

        $response = $this->httpClient->post('https://huke.163.com/openapi/customer/list', ['body'=>$params,'headers' => $headers]);
        $res = json_decode($response->getBody()->getContents(),true);
        dd($res);
    }

    /**
     * 格式化互客用户信息
     * @param array $data
     */
    public function format_user(array $data)
    {
        $user = [];
        $fields = $this->get_customer_fields();
        if(is_array($data['customFields'])){
            foreach ($data['customFields'] as $k => $v){
                switch ($v['id']){
                    case -1:
                        $user['avatars'] = $v['fieldValue'];
                        break;
                    case -2:
                        $user['realname'] = $v['fieldValue'];
                        break;
                    case -3:
                        $user['mobile'] = $v['fieldValue'];
                        break;
                    case -4:
                        $user['email'] = $v['fieldValue'];
                        break;
                    case -5:
                        $user['weixin'] = $v['fieldValue'];
                        break;
                    case -6:
                        $user['wechat_name'] = $v['fieldValue'];
                        break;
                    case -7:
                        $user['sex'] = $fields[-7]['options'][$v['fieldValue']]['optionValue'];
                        break;
                    case -8:
                        $user['area'] = $v['fieldValue'];
                        break;
                    case -9:
                        $user['tel'] = $v['fieldValue'];
                        break;
                    case -10:
                        $user['tel_ex'] = $v['fieldValue'];
                        break;
                    case 10018777:
                        $user['label'] = $fields[10018777]['options'][$v['fieldValue']]['optionValue'];
                        break;
                    case 10019746:
                        $user['address'] = $v['fieldValue'];
                        break;
                    case 10019747:
                        $user['trade'] = $v['fieldValue'];
                        break;
                    case 10019748:
                        $user['company'] = $v['fieldValue'];
                        break;
                    case 10020717:
                        $user['job'] = $v['fieldValue'];
                        break;
                    case 10018778:
                        $user['birthday'] = $v['fieldValue'];
                        break;
                    case 10019749:
                        $user['origin'] = $fields[10019749]['options'][$v['fieldValue']]['optionValue'];
                        break;
                    case 10018779:
                        $user['remark'] = $v['fieldValue'];
                        break;
                    case 10018780:
                        $user['attachment'] = $v['fieldValue'];
                        break;
                    case 10019750:
                        $user['cid'] = $v['fieldValue'];
                        break;
                    case 10019751:
                        $user['age_range'] =  $fields[10019751]['options'][$v['fieldValue']]['optionValue'];
                        break;
                    case 10019765:
                        $user['age'] = $v['fieldValue'];
                        break;
                    case 10031724:
                        $user['level'] = $fields[10031724]['options'][$v['fieldValue']]['optionValue'];
                        break;
                    case 10051871:
                        $user['edu'] = $v['fieldValue'];
                        break;
                    case 15293060:
                        $user['politic_countenance'] = $fields[15293060]['options'][$v['fieldValue']]['optionValue'];
                        break;
                    case 15353563:
                        $user['education'] = $fields[15353563]['options'][$v['fieldValue']]['optionValue'];
                        break;
                    case 15352635:
                        $user['school'] = $v['fieldValue'];
                        break;
                    case 15355464:
                        $user['pro'] = $v['fieldValue'];
                        break;
                    case 15354507:
                        $user['graduation_time'] = date("Y-m-d",$v['fieldValue']/1000);
                        break;
                    case 15352636:
                        $user['country'] = $v['fieldValue'];
                        break;
                    case 15352650:
                        $user['come_in_time'] = date("Y-m-d",$v['fieldValue']/1000);
                        break;
                    case 15353579:
                        $user['require'] = $fields[15353579]['options'][$v['fieldValue']]['optionValue'];
                        break;
                    case 15353580:
                        $user['trade_type'] = $v['fieldValue'];
                        break;
                    case 15355480:
                        $user['speciality'] = $v['fieldValue'];
                        break;
                }
            }
        }
        return $user;
    }

    /**
     * @param int $type 0-手机,1-微信号, 2-邮箱,3-cid  4-唯一ID,5-姓名,6-公司/客户名称,7-微信unionId
     * @param array $value 对应查询类型的字段列表,数量不能超过100
     */
    public function get_customer_query(int $type,array $value)
    {
        if($type < 0 || $type > 7)
        {
            return false;
        }
        if(count($value) < 1){
            return false;
        }
        $params = [
            'type' => $type,
            'targets' => $value
        ];
        $params = json_encode($params);
        $appSecret = substr(openssl_digest(openssl_digest($this->app_secret, 'sha1', true), 'sha1', true), 0, 16);
        $time = time();
        $sign = md5($params);
        $checksum = bin2hex(openssl_encrypt($this->app_key. $sign. $time, 'AES-128-ECB', $appSecret, OPENSSL_RAW_DATA));
        $headers = [
            'Content-Type' => 'application/json',
            'ur-appkey' => $this->app_key,
            'ur-sign' => $sign,
            'ur-curtime' => $time,
            'ur-checksum' => $checksum
        ];

        $response = $this->httpClient->post('https://huke.163.com/openapi/customer/query', ['body'=>$params,'headers' => $headers]);
        $res = json_decode($response->getBody()->getContents(),true);
        return $res['data'];
    }

    public function get_customer_events(int $cid,$startTime,$endTime,$page,$pageSize){
        $params = [
            'cid' => $cid,
            'startTime' => $startTime,
            'endTime' => $endTime,
            'page'=>$page,
            'pageSize'=>$pageSize
        ];
        $params = json_encode($params);
        $appSecret = substr(openssl_digest(openssl_digest($this->app_secret, 'sha1', true), 'sha1', true), 0, 16);
        $time = time();
        $sign = md5($params);
        $checksum = bin2hex(openssl_encrypt($this->app_key. $sign. $time, 'AES-128-ECB', $appSecret, OPENSSL_RAW_DATA));
        $headers = [
            'Content-Type' => 'application/json',
            'ur-appkey' => $this->app_key,
            'ur-sign' => $sign,
            'ur-curtime' => $time,
            'ur-checksum' => $checksum
        ];

        $response = $this->httpClient->post('https://huke.163.com/openapi/customer/getCustomerEvents', ['body'=>$params,'headers' => $headers]);
        $res = json_decode($response->getBody()->getContents(),true);

        return $res;
    }

    public function test()
    {
        /*===========客户旅程==============*/
        $params = [
            'cid' => 42832294,
            'startTime' => str_pad(strtotime('2021-11-01'),13,'0',STR_PAD_RIGHT),
            'endTime' => str_pad(strtotime('2021-11-30'),13,'0',STR_PAD_RIGHT),
            'page'=>2,
            'pageSize'=>50
        ];
        $params = json_encode($params);
        $appSecret = substr(openssl_digest(openssl_digest($this->app_secret, 'sha1', true), 'sha1', true), 0, 16);
        $time = time();
        $sign = md5($params);
        $checksum = bin2hex(openssl_encrypt($this->app_key. $sign. $time, 'AES-128-ECB', $appSecret, OPENSSL_RAW_DATA));
        $headers = [
            'Content-Type' => 'application/json',
            'ur-appkey' => $this->app_key,
            'ur-sign' => $sign,
            'ur-curtime' => $time,
            'ur-checksum' => $checksum
        ];

        $response = $this->httpClient->post('https://huke.163.com/openapi/customer/getCustomerEvents', ['body'=>$params,'headers' => $headers]);
        $res = json_decode($response->getBody()->getContents(),true);

        return $res;

        dd($res);

//        $curl = curl_init();
//        curl_setopt($curl, CURLOPT_URL, 'https://www.jucai.gov.cn/api/scrm/data');
//        //设置头文件的信息作为数据流输出
//        curl_setopt($curl, CURLOPT_HEADER, 0);
//        //设置获取的信息以文件流的形式返回,而不是直接输出。
//        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//        // 超时设置
//        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
//
//        // 超时设置,以毫秒为单位
//        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
//
//        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE );
//        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE );
//
//        //设置post方式提交
//        curl_setopt($curl, CURLOPT_POST, 1);
//        $post = [
//            'eid' => '1000459',
//            'type' => '1011',
//            'cid' => '108720798',
//            'params' => [
//                'customerEvent' => '{"id":1687628552,"eid":1000459,"cid":110762053,"createTime":1637073249037,"eventCode":309,"eventName":"更新客户资料","fieldList":[{"value":"中国福建泉州","name":"15352636"},{"value":"1656604800000","name":"15352650"},{"value":"1656604800000","name":"15354507"}]}'
//            ]
//        ];
//        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
//        //执行命令
//        $data = curl_exec($curl);
//        dd($data);
        $params = [
            'type' => 3,
            'targets' => [
                '110762053'
            ]
        ];
        $params = json_encode($params);
        $appSecret = substr(openssl_digest(openssl_digest($this->app_secret, 'sha1', true), 'sha1', true), 0, 16);
        $time = time();
        $sign = md5($params);
        $checksum = bin2hex(openssl_encrypt($this->app_key. $sign. $time, 'AES-128-ECB', $appSecret, OPENSSL_RAW_DATA));
        $headers = [
            'Content-Type' => 'application/json',
            'ur-appkey' => $this->app_key,
            'ur-sign' => $sign,
            'ur-curtime' => $time,
            'ur-checksum' => $checksum
        ];

        $response = $this->httpClient->post('https://huke.163.com/openapi/customer/query', ['body'=>$params,'headers' => $headers]);
        $res = json_decode($response->getBody()->getContents(),true);

        dd($res);
    }
}