<?php
/**
 * Created by PhpStorm.
 * User: zilongs
 * Date: 20-9-23
 * Time: 上午11:26
 */

namespace App\Http\Controllers\Api\V2;

use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Models\Order;
use App\Models\User;
use App\Models\Docter;
use EasyWeChat\Factory;
use http\Env\Request;
use Illuminate\Support\Facades\DB;
use AlibabaCloud\Client\Exception\ClientException;
use Alibabaloud\Client\Exception\ServerException;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Dybaseapi\MNS\Requests\BatchReceiveMessage;
use AlibabaCloud\Dybaseapi\MNS\Requests\BatchDeleteMessage;
use App\Models\CallLog;
use App\Models\Axb;
use App\Models\ImMessage;
use Cache;


/**
 * 公共方法类
 * Class CommonController
 * @package App\Http\Controllers\Api\V2
 */
class CommonController extends Controller
{
    public function wxLogin()
    {
        $req = request()->post();
        $this->validate(request(), [
            'wechat_code' => 'required',
            'nickname|昵称' => 'max:50',
            'avatar|头像' => 'url',
            'latitude|纬度' => 'numeric',
            'longitude|纬度' => 'numeric',
        ]);

        $app = Factory::miniProgram(config('config.docter_wechat_small_program'));

        $data = $app->auth->session($req['wechat_code']);

        if (empty($data['openid'])){
            return out(null, 10001, '微信登录code错误');
        }

        $session_key = !empty($data['session_key']) ? $data['session_key'] : '';

        $user = User::select(['id', 'status', 'phone', 'nickname', 'avatar'])->where('openid', $data['openid'])->first();
        if (empty($user)){
            $user = User::create([
                'openid' => $data['openid'],
                'nickname' => $req['nickname'] ?? '',
                'avatar' => $req['avatar'] ?? '',
                'latitude' => $req['latitude'] ?? 0,
                'longitude' => $req['longitude'] ?? 0,
                'session_key' => $session_key
            ]);
        }
        else {
            if ($user['status'] == 0) {
                return out(null, 10002, '该账号已被冻结');
            }

            User::where('id', $user['id'])->update([
                'nickname' => $req['nickname'] ?? '',
                'avatar' => $req['avatar'] ?? '',
                'latitude' => $req['latitude'] ?? 0,
                'longitude' => $req['longitude'] ?? 0,
                'session_key' => $session_key
            ]);
        }
        // 查询医生表有没有记录
        $doct = User::where('openid',$data['openid'])->orderBy('id','desc')->first();

        if ($doct['phone']!=''){
            $list = Docter::where('phone',$doct['phone'])->orderBy('id','desc')->first();
            if ($list){
                if ($list['status'] == 0) {
                    return out(null, 10002, '该账号已被冻结');
                }
                $datas = [
                    'avatar' => $list['avatar'],
                    'name' => $list['name'],
                    'flag' => 'doctor_'.$list['id'],
                ];
                $token = aes_encrypt(['doctor_id' => $list['id'], 'time' => time()]);
                return out(['token' => $token,'data'=>$datas]);
            }else{
                return out(['session_key'=>$session_key,'openid'=>$data['openid']]);
            }
        }else{
            return out(['session_key'=>$session_key,'openid'=>$data['openid']]);
        }
    }

