<?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 SysCallByTtsCostController extends BaseController
{
    /**|---------------------------------------------------------------------------------
     * @name 获取需要推送数据
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/24 14:04
     * |---------------------------------------------------------------------------------
    */
    public function getCallByTtsCost ( ){
        $time_start = date("Y-m-d H:i:s", strtotime(" -5 minute" . date("Y-m-d H:i:s")));
        $list = OrderCallphone::where('och_state',1)->where('och_creactime', '<', $time_start)->get();
        $list = CommonService::dataToArray($list);
        if (!empty($list)) {
            $num = 0;
            $data = [];
            foreach ($list as $k => $v) {
                $QueryDate = strtotime($v['och_creactime']).'000';
                $res = self::queryCallDetailByCallId($v['och_CallId'], $QueryDate);
                $res = CommonService::dataToArray($res);
                if(isset($res['Data'])){
                    $och['och_Message'] = $res['Data'];
                    $res['Data'] = json_decode(str_replace('\"', '"', $res['Data']));
                    $res['Data'] = CommonService::dataToArray($res['Data']);
                    if($res['Data']['duration']>0){
                        $och['och_state'] = 2;
                    }else{
                        $och['och_state'] = 3;
                    }
                }else{
                    $och['och_Message'] = '';
                    $och['och_state'] = 4;
                }
                $och['och_updatetime'] = date("Y-m-d H:i:s");
                OrderCallphone::where('och_id',$v['och_id'])->update($och);
                if(in_array($och['och_state'], [4,2,3])) {
                    $post_data['adm_id'] = 0;
                    $post_data['company_id'] = $v['och_company_id'];
                    $post_data['order_number'] = $v['och_order_number'] . '-' . $v['och_serial_number'];
                    $post_data['reo_price'] = -0.1;
                    $post_data['reo_pay_way'] = 5;
                    $post_data['pay_type'] = 1;
                    OrderDeductionFeeService::deductFee($post_data);
                }
                $data[$num]['order_num'] = $v['och_order_number'].'-'.$v['och_serial_number'];
                $data[$num]['och_company_id'] = $v['och_company_id'];
                $data[$num]['content'] = $res;
                $num++;
            }
            CommonService::addLog('电话通知扣费', json_encode($data, JSON_UNESCAPED_UNICODE), '', 'getCallByTtsCost');
            return response()->json(['code'=>200, 'msg'=>'操作完成', 'data'=>$data]);
        }else{
            CommonService::addLog('电话通知扣费', '无数据', '', 'getCallByTtsCost');
        }
    }

    /**
     * 通过呼叫ID获取呼叫记录
     */
    function queryCallDetailByCallId($CallId,$QueryDate) {

        $params = array();

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

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

        // fixme 必填: 从上次呼叫调用的返回值中获取的CallId
        $params["CallId"] = $CallId;

        // fixme 必填: Unix时间戳（毫秒），会查询这个时间点对应那一天的记录
        $params["QueryDate"] = $QueryDate;

        // fixme 必填: 语音通知为:11000000300006, 语音验证码为:11010000138001, IVR为:11000000300005, 点击拨号为:11000000300004, SIP为:11000000300009
        $params["ProdId"] = "11000000300006";

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

        // 此处可能会抛出异常，注意catch
        $content = self::request(
            $accessKeyId,
            $accessKeySecret,
            "dyvmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-beijing",
                "Action" => "QueryCallDetailByCallId",
                "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;
    }
}
