<?php
/**
 * 文件名称（自动拨打电话）
 * 文件简单描述（自动拨打电话）
 * @author DouBin
 * @Date: 2024/8/7
 * @Time: 11:46
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */
namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\AdminInfor;
use App\Models\OrderCallphone;
use App\Models\OrderList;
use App\Services\CommonService;
use App\Services\OrderDeductionFeeService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use DB;


class SingLeCallByTtsController extends BaseController
{
    /**|---------------------------------------------------------------------------------
     * @name 获取需要推送数据
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/24 14:04
     * |---------------------------------------------------------------------------------
    */
    public function getSingleCallByTts ( ){
        if('08:30:00'<date("H:i:s") && '18:00:00'>date("H:i:s")){
            $time_start = date("Y-m-d H:i:s", strtotime(" -5 minute" . date("Y-m-d H:i:s")));
            $list = OrderList::where('stauas', '20')->where('call_phone', 1)->where('id', 5538)->whereIn('company_id', [12, 14])->where('create_time', '<', $time_start)->select('id','ser_id', 'order_num', 'sys_num', 'serial_number', 'customer_id','company_id')->limit(10)->get();
            $list = CommonService::dataToArray($list);
            $ser_id = [];
            $num = 0;
            $data = [];
            if (!empty($list)) {
                foreach ($list as $k => $v) {
                    $indata = $v['ser_id'].$v['company_id'];
                    if (!empty($ser_id) && in_array($indata, $ser_id)) {

                    }else{
                        $db = new OrderList;
                        $params = ['ser_id' => $v['ser_id'],'stauas'=>20,'company_id'=>$v['company_id']];
                        $select = ['id','serial_number'];//,'order_num', 'sys_num', 'serial_number', 'stauas', 'ser_id', 'p_id', 'order_goods_id', 'store_type', 'ol_dispamount', 'customer_id'
                        $orderBy = ['stauas' => 'DESC'];
                        $orderListArrs = CommonService::getMysqlData($db, $params, $select, $orderBy);
                        if (!$orderListArrs) {
                            $data[$num]['order_num'] = $v['order_num'];
                            $data[$num]['ser_id'] = $v['ser_id'];
                            $data[$num]['company_id'] = $v['company_id'];
                            $data[$num]['content'] = '数据异常';
                            $num++;
                        }else{
                            $phone = AdminInfor::where('admin_id',$v['ser_id'])->value('phone');
                            $res = self::singleCallByTts($phone);
                            $serial_number = array_column($orderListArrs, 'serial_number');
                            $order_num = array_column($orderListArrs, 'order_num');
                            $data[$num]['order_num'] = $order_num.'-'.$serial_number;
                            $data[$num]['ser_id'] = $v['ser_id'];
                            $data[$num]['company_id'] = $v['company_id'];
                            $data[$num]['content'] = $res;
                            $num++;
                            $res = CommonService::dataToArray($res);
                            if($res['Code'] =='OK'){
                                $ser_id[] = $indata;
                                $id = array_column($orderListArrs, 'id');
                                OrderList::whereIn("id",$id)->update(['call_phone'=>2]);
                                $och['och_RequestId'] = $res['RequestId'];
                                $och['och_CallId'] = $res['CallId'];
                                $och['och_company_id'] = $v['company_id'];
                                $och['och_order_number'] = $v['order_num'];
                                $och['och_serial_number'] = $v['serial_number'];
                                $och['och_state'] = 1;
                                $och['och_creactime'] = date('Y-m-d H:i:s');
                                $och['och_updatetime'] = date('Y-m-d H:i:s');
                                $res = OrderCallphone::insert($och);
                                if(!$res){
                                    $post_data['adm_id'] = 0;
                                    $post_data['company_id'] = $v['company_id'];
                                    $post_data['order_number'] = $v['order_num'].'-'.$v['serial_number'];
                                    $post_data['reo_price'] = -0.1;
                                    $post_data['reo_pay_way'] = 5;
                                    $post_data['pay_type'] = 1;
                                    OrderDeductionFeeService::deductFee($post_data);
                                }

                            }
                        }
                    }
                }
                CommonService::addLog('自动拒单', json_encode($data, JSON_UNESCAPED_UNICODE), '', 'singleCallByTts');
                return response()->json(['code'=>200, 'msg'=>'操作完成', 'data'=>$data]);
            }else{
                CommonService::addLog('电话通知', '无数据', '', 'singleCallByTts');
            }
        }else{
            CommonService::addLog('电话通知', '非指定时间段08:30:00-18:00:00', '','singleCallByTts');
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 发送电话通知方法
     * @param string 服务商id 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/24 16:55
     * |---------------------------------------------------------------------------------
    */
    public function singleCallByTts ( $phone ){
        $params = array ();

        // *** 需用户填写部分 ***
        // fixme 必填：是否启用https
        $security = false;

        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
        $accessKeyId = "LTAI5t64Hr8rE8NdT1D1jKNh";
        $accessKeySecret = "vpJvj5ksVOy7szD9DFraUbb7yHv8Jb";

        // fixme 必填: 被叫显号
        //$params["CalledShowNumber"] = "4001112222";

        // fixme 必填: 被叫显号
        $params["CalledNumber"] = $phone;

        // fixme 必填: Tts模板Code
        $params["TtsCode"] = "TTS_304855064";

        // fixme 选填: Tts模板中的变量替换JSON,假如Tts模板中存在变量，则此处必填
        //$params["TtsParam"] = array("AckNum" => "123456");

        // fixme 选填: 音量
        $params["Volume"] = 100;

        // fixme 选填: 播放次数
        $params["PlayTimes"] = 2;

        // fixme 选填: 音量, 取值范围 0~200
        $params["Volume"] = 100;

        // fixme 选填: 预留给调用方使用的ID, 最终会通过在回执消息中将此ID带回给调用方
        $params["OutId"] = "123456";

        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***

        if(!empty($params["TtsParam"]) && is_array($params["TtsParam"])) {
            $params["TtsParam"] = json_encode($params["TtsParam"], JSON_UNESCAPED_UNICODE);
        }

        // 此处可能会抛出异常，注意catch
        $content = self::request(
            $accessKeyId,
            $accessKeySecret,
            "dyvmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-beijing",
                "Action" => "SingleCallByTts",
                "Version" => "2017-05-25",
            )),
            $security
        );

        return $content;
    }