    /**
     * 获取手机号！
     * Auth:Yuanhang-Liu
     * Date:2020/10/18 17:17 *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPhoneNumber(){
        $req = request()->post();
        $this->validate(request(), [
            'iv' => 'required',
            'encryptedData' => 'required',
            'session_key' => 'required',
            'openid' => 'required',
        ]);


        $app = Factory::miniProgram(config('config.docter_wechat_small_program'));
//        $data = $app->auth->session($req['code']);
//        if (empty($data['openid'])){
//            return out(null, 10001, '微信登录code错误');
//        }
        $session_key = !empty($req['session_key']) ? $req['session_key'] : '';
        $user = User::select(['id','sex', 'status', 'phone', 'birthday','nickname', 'avatar','status'])->where('openid', $req['openid'])->first();
        if (!$user){
            return out(['status'=>false,'msg' => '用户不存在！']);
        }


        $decryptedData = $app->encryptor->decryptData($session_key, $req['iv'], $req['encryptedData']);
        if (!isset($decryptedData['phoneNumber']) || empty($decryptedData['phoneNumber'])){
            return out(['status'=>false,'msg' => '手机号解密失败！']);
        }


        $docter_list = [
            'type' => 1,
            'name' => $user['nickname'],
            'phone' => $decryptedData['phoneNumber'],
            'sex' => $user['sex'],
            'birthday' => $user['birthday'],
            'avatar' => $user['avatar'],
            'status' => 1,
            'label' => '无',
            'sign' => '无',
            'intro' => 0,
            'office_id' => 0,
            'qualification_id' => 0,
            'score' => 0,
            'service_persons' => 0,
            'eva_num' => 0,
            'service_days' => 0,
            'phone_minutes' => 0,
            'chat_price' => 0,
            'phone_price' => 0,
            'appoint_price' => 0,
            'is_chat' => 0,
            'is_phone' => 0,
            'is_appoint' => 0,
            'latitude' => 0,
            'longitude' => 0,
            'is_then' => 0,
            'practice' => 0,
            'card_photo' => 0,
            'is_quail' => 0,
            'card_id' => 0,
        ];
        // 查询医生表有没有记录
        $doct = Docter::where('phone',$decryptedData['phoneNumber'])->orderBy('id','desc')->first();

        if ($doct){
            if ($doct['status'] == 0) {
                return out(null, 10002, '该账号已被冻结');
            }
            $datas = [
                'avatar' => $doct['avatar'],
                'name' => $doct['name'],
                'flag' => 'doctor_'.$doct['id'],
            ];
            $token = aes_encrypt(['doctor_id' => $doct['id'], 'time' => time()]);
            return out(['token' => $token,'data'=>$datas]);
        }
        $list=[];
        if ($user){
            DB::beginTransaction();
            try {
                User::where('openid', $req['openid'])->update([
                    'phone' => $decryptedData['phoneNumber'] ?? '','is_docter'=>1,
                ]);
                // 注册医生
                $list = Docter::create($docter_list);
                DB::commit();
            }catch (\Exception $e){
                DB::rollback();
                return out(null, 500, $e->getMessage());
            }catch (\PDOException $e){
                DB::rollback();
                return out(null, 500, $e->getMessage());
            }
        }

        $datas = [
            'avatar' => $list['avatar'],
            'name' => $list['name'],
            'flag' => 'doctor_'.$list['id'],
        ];
        $token = aes_encrypt(['doctor_id' => $list['id'], 'time' => time()]);
        return out(['token' => $token,'data'=>$datas]);

    }

    /**
     * 手机号登陆
     * Auth:Yuanhang-Liu
     * Date:2020/10/18 19:17 *
     * @return \Illuminate\Http\JsonResponse
     */
    public function phoneLogin(){
        $req = request()->post();
        $this->validate(request(), [
            'phone|手机号' => 'required|integer',
        ]);
        $req['verify'] = 0;
        $find = Docter::where('phone','=',$req['phone'])->first();

        if (empty($find)){
            $docter_list = [
                'type' => 1,
                'name' => '用户名',
                'phone' => $req['phone'],
                'sex' => 0,
                'birthday' => 0,
                'avatar' => '../../static/login/moren.png',
                'status' => 1,
                'label' => '无',
                'sign' => '无',
                'intro' => 0,
                'office_id' => 0,
                'qualification_id' => 0,
                'score' => 0,
                'service_persons' => 0,
                'eva_num' => 0,
                'service_days' => 0,
                'phone_minutes' => 0,
                'chat_price' => 0,
                'phone_price' => 0,
                'appoint_price' => 0,
                'is_chat' => 0,
                'is_phone' => 0,
                'is_appoint' => 0,
                'latitude' => 0,
                'longitude' => 0,
                'is_then' => 0,
                'practice' => 0,
                'card_photo' => 0,
                'is_quail' => 0,
                'card_id' => 0,
            ];
            $list = Docter::create($docter_list)->toArray();
            if (!empty($list)){
                $datas = [
                    'avatar' => $list['avatar'],
                    'name' => $list['name'],
                    'flag' => 'doctor_'.$list['id'],
                ];
                $token = aes_encrypt(['doctor_id' => $list['id'], 'time' => time()]);
                return out(['token' => $token,'data'=>$datas]);
            }else{
                return out('',401,'用户不存在,注册失败！');
            }
        }

        $find = $find->toArray();
        if ($find['status'] == 0) {
            return out(null, 10002, '该账号已被冻结');
        }
        if ($req['verify']==0){
            $datas = [
                'avatar' => $find['avatar'],
                'name' => $find['name'],
                'flag' => 'doctor_'.$find['id'],
            ];
            // 验证是否正确
            $token = aes_encrypt(['doctor_id' => $find['id'], 'time' => time()]);
            return out(['token' => $token,'data'=>$datas]);
        }else{
            return out(null, 401, '验证码错误');

        }

    }

    /**
     * 账号密码登陆
     * Auth:Yuanhang-Liu
     * Date:2020/10/18 19:17 *
     * @return \Illuminate\Http\JsonResponse
     */
    public function passLogin(){
        $req = request()->post();
        $this->validate(request(), [
            'phone|手机号' => 'required|integer',
            'password|密码' => 'required',
        ]);
        $find = Docter::where('phone','=',$req['phone'])->first();
        if (empty($find)){
            return out(null, 401, '账号不存在');
        }
        if ($find['status'] == 0) {
            return out(null, 10002, '该账号已被冻结');
        }
        $find = $find->toArray();
        // 验证密码
        $password = md5(md5(md5($req['password'])));
        if ($password==$find['password']){

            $datas = [
                'avatar' => $find['avatar'],
                'name' => $find['name'],
                'flag' => 'doctor_'.$find['id'],
            ];
            $token = aes_encrypt(['doctor_id' => $find['id'], 'time' => time()]);

            return out(['token' => $token,'data'=>$datas]);
        }else{
                return out(null, 401, '密码错误');
        }
    }

    /**
     * 获取验证码
     * @return \Illuminate\Http\JsonResponse
     * @author Liu-Yh
     * Create By 2020/11/6 10:45
     */
    public function putverfiy(){

        //防止恶意刷验证码接口，一分钟最多10次
        check_repeat_request(60, 10);
        $req = request()->post();
        $this->validate(request(), [
            'phone|手机号' => 'required|integer',
        ]);
        $mobile =$req['phone']; //获取传入的手机号
        $verify_code = generate_code();
        $result = send_sms($mobile,'verify_template_code',['code'=>$verify_code]);
        if (empty($result['Code']) || $result['Code'] != 'OK'){
            return out(null, 30010, '验证码发送失败，请稍后重试');
        }
        Cache::set($req['phone'].'-', $verify_code, config('config.aly_sms.sms_verify_code_expire'));

        return out();
    }

    /**
     * 手机号注册
     * Auth:Yuanhang-Liu
     * Date:2020/10/18 20:17 *
     * @return \Illuminate\Http\JsonResponse
     */
    public function phoneRegister(){
        $req = request()->post();
        $this->validate(request(), [
            'phone|手机号' => 'required|integer',
            'password|密码' => 'required',
        ]);

        // 查询是否注册过！
        $docters = Docter::where('phone','=',$req['phone'])->first();

        if (!empty($docters)){
            return out('',500,'此手机号已被注册！');
        }

        $password = md5(md5(md5($req['password'])));
        $docter_list = [
            'type' => 1,
            'name' => '用户名',
            'phone' => $req['phone'],
            'sex' => 0,
            'birthday' => 0,
            'avatar' => '无',
            'status' => 1,
            'label' => '无',
            'sign' => '',
            'intro' => '',
            'office_id' => 0,
            'qualification_id' => 0,
            'score' => 0,
            'service_persons' => 0,
            'eva_num' => 0,
            'service_days' => 0,
            'phone_minutes' => 0,
            'chat_price' => 0,
            'phone_price' => 0,
            'appoint_price' => 0,
            'is_chat' => 0,
            'is_phone' => 0,
            'is_appoint' => 0,
            'latitude' => 0,
            'longitude' => 0,
            'password' => $password,
            'is_then' => 0,
            'practice' => 0,
            'card_photo' => 0,
            'is_quail' => 0,
            'card_id' => 0,
        ];
        $list = Docter::create($docter_list)->toArray();
        if (!empty($list)){

            $datas = [
                'avatar' => $list['avatar'],
                'name' => $list['name'],
                'flag' => 'doctor_'.$list['id'],
            ];
            $token = aes_encrypt(['doctor_id' => $list['id'], 'time' => time()]);
            return out(['token' => $token,'data'=>$datas]);
        }else{
            return out('',500,'注册失败！');
        }

//        return out();
    }

    public function articleList()
    {
        $data = Article::orderBy('id', 'desc')->paginate();

        return out($data);
    }

    public function getUserIdByDoctorId($phone=null){
        $list = Docter::where('phone', $phone)->first();
        if ($list){
            return $list->id;
        }else{
            return false;
        }
    }