    /**
     * 生成签名并发起请求
     *
     * @param $accessKeyId string AccessKeyId (https://ak-console.aliyun.com/)
     * @param $accessKeySecret string AccessKeySecret
     * @param $domain string API接口所在域名
     * @param $params array API具体参数
     * @param $security boolean 使用https
     * @param $method boolean 使用GET或POST方法请求，VPC仅支持POST
     * @return bool|\stdClass 返回API接口调用结果，当发生错误时返回false
     */
    public function request($accessKeyId, $accessKeySecret, $domain, $params, $security=false, $method='POST') {
        $apiParams = array_merge(array (
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(mt_rand(0,0xffff), true),
            "SignatureVersion" => "1.0",
            "AccessKeyId" => $accessKeyId,
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
            "Format" => "JSON",
        ), $params);
        ksort($apiParams);

        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
        }

        $stringToSign = "${method}&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));

        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&",true));

        $signature = $this->encode($sign);

        $url = ($security ? 'https' : 'http')."://{$domain}/";

        try {
            $content = $this->fetchContent($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");
            return json_decode($content);
        } catch( \Exception $e) {
            return false;
        }
    }

    private function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);
        return $res;
    }

    private function fetchContent($url, $method, $body) {
        $ch = curl_init();

        if($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        } else {
            $url .= '?'.$body;
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "x-sdk-client" => "php/2.0.0"
        ));

        if(substr($url, 0,5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $rtn = curl_exec($ch);

        if($rtn === false) {
            // 大多由设置等原因引起，一般无法保障后续逻辑正常执行，
            // 所以这里触发的是E_USER_ERROR，会终止脚本执行，无法被try...catch捕获，需要用户排查环境、网络等故障
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);

        return $rtn;
    }
}