    public function uploadFile()
    {
        $file = request()->file('file');
        if (empty($file)) {
            return out(null, 10001, '文件不能为空');
        }

        $path = $file->store('uploads/'.date('Ymd'));
//        $url = request()->getScheme().'://'.request()->getHost().'/'.$path;

        return out(['url' => $path]);
    }

    public function doc()
    {
        $database = env('DB_DATABASE');
        $prefix = env('DB_PREFIX');
        $exclude_tables = "'bm_password_resets','bm_admin_menu','bm_admin_users','bm_failed_jobs','bm_migrations'";

        $sql = "select TABLE_NAME name,TABLE_COMMENT comment from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='".$database."' and TABLE_NAME not in (".$exclude_tables.")";
        $tables = \DB::select($sql);
        $map1 = $map2 = [];
        $i = round(count($tables)/2);
        foreach ($tables as $k => $v) {
            $name = str_replace($prefix, '', $v->name);
            if ($k >= $i) {
                $map1[$v->name] = $name.'('.$v->comment.')';
            }
            else {
                $map2[$v->name] = $name.'('.$v->comment.')';
            }
        }

        $data1 = [];
        foreach ($map1 as $k => $v){
            $sql = "select COLUMN_NAME name, DATA_TYPE type, COLUMN_COMMENT comment from INFORMATION_SCHEMA.COLUMNS where table_schema = '".$database."' AND table_name = '".$k."'";
            $comment = \DB::select($sql);
            $data1[$v] = $comment;
        }

        $data2 = [];
        foreach ($map2 as $k => $v){
            $sql = "select COLUMN_NAME name, DATA_TYPE type, COLUMN_COMMENT comment from INFORMATION_SCHEMA.COLUMNS where table_schema = '".$database."' AND table_name = '".$k."'";
            $comment = \DB::select($sql);
            $data2[$v] = $comment;
        }

        return view('doc', ['data1' => $data1, 'data2' => $data2]);
    }


    /**
     * 绑定号码池子
     * @param string $phone1 医生id
     * @param string $phone2 用户id
     * @param array $data 参数
     * @return mixed
     */
    public function BindAxb($phone1,$phone2,$data=[]){
        $config = config('config.axb');
        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
            ->regionId('cn-kunming')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dyplsapi')
                ->version('2017-05-25')
                ->action('BindAxb')
                ->method('POST')
                ->host('dyplsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        "Expiration" => date("Y-m-d H:i:s",strtotime("+1 day")),
                        'RegionId' => "cn-kunming",
                        'PhoneNoA' => $phone1,
                        'PhoneNoB' => $phone2,
                    ],
                ])
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }

    /**
     * 释放虚拟号码
     * @param int $phone
     */
    public function ReleaseSecretNo($phone){
        $config = config('config.axb');
        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
            ->regionId('cn-kunming')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dyplsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('ReleaseSecretNo')
                ->method('POST')
                ->host('dyplsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-kunming",
                        "SecretNo" => $phone,
                        "PoolKey" => $config['PoolKey'],
                    ],
                ])
                ->request();
            $res = $result->toArray();
           return $res;

        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }


    /**
     * 查询号码关系
     * @param $phone
     * @return mixed
     */
    public function QuerySubscriptionDetail($phone,$SubsId){
        $config = config('config.axb');
        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
            ->regionId('cn-kunming')
            ->asDefaultClient();

        try {

            $result = AlibabaCloud::rpc()
                ->product('Dyplsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('QuerySubscriptionDetail')
                ->method('POST')
                ->host('dyplsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        "PoolKey" => $config['PoolKey'],
                        "SubsId" => $SubsId,
                        "PhoneNoX" => $phone,

                    ],
                ])
                ->request();

            $res = $result->toArray();
           return $res;

        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }


    /**
     * 解除绑定关系
     * @param $phone
     * @return mixed
     */
    public function UnbindSubscription($phone,$subId){
        $config = config('config.axb');
        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
            ->regionId('cn-kunming')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dyplsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('UnbindSubscription')
                ->method('POST')
                ->host('dyplsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-kunming",
                        'SubsId' => $subId,
                        "SecretNo" => $phone,
                        "PoolKey" => $config['PoolKey'],
                    ],
                ])
                ->request();
            $res = $result->toArray();
            return $res;
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }


    /**
     * 调用接口QuerySubsId查询绑定唯一标识SubsId
     * @param $phone X号码
     * @return mixed
     */
    public function QuerySubsId($phone){
        $config = config('config.axb');
        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
            ->regionId('cn-kunming')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dyplsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('QuerySubsId')
                ->method('POST')
                ->host('dyplsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'Action' => "QuerySubsId",
                        "PhoneNoX" => $phone,
                        "PoolKey" => $config['PoolKey'],
                    ],
                ])
                ->request();
            $res = $result->toArray();
            return $res;
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }


    /**
     * 解锁号码
     * @return \Illuminate\Http\JsonResponse
     * @author Liu-Yh
     * Create By 2020/11/25 18:36
     */
    public function unLokPhone($phone,$SubsId){
        $unlok = $this->UnbindSubscription($phone,$SubsId);
        if ($unlok['Code']!='OK'){
            return out($unlok);
        }else{
            return 1;
        }
    }

    /**
     * 测试解除绑定电话的方法
     */
    public function testunlockphone(){
        $phone = 17052201940;
        $sub_id = 1000027059330181;
        var_dump($this->unLokPhone($phone,$sub_id));

    }

    /**
     * 调用接口QueryCallStatus查询呼叫状态。
     * @param $phone
     * @author Liu-Yh
     * Create By 2020/11/26 10:51
     */
    public function QueryCallStatus($phone,$SubsId){
        $config = config('config.axb');
        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
            ->regionId('cn-kunming')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dyplsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('QueryCallStatus')
                ->method('POST')
                ->host('dyplsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        "PoolKey" => $config['PoolKey'],
                        "SubsId" => $SubsId,
                    ],
                ])
                ->request();
            $res = $result->toArray();
            return $res;
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }

    }


    /**
     * 接收通话发起时的通话记录报告内容，可以在呼叫发起时立即获取到通话记录信息，包括通话开始时间、主被叫号码等，便于平台进行预判处理
     * @author Liu-Yh
     * Create By 2020/11/25 14:44
     */
    public function StartSecretReport(){
        $config = config('config.axb');
        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
            ->regionId('cn-kunming')
            ->asDefaultClient();
        $queueName = $config['StartReport']; // 队列名称
        $messageType = "SecretStartReport"; // 需要接收的消息类型
        $response = null;
        $token = null;
        $i = 0;
        do {
            try {
                if (null == $token || strtotime($token['ExpireTime']) - time() > 2 * 60) {
                    $response = AlibabaCloud::rpcRequest()
                        ->product('Dybaseapi')
                        ->version('2017-05-25')
                        ->action('QueryTokenForMnsQueue')
                        ->method('POST')
                        ->host("dybaseapi.aliyuncs.com")
                        ->options([
                            'query' => [
                                'MessageType' => $messageType,
                                'QueueName' => $queueName,
                            ],
                        ])
                        ->request()
                        ->toArray();
                }
                $token = $response['MessageTokenDTO'];
                $mnsClient = new \AlibabaCloud\Dybaseapi\MNS\MnsClient(
                    "http://1943695596114318.mns.cn-hangzhou.aliyuncs.com",
                    $token['AccessKeyId'],
                    $token['AccessKeySecret'],
                    $token['SecurityToken']
                );
                $mnsRequest = new BatchReceiveMessage(10, 5);
                $mnsRequest->setQueueName($queueName);
                $mnsResponse = $mnsClient->sendRequest($mnsRequest);
                $receiptHandles = Array();
                foreach ($mnsResponse->Message as $message) {
                    // 用户逻辑：
                    // 入库
//                    var_dump(base64_decode($message->MessageBody));
//                    var_dump(json_decode(base64_decode($message->MessageBody),true));

//                    $receiptHandles[] = $message->ReceiptHandle; // 加入$receiptHandles数组中的记录将会被删除
                    $messageBody = json_decode(base64_decode($message->MessageBody),true); // base64解码后的JSON字符串
                    echo "进来了";

                    var_dump($messageBody);
                }

                if (count($receiptHandles) > 0) {
                    $deleteRequest = new BatchDeleteMessage($queueName, $receiptHandles);
                    $mnsClient->sendRequest($deleteRequest);
                }
            } catch (ClientException $e) {
                echo $e->getErrorMessage() . PHP_EOL;
            } catch (ServerException $e) {
                if ($e->getCode() == 404) {
                    $i++;
                }
                echo $e->getErrorMessage() . PHP_EOL;
            }
        } while ($i < 3);
    }



    /**
     * 接收通话结束时的通话记录报告内容，可以在呼叫结束后获取通话记录信息，包括通话开始时间、通话结束时间、主被叫号码等，
     * @author Liu-Yh
     * Create By 2020/11/25 12:29
     */
    public function SecretPullReport(){
        $config = config('config.axb');
        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
            ->regionId('cn-kunming')
            ->asDefaultClient();
        $queueName = $config['Report']; // 队列名称
        $messageType = "SecretReport"; // 需要接收的消息类型
        $response = null;
        $token = null;
        $i = 0;
        do {
            try {
                if (null == $token || strtotime($token['ExpireTime']) - time() > 2 * 60) {
                    $response = AlibabaCloud::rpcRequest()
                        ->product('Dybaseapi')
                        ->version('2017-05-25')
                        ->action('QueryTokenForMnsQueue')
                        ->method('POST')
                        ->host("dybaseapi.aliyuncs.com")
                        ->options([
                            'query' => [
                                'MessageType' => $messageType,
                                'QueueName' => $queueName,
                            ],
                        ])
                        ->request()
                        ->toArray();
                }
                $token = $response['MessageTokenDTO'];
                $mnsClient = new \AlibabaCloud\Dybaseapi\MNS\MnsClient(
                    "http://1943695596114318.mns.cn-hangzhou.aliyuncs.com",
                    $token['AccessKeyId'],
                    $token['AccessKeySecret'],
                    $token['SecurityToken']
                );
                $mnsRequest = new BatchReceiveMessage(10, 5);
                $mnsRequest->setQueueName($queueName);
                $mnsResponse = $mnsClient->sendRequest($mnsRequest);
                $receiptHandles = Array();
                $getList = CallLog::get();
                if ($getList){
                    $getList = $getList->toArray();
                }
                $msgs = $mnsResponse->Message;
                if (!is_array($msgs)){
                    $messageBody = json_decode(base64_decode($msgs->MessageBody),true); // base64解码后的JSON字符
                    if (count($getList)==0){
                        CallLog::create([
                            'call_time'=>$messageBody['call_time'],
                            'ring_time'=>$messageBody['release_time'],
                            'release_dir'=>$messageBody['release_dir'],
                            'call_type'=>$messageBody['call_type'],
                            'aphone'=>$messageBody['phone_no'],
                            'bphone'=>$messageBody['peer_no'],
                            'call_id'=>$messageBody['call_id'],
                            'secret_no'=>$messageBody['secret_no'],
                            'sub_id'=>$messageBody['sub_id'],
                            'talk_time'=> strtotime($messageBody['release_time'])-strtotime($messageBody['start_time']),
                        ]);
                    }else{
                        foreach ($getList as $k=>$v){
                            if ($v['call_id']==$messageBody['call_id']){
                                unset($messageBody);
                            }else{
                                CallLog::create([
                                    'call_time'=>$messageBody['call_time'],
                                    'ring_time'=>$messageBody['release_time'],
                                    'release_dir'=>$messageBody['release_dir'],
                                    'call_type'=>$messageBody['call_type'],
                                    'aphone'=>$messageBody['phone_no'],
                                    'bphone'=>$messageBody['peer_no'],
                                    'call_id'=>$messageBody['call_id'],
                                    'secret_no'=>$messageBody['secret_no'],
                                    'sub_id'=>$messageBody['sub_id'],
                                    'talk_time'=> strtotime($messageBody['release_time'])-strtotime($messageBody['start_time']),
                                ]);
                            }
                        }
                    }
                }else{
                    foreach ($msgs as $message) {
                        // 用户逻辑：
                        $messageBody = json_decode(base64_decode($message->MessageBody),true); // base64解码后的JSON字符串
                        if (count($getList)==0) {
                            CallLog::create([
                                'call_time'=>$messageBody['call_time'],
                                'ring_time'=>$messageBody['release_time'],
                                'release_dir'=>$messageBody['release_dir'],
                                'call_type'=>$messageBody['call_type'],
                                'aphone'=>$messageBody['phone_no'],
                                'bphone'=>$messageBody['peer_no'],
                                'call_id'=>$messageBody['call_id'],
                                'secret_no'=>$messageBody['secret_no'],
                                'sub_id'=>$messageBody['sub_id'],
                                'talk_time'=> strtotime($messageBody['release_time'])-strtotime($messageBody['start_time']),
                            ]);
                        }else{
                            foreach ($getList as $k=>$v){
                                if ($v['call_id']==$messageBody['call_id']){
                                    unset($messageBody);
                                }else{
                                    CallLog::create([
                                        'call_time'=>$messageBody['call_time'],
                                        'ring_time'=>$messageBody['release_time'],
                                        'release_dir'=>$messageBody['release_dir'],
                                        'call_type'=>$messageBody['call_type'],
                                        'aphone'=>$messageBody['phone_no'],
                                        'bphone'=>$messageBody['peer_no'],
                                        'call_id'=>$messageBody['call_id'],
                                        'secret_no'=>$messageBody['secret_no'],
                                        'sub_id'=>$messageBody['sub_id'],
                                        'talk_time'=> strtotime($messageBody['release_time'])-strtotime($messageBody['start_time']),
                                    ]);
                                }
                            }
                        }
                     $receiptHandles[] = $message->ReceiptHandle; // 加入$receiptHandles数组中的记录将会被删除
                    }
                }
                if (count($receiptHandles) > 0) {
                    $deleteRequest = new BatchDeleteMessage($queueName, $receiptHandles);
                    $mnsClient->sendRequest($deleteRequest);
                }
            } catch (ClientException $e) {
                echo $e->getErrorMessage() . PHP_EOL;
            } catch (ServerException $e) {
                if ($e->getCode() == 404) {
                    $i++;
                }
                echo $e->getErrorMessage() . PHP_EOL;
            }
        } while ($i < 3);

    }




    /**
     * 通话开始时候回调数据
     * @return false|string
     * 返回参数
     * [{
        "phone_no": "18831138292",
        "pool_key": "FC100000115024469", 对应的号池Key。
        "city": "昆明",
        "sub_id": 1000027052283144,  	通话对应的三元组的绑定关系ID。
        "unconnected_cause": 0,
        "call_time": "2020-12-21 17:23:56",  主叫拨打时间。
        "peer_no": "15222021008",             AXB中的B号码或者N号码。
        "called_display_no": "17052201941",   被叫显号X号码
        "call_id": "31343639616333323735",  	唯一标识一通通话记录的ID。
        "partner_key": "FC100000115024469",
        "control_msg": "OK",
        "id": 1007221453890,
        "secret_no": "17052201941",
        "call_type": 0,0:主叫(phone_no打给peer_no)；1:被叫(peer_no打给phone_no)；2:短信发送；3:短信接收；4:呼叫拦截；5:短信收发拦截；
        "control_type": "CONTINUE"
      }]
     */
    public function SecretStartReport(){
        // 开始json
        $req = request()->post();
        // 首先创建记录
        try {
            $data = [];
            $data['call_time'] = $req[0]['call_time'];
            $data['call_type'] = $req[0]['call_type'];
            $data['aphone'] = $req[0]['phone_no'];
            $data['bphone'] = $req[0]['peer_no'];
            $data['call_id'] = $req[0]['call_id'];
            $data['secret_no'] = $req[0]['called_display_no'];
            $data['sub_id'] = $req[0]['sub_id'];
            CallLog::create($data);
        }catch (\Exception $e){
            var_dump($e->getFile().$e->getLine().$e->getMessage());

        }catch (\PDOException $e){
            var_dump($e->getFile().$e->getLine().$e->getMessage());
        }

        return json_encode(['code'=>0,'msg'=>"成功"],JSON_UNESCAPED_UNICODE);
    }


    /**
     * 电话挂断时候回调数据！
     * @return false|string
     * 回调数据
     * [{
        "phone_no": "18831138292",              主叫号码
        "pool_key": "FC100000115024469",        对应的号池Key。
        "city": "昆明",
        "sub_id": 1000027052283144, 	        通话对应的三元组的绑定关系ID。
        "unconnected_cause": 0,                 0表示正常通话，1表示黑名单拦截,2表示无绑定关系,3表示呼叫限制,4表示其他
        "call_time": "2020-12-21 17:23:56",     主叫拨打时间
        "call_out_time": "2020-12-21 17:23:56", 呼叫由X送给B端局的时间
        "peer_no": "15222021008",               AXB中的B号码或者N号码
        "called_display_no": "17052201941",     被叫显号
        "release_dir": 2,                       通话释放方向。0表示平台释放,1表示主叫挂断,2表示被叫挂断
        "ring_time": "2020-12-21 17:23:56",     呼叫送被叫端局时，被叫端局响应的时间。
        "call_id": "31343639616333323735",  	唯一标识一通通话记录的ID。
        "start_time": "2020-12-21 17:24:05",    被叫接听时间
        "free_ring_time": "2020-12-21 17:24:03",被叫手机真实的振铃时间。free_ring_time 大于call_out_time表示被叫真实发生了振铃事件。free_ring_time 和call_out_time相等表示未振铃。
        "partner_key": "FC100000115024469",
        "control_msg": "OK",
        "id": 1007221453890,
        "secret_no": "17052201941",             AXB中的X号码
        "call_type": 0,                         呼叫类型，包括：0：主叫，即phone_no打给peer_no。1：被叫，即peer_no打给phone_no。2：短信发送。3：短信接收。4：呼叫拦截5：短信收发拦截
        "release_cause": 16,                    释放原因。请根据编号在释放原因中查看。
        "control_type": "CONTINUE",
        "release_time": "2020-12-21 17:24:09"   被叫挂断时间。release_time和start_time之差表示通话时长， 如果结果为0，说明呼叫未接通
        }]
     *
     */
    public function SecretReport(){
        $req = request()->post();
        $callids = CallLog::where('call_id',$req[0]['call_id'])->first();
        try {
            if ($callids){
                if($req[0]['release_dir']==0||(strtotime($req[0]['release_time'])-strtotime($req[0]['start_time']))==0||$req[0]['unconnected_cause']!=0){
                    CallLog::where('call_id',$req[0]['call_id'])->delete();
                }else{
                    // 修改信息
                    $axbId = Axb::where(['xphone'=>$req[0]['called_display_no'],'subs_id'=>$req[0]['sub_id']])->first();
                    if($axbId){
                        $where['docter_id'] = $axbId['docter_id'];
                        $where['user_id'] = $axbId['user_id'];
                        $where['product_type'] =1;
                        $where['order_status'] =3;
                        $where['payment_status'] =2;
                        $order_id = Order::where($where)->first();
                        if ($order_id){
                            $order_id = $order_id->id;
                            $save_data = [];
                            $save_data['order_id'] = $order_id;
                            $save_data['ring_time'] = $req[0]['release_time'];
                            $save_data['docter_id'] = $axbId['docter_id'];
                            $save_data['release_dir'] = $req[0]['release_dir'];
                            $save_data['talk_time'] = strtotime($req[0]['release_time'])-strtotime($req[0]['start_time']);
                            $save_data['text'] = json_encode($req,JSON_UNESCAPED_UNICODE);
                            // 解除号码绑定，并且删除数据库绑定信息
//                            $this->unLokPhone($req[0]['called_display_no'],$req[0]['sub_id']);
//                            Axb::where(['subs_id'=>$req[0]['sub_id']])->delete();
                            CallLog::where('call_id',$req[0]['call_id'])->update($save_data);
                            return json_encode(['code'=>0,'msg'=>"成功"],JSON_UNESCAPED_UNICODE);
                        }
                    }
                }
            }

        }catch (\Exception $e){
            CallLog::create(['text'=>json_encode($e->getFile().$e->getCode().$e->getMessage(),JSON_UNESCAPED_UNICODE)]);
        }catch (\PDOException $e){
            CallLog::create(['text'=>json_encode($e->getFile().$e->getCode().$e->getMessage(),JSON_UNESCAPED_UNICODE)]);
        }

    }


    /**
     * goEasy聊天记录存入数据库
     * * @return false|string
     */
    public function easyMessage(){
        $req = request()->post();
        try {
            $data = json_decode($req['content'],true);
            $ImList = ImMessage::get();
            $newList=[];
            if ($ImList){
                foreach ($ImList as $k=>$v){
                    $newList[$k] = $v['messageId'];
                }
            }
            $list = [];
            if($data){
                foreach ($data as $k=>$v){
                    if(!in_array($v['messageId'],$newList)){
                        $list[$k]['messageId'] = $v['messageId'];
                        $list[$k]['type'] = $v['type'];
                        $list[$k]['senderId'] = $v['senderId'];
                        $list[$k]['receiverId'] = $v['receiverId'];
                        $list[$k]['timestamp'] = $v['timestamp'];
                        $list[$k]['payload'] = $v['payload'];
                        $list[$k]['text'] = $req['content'];
                        $list[$k]['create_time'] = time();
                    }
                }
                ImMessage::insert($list);
            }else{
                $list['text'] = $req['content'];
                ImMessage::create($list);

            }
            return json_encode(['code'=>200,'content'=>'success']);
        }catch (\Exception $e){
            ImMessage::create(['text'=>json_encode($e->getFile().'的第 '.$e->getLine().'行报错：'.$e->getMessage(),true)]);
        }catch (\PDOException $e){
            ImMessage::create(['text'=>json_encode($e->getFile().'的第 '.$e->getLine().'行报错：'.$e->getMessage(),true)]);
        }

    }
}
