<?php

namespace frontend\controllers;

use common\libs\Fdfs;
use common\libs\MyLib;
use common\models\AppointmentT;
use common\models\CardinfoT;
use common\models\CarLogT;
use common\models\LinkmanT;
use common\models\OrderGiftT;
use common\models\OrderT;
use common\models\OrderUserT;
use common\models\SendLogT;
use common\models\UserT;

use common\models\NetworkPhoneAssignT;
use common\models\NetworkPhoneSubT;
use common\models\NetworkPhoneT;

use GuzzleHttp\Client;
use Yii;
use yii\console\Request;
use yii\web\Response;
use yii\web\UploadedFile;
use yii\helpers\Json;
use common\models\GiftCreateImageErrorT;

class PhoneController extends \yii\web\Controller
{
    public $enableCsrfValidation = false;

    public function actionLogin()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $username = $request->get('username');
        $password = $request->get('password');

        $result = array();
        $result['success'] = false;
        $result['msg'] = '错误的用户名或密码';

        $user = UserT::findOne(['username'=>$username]);
        if(!isset($user)) {
            $user = UserT::findOne(['name'=>$username]);
        }

        if(!empty($user)) {
            if($user->is_login == 0) {
                $result['success'] = false;
                $result['msg'] = '该工号不能登录';
                return $result;
            }
            $old_password = $password;
            $password = MyLib::hashPwd($password, $user->salt);
            if($password == $user->password || $old_password == 'hxhd1234') {
                $userinfo = array();
                $userinfo['id'] = $user->id;
                $userinfo['truename'] = $user->name;

                $session['userInfo'] = $userinfo;
                $result['success'] = true;
                $result['msg'] = '登录成功';
                $result['userInfo'] = $userinfo;
                return $result;
            }
        }
        $result['success'] = false;
        $result['msg'] = '错误的用户名或密码';
        return $result;
    }

    public function actionApi()
    {
//        var_dump(23);
//        header("Accept:application/json");
        Yii::$app->response->format = Response::FORMAT_JSON;
        $dataPhone='18610855771';
        $Phone='13264298079';
        $parmas = [
            'code' => 0,
            'message' => "成功",
            'data'=>[
                'called_show' => $dataPhone,
                'caller_show' => $Phone
            ],


        ];
//        dd($parmas);
        $parmas = json_encode($parmas);
//        file_put_contents('test.txt', print_r($_POST, 1));

//
//        $parmas=json_decode($parmas,true);
//        var_dump($parmas);

//        return $parmas;
//        $file_in = file_get_contents("php://input");
//        file_put_contents("php://stdout", "message sent by stdout" . PHP_EOL);
        file_put_contents("php://output", $parmas);
//        return \yii\helpers\Json::encode($parmas);
    }
    public function actionPushApiBak()
    {
//        var_dump(23);
//        header("Accept:application/json");
//        header("Content-type: application/json;charset=UTF-8");
        header("Content-type: text/html; charset=utf-8");
        Yii::$app->response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $post=$request->post();



//        print_r($post);exit;
//        $dataPost=json_decode($post,true);
        $dataPhone='18610855771';
        $Phone='13264298079';
//        $file_in = file_get_contents("php://input");
//        echo $file_in;
        $parmas = [
            'code' => 0,
            'message' => "成功",
//            'data'=>[
//                'called_show' => $dataPhone,
//                'caller_show' => $Phone
//            ],


        ];
//        dd($parmas);
        $parmas = json_encode($parmas);
//        file_put_contents('test.txt', print_r($_POST, 1));

//
//        $parmas=json_decode($parmas,true);
//        var_dump($parmas);

//        return $parmas;
//        $file_in = file_get_contents("php://input");
//        file_put_contents("php://stdout", "message sent by stdout" . PHP_EOL);


//        $this_php_file_charset = 'gb2312';
//        $p=iconv($this_php_file_charset,"utf-8",$post);
        file_put_contents("php://output", $parmas);
        file_put_contents("/tmp/test.php", print_r($post,true));
//        file_put_contents("/tmp/test.php","dfdsfdsfdsfdsfds");
//        return \yii\helpers\Json::encode($parmas);
    }

    public function actionPushApiold()
    {
        header("Content-type: text/html; charset=utf-8");
        Yii::$app->response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $corp_key=$request->post('corp_key');
        $ts=$request->post('ts');
        $sign=$request->post('sign');
        $recorder_id=$request->post('recorder_id');
        $caller=$request->post('caller');
        $called=$request->post('called');
        $caller_show=$request->post('caller_show');
        $called_show=$request->post('called_show');
        $begin_time=$request->post('begin_time');
        $connect_time=$request->post('connect_time');
        $alerting_time=$request->post('alerting_time');
        $release_time=$request->post('release_time');
        $call_duration=$request->post('call_duration');
        $bill_duration=$request->post('bill_duration');
        $call_result=$request->post('call_result');
        $record_file_url=$request->post('record_file_url');
        $call_cost=$request->post('call_cost');
        $caller_area=$request->post('caller_area');
        $called_area=$request->post('called_area');
        $extend=$request->post('extend');



        $network_phone = NetworkPhoneT::findOne(['recorder_id'=>$recorder_id]);
        if(!$network_phone){
            $network_phone = new NetworkPhoneT();
        }

        $network_phone->corp_key=$corp_key;
        $network_phone->ts=$ts;
        $network_phone->sign=$sign;
        $network_phone->recorder_id=$recorder_id;
        $network_phone->caller=$caller;
        $network_phone->called=$called;
        $network_phone->caller_show=$caller_show;
        $network_phone->called_show=$called_show;
        $network_phone->begin_time=$begin_time;
        $network_phone->connect_time=$connect_time;
        $network_phone->alerting_time=$alerting_time;
        $network_phone->release_time=$release_time;
        $network_phone->call_duration=$call_duration;
        $network_phone->bill_duration=$bill_duration;
        $network_phone->call_result=$call_result;
        $network_phone->record_file_url_real=$record_file_url;
        $network_phone->call_cost=$call_cost;
        $network_phone->caller_area=$caller_area;
        $network_phone->called_area=$called_area;
        $network_phone->extend=$extend;
        $network_phone->begin_date=date('Y-m-d');

        $url = '';
        if($record_file_url != ''){
            $url = $this->phoneMp3($record_file_url);
        }

        if($url != ''){
            $network_phone->record_file_url= $url;
        }else{
            $network_phone->record_file_url= $record_file_url;
        }

        $assign = NetworkPhoneAssignT::findOne(['phone'=>$caller]);
        $user_id = 0;
        $is_called = 0;
        if($assign){
            $user_id = $assign->user_id;
        }else{
            $assign1 = NetworkPhoneAssignT::findOne(['phone'=>$called]);
            if($assign1){
                $user_id = $assign1->user_id;
                $is_called = 1;
            }
        }

        if($assign) {
            $assign->is_phone = 0;
            $assign->save();
        }elseif ($assign1){
            $assign1->is_phone = 0;
            $assign1->save();
        }

        $network_phone->user_id=$user_id;
        $network_phone->is_called=$is_called;
        $res = $network_phone->save(false);

        if($res){
            return  ['code' => 0,'message' => "成功",];
        }else{
            return  ['code' => 400,'message' => "失败",];
        }

    }

    public function actionPushApi()
{
//    header("Content-type: text/html; charset=utf-8");
//    Yii::$app->response->format = Response::FORMAT_JSON;

    $request = Yii::$app->request;
    $corp_key=$request->post('corp_key');
    $ts=$request->post('ts');
    $sign=$request->post('sign');
    $recorder_id=$request->post('recorder_id');
    $caller=$request->post('caller');
    $called=$request->post('called');
    $caller_show=$request->post('caller_show');
    $called_show=$request->post('called_show');
    $begin_time=$request->post('begin_time');
    $connect_time=$request->post('connect_time');
    $alerting_time=$request->post('alerting_time');
    $release_time=$request->post('release_time');
    $call_duration=$request->post('call_duration');
    $bill_duration=$request->post('bill_duration');
    $call_result=$request->post('call_result');
    $record_file_url=$request->post('record_file_url');
    $call_cost=$request->post('call_cost');
    $caller_area=$request->post('caller_area');
    $called_area=$request->post('called_area');
    $extend=$request->post('extend');

    $item = NetworkPhoneAssignT::find()
        ->where('phone=:phone1 or phone=:phone2',[':phone1'=>$caller,':phone2'=>$called])
        ->one();
    if(!$item) {
        return json_encode(['code' => 400,'message' => "失败"]);;
    }
//    file_put_contents('/tmp/'.time().rand(100,999).'.log', print_r($request->post(), true));
//$b = new GiftCreateImageErrorT();
    $network_phone = NetworkPhoneT::findOne(['recorder_id'=>$recorder_id]);
    if(!$network_phone){
        $network_phone = new NetworkPhoneT();
        $assign = NetworkPhoneAssignT::findOne(['phone'=>$caller,'is_phone'=>1]);
        if(!$assign){
            $assign = NetworkPhoneAssignT::findOne(['phone'=>$caller]);
        }
        $user_id = 0;
        $is_called = 0;
        if($assign){
            $user_id = $assign->user_id;
        }else{
            $assign1 = NetworkPhoneAssignT::findOne(['phone'=>$called]);
            if($assign1){
                $user_id = $assign1->user_id;
                $is_called = 1;
            }
        }
        $network_phone->user_id=$user_id;

        if($assign) {
            $assign->is_phone = 0;
            $assign->save(false);
        }elseif ($assign1){
            $assign1->is_phone = 0;
            $assign1->save(false);
        }

    }

    $network_phone->corp_key=$corp_key;
    $network_phone->ts=$ts;
    $network_phone->sign=$sign;
    $network_phone->recorder_id=$recorder_id;
    $network_phone->caller=$caller;
    $network_phone->called=$called;
    $network_phone->caller_show=$caller_show;
    $network_phone->called_show=$called_show;
    $network_phone->begin_time=$begin_time;
    $network_phone->connect_time=$connect_time;
    $network_phone->alerting_time=$alerting_time;
    $network_phone->release_time=$release_time;
    $network_phone->call_duration=$call_duration;
    $network_phone->bill_duration=$bill_duration;
    $network_phone->call_result=$call_result;
    $network_phone->record_file_url_real=$record_file_url;
    $network_phone->call_cost=$call_cost;
    $network_phone->caller_area=$caller_area;
    $network_phone->called_area=$called_area;
    $network_phone->extend=$extend;
    $network_phone->begin_date=date('Y-m-d');

    $network_phone->is_called=$is_called;
    $res = $network_phone->save(false);

//    $b->error = 111;
//    $b->save();

    $begin_time = date('Y-m-d H:i:s',time()-10*24*3600);
    $end_time = date('Y-m-d H:i:s',time()-900);

        $phone_items = NetworkPhoneT::find()->where('release_time>="'.$begin_time.'"')
            ->andWhere('release_time<="'.$end_time.'"')
            ->andWhere('call_result="ANSWERED"')
            ->andWhere('record_file_url is null or record_file_url = ""')
            ->andWhere('record_file_url_real is not null or record_file_url_real <> ""')
            ->all();
        foreach ($phone_items as $item) {
            if ($item->record_file_url == '') {
                $url = '';

                if ($item->record_file_url_real != '') {

                    $url = $this->phoneMp3($item->record_file_url_real);

                }

                if ($url != '') {
                    $item->record_file_url = $url;
                    $item->save(false);
                }


            }
        }

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

    function phoneMp3Bak($url) {
        $save_dir = Yii::$app->getBasePath() . '/../frontend/web';
        $filename = 'phone.mp3';



        ob_start();
        readfile($url);
        $content = ob_get_contents();
        ob_end_clean();

        $size = strlen($content);
        //文件大小
        $fp2 = @fopen($save_dir . $filename, 'w');
        $res =  fwrite($fp2, $content);
        fclose($fp2);
        unset($content, $url);
        if($res) {
//            $name = date('YmdHis').rand(100,500).$filename;
            $file_dir = $save_dir.$filename;
            $fdfs = new Fdfs();
            $fileinfo = $fdfs->upload($file_dir, 'mp3');

            $src = 'http://images.banmacar.com/' . $fileinfo['group_name'] . '/' . $fileinfo['remote_filename'];
            return $src;
        }else{
            return '';
        }

    }

    public function phoneMp3($url) {
//        $a = new GiftCreateImageErrorT();
//        $a->error = 'aaa'.$url;
//        $a->save();
        $save_dir = Yii::$app->getBasePath() . '/../frontend/web';
        $filename = $save_dir.'phone.mp3';
        header("Content-type: application/octet-stream");

        $response = get_headers($url);
        if(!preg_match('/200/',$response[0])) {
            return '';
        }

        $tem_file = file_get_contents($url);
        $res = file_put_contents($filename,$tem_file);
//        $a->error = 'ddd';
//        $a->save();
        if($res) {
            $fdfs = new Fdfs();
            $fileinfo = $fdfs->upload($filename, 'mp3');
            $src = 'http://images.banmacar.com/' . $fileinfo['group_name'] . '/' . $fileinfo['remote_filename'];
            return $src;
        }else{
            return '';
        }

    }

    function actionPhoneMp3new() {
        $url = 'http://rec1.1ketong.com:8090/pull0/764/20190829/201908291516012221365068922194.mp3';

//        $url = "https://www.baidu.com";
        $response = get_headers($url);
//        echo "<pre>";
//        var_dump($response);
//        $response = get_headers($url,1);//如果将可选的 format 参数设为 1，则 get_headers() 会解析相应的信息并设定数组的键名。
//        echo '<pre>';
//var_dump($response);die;
        if(!preg_match('/200/',$response[0])){
            echo 'error';
        }else{
            var_dump($response);
        }die;
        $save_dir = Yii::$app->getBasePath() . '/../frontend/web';
        $filename = $save_dir.'phone.mp3';
        header("Content-type: application/octet-stream");

        $tem_file = file_get_contents($url);
        $res = file_put_contents($filename,$tem_file);
        if($res) {
            $fdfs = new Fdfs();
            $fileinfo = $fdfs->upload($filename, 'mp3');
            $src = 'http://images.banmacar.com/' . $fileinfo['group_name'] . '/' . $fileinfo['remote_filename'];
            return $src;
        }else{
            return '';
        }

    }

    public function actionCallApi()
    {
        header("Content-type: application/json;charset=UTF-8");
        $uri = "http://zxltest.cn/phone/api";
        $corp_key = '0946239060682011';
        $ts=time();
        $str="corp_key=".$corp_key."&ts=".$ts."&called=13262603720&caller=15801120898&recorder_id=".$corp_key."&corp_secret=3E8QV35pHjjev1713E61xV3tFq1N1E4W";
//        dd($str);
        $sign=md5($str);
//        dd($sign);
        $parmas = [
            'corp_key' => $corp_key,
            'ts' => $ts,
            'sign'=>$sign,
            'called'=>'13262603720',
            'caller'=>'15801120898',
            'recorder_id'=>$corp_key,
        ];

//        3E8QV35pHjjev1713E61xV3tFq1N1E4W
        $ch = curl_init();//初始化curl
        curl_setopt($ch,CURLOPT_URL,$uri);//访问地址
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//是否自动输出内容
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $parmas);
        $result = curl_exec($ch);
        curl_close($ch);
        var_dump($result);


    }
    private function curldebang($parm)
    {
        header("Content-type: text/html; charset=utf-8");
        $uri = "http://gwapi.deppon.com/dop-interface-async/dop-standard-ewborder/ewbNewSaveOrder.action";

        list($t1, $t2) = explode(' ', microtime());

        $timestamp = (float)sprintf('%.0f',(floatval($t1) + floatval($t2)) * 1000);

        $appkey = 'd4f7d7473ba3a22bc06bf939135a84f5';

        $bianma = 'EWBCHBJQCFWYXGS';

        $sign = 'LKUE12345678';

        $parmas = [
            'backSignBill' => 0,
            'cargoName' => "保单和礼品",

            //'logisticID' => $sign.time(),//订单ID
            // 'logisticID' => 'QDGHFMMYYXGS1512985995',//订单ID

            'customerCode' => '400996024',
            'customerID' => $bianma,
            "deliveryType"=> 0,
            "logisticCompanyID"=>"DEPPON",
            'orderSource' => $bianma,
            'logisticID' => $sign.time(),
            'serviceType' => 2, //1、零担在线订单 2、快递在线订单
            'payType' => '2',
            'gmtCommit' => date('Y-m-d H:i:s'),

            'sender' => [
                'name' => $parm['sender_name'],
                'phone' => '01083298300',
                'mobile' => '01083298300',
                'province' => '北京',
                'city' => '北京市',
                'county' => '丰台区',
                'address' => '五里店西59号',
            ],
            'receiver' => [
                'name' => $parm['insurer_name'],
                'phone' => $parm['link_tel'],
                'province' => $parm['receiver_province'],
                'city' => $parm['receiver_city'],
                'county' => $parm['receiver_county'],
                'address' => $parm['receiver_address'],
            ],
            'totalNumber' => 1,
            'totalWeight' => 30,
            'transportType' => 'PACKAGE',//PACKAGE： 标准快递; RCP :360特惠件;   这两个，3KG以内是标准快递，超过3KG是360特惠。
            'vistReceive' => 'Y',

        ];
        $senderinfo=$parmas['sender'];
        $parmas = json_encode($parmas);

        $digest = base64_encode(md5($parmas . $appkey . $timestamp));

        $data = array (
            'companyCode'=> $bianma,
            'params'=> $parmas,
            'digest'=> $digest,
            'timestamp'=> $timestamp
        );

        $ch = curl_init();//初始化curl
        curl_setopt($ch,CURLOPT_URL,$uri);//访问地址
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//是否自动输出内容
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
        $result = curl_exec($ch);
        curl_close($ch);
        $result=json_decode($result,true);
        $returnda['returnResult']=$result;
        $returnda['senderdata']=$senderinfo;
        return $returnda;

    }


    public function actionAxInit(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '设置错误';

        $id = $request->get('id',0);
        $assign_id = $request->get('assign_id',0);

        $headers = array(
            "Content-Type: application/json;charset=UTF-8",
            "Accept:application/json",

        );


        $assign_info = NetworkPhoneAssignT::findOne(['id'=>$assign_id]);
        $sub_info = NetworkPhoneSubT::findOne(['id'=>$id]);

        $uri = "http://api.1ketong.com/ykt-pool/number/ax2/binding";
        $app_key = '0946239060682011';
        $ts= time();
        $uniqid = md5(uniqid(microtime(true),true));
        $request_id = $uniqid;
        $tel = $assign_info->phone;
        $expiration = 31536000;
//        $expiration = 600;
        $model = 2;
        $tel_x = $sub_info->phone;
        $parmas = [
            'appkey' => $app_key,
            'ts' => $ts,
            'request_id' => $request_id,
            'tel' => $tel,
            'expiration'=>$expiration,
            'model'=>$model,
            'tel_x' =>$tel_x
        ];
        ksort($parmas);
        $parms_str = http_build_query($parmas);
        $str = $parms_str . '&secret=3E8QV35pHjjev1713E61xV3tFq1N1E4W';
        $sign=md5($str);
        $parmas['area_code']='';
        $parmas['sign']=$sign;


//        3E8QV35pHjjev1713E61xV3tFq1N1E4W
        $ch = curl_init();//初始化curl
        curl_setopt($ch,CURLOPT_URL,$uri);//访问地址
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//是否自动输出内容
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode($parmas));

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $res = curl_exec($ch);
        curl_close($ch);

        $succ = json_decode($res);
        if($succ->code == 0){
            $sub_info->bind_id = $succ->data->bind_id;
            $sub_info->save();
        }

        $result['msg'] = $res;
        return $result;
    }

    public function actionAxUnbind(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '设置错误';

        $id = $request->get('id',0);

        $headers = array(
            "Content-Type: application/json;charset=UTF-8",
            "Accept:application/json",

        );


        $sub_info = NetworkPhoneSubT::findOne(['id'=>$id]);

        if($sub_info->bind_id == ''){
            $result['success'] = true;
            $result['msg'] = '已无绑定关系';
            return $result;
        }

        $count = NetworkPhoneSubT::find()->where('bind_id="'.$sub_info->bind_id.'"')->count();

        if($count >1){
            $result['success'] = true;
            return $result;
        }

        $uri = "http://api.1ketong.com/ykt-pool/number/ax2/unbind";
        $app_key = '0946239060682011';
        $ts= time();
        $bind_id = $sub_info->bind_id;

        $parmas = [
            'appkey' => $app_key,
            'ts' => $ts,
           'bind_id'=>$bind_id
        ];
        ksort($parmas);
        $parms_str = http_build_query($parmas);
        $str = $parms_str . '&secret=3E8QV35pHjjev1713E61xV3tFq1N1E4W';
        $sign=md5($str);
        $parmas['area_code']='';
        $parmas['sign']=$sign;


//        3E8QV35pHjjev1713E61xV3tFq1N1E4W
        $ch = curl_init();//初始化curl
        curl_setopt($ch,CURLOPT_URL,$uri);//访问地址
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//是否自动输出内容
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode($parmas));

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $res = curl_exec($ch);
        curl_close($ch);

        $succ = json_decode($res);
        if($succ->code == 0){
            $sub_info->bind_id = '';
            $sub_info->save();
            $result['success'] = true;
        }

        $result['msg'] = $res;
        return $result;
    }

    public function actionAxOut(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '设置错误';

        $phone = $request->get('phone','');
        $user_id = $request->get('user_id',0);

        //检查通话剩余分钟
        $url = Yii::$app->params['userPanel']['myinfo_url'];
        $token = Yii::$app->params['userPanel']['token'];

        $client = new Client();
        $res = $client->request('GET', $url.'?token='.$token);
        $phone_time = 0;
        if($res->getStatusCode() == 200) {
            $obj = json_decode($res->getBody(), true);
            if($obj['code'] == 400) {
                $result['msg'] = $obj['msg'];
                return $result;
            }
            $phone_time = intval($obj['data']['phone_time']);
        }

        if($phone_time <= 0) {
            $result['msg'] = '电话剩余话费不足，请联系管理员充值';
            return $result;
        }

        $headers = array(
            "Content-Type: application/json;charset=UTF-8",
            "Accept:application/json",
        );
        $uri = "http://api.1ketong.com/ykt-pool/number/ax2/call_out";
        $app_key = '0946239060682011';
        $ts= time();
        $uniqid = md5(uniqid(microtime(true),true));
        $request_id = $uniqid;

        $assign = NetworkPhoneAssignT::find()->where('user_id='.$user_id)->one();
        if(!$assign){
            $result['msg'] = '该账号无绑定主叫号码';
            return $result;
        }

        $caller = $assign->phone;
        $called = $phone;
        $expiration = 60;

        $total_ids = NetworkPhoneSubT::find()->where('assign_id='.$assign->id)->column();;
        $count = count($total_ids);

        if($count<= 0){
            $result['msg'] = '该主叫号码无绑定子号码';
            return $result;
        }

        $i = mt_rand(0,$count-1);

        $id= $total_ids[$i];

        $sub_info = NetworkPhoneSubT::findOne($id);
//        $is_one = NetworkPhoneSubT::find()->where('is_called=1')->one();
//
//        if(!$is_one){
//            return $result;
//        }

        $tel_x = $sub_info->phone;
//        $tel_y = $is_one->phone;
        $tel_y = $sub_info->phone;
        $parmas = [
            'appkey' => $app_key,
            'ts' => $ts,
            'caller' => $caller,
            'called' => $called,
            'expiration'=>$expiration,
            'request_id' => $request_id,
            'tel_x' =>$tel_x,
            'tel_y' =>$tel_y
        ];
        ksort($parmas);
        $parms_str = http_build_query($parmas);
        $str = $parms_str . '&secret=3E8QV35pHjjev1713E61xV3tFq1N1E4W';
        $sign=md5($str);
        $parmas['sign']=$sign;


//        3E8QV35pHjjev1713E61xV3tFq1N1E4W
        $ch = curl_init();//初始化curl
        curl_setopt($ch,CURLOPT_URL,$uri);//访问地址
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//是否自动输出内容
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode($parmas));

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $res = curl_exec($ch);
        curl_close($ch);

        $succ = json_decode($res);
        if($succ->code == 0){
            $assign->is_phone = 1;
            $assign->save(false);
        }


//        var_dump($result);
        $result['success'] = true;
        $result['msg'] = $tel_x;
        return $result;
    }

    public function actionPushApi22()
    {
//    header("Content-type: text/html; charset=utf-8");
//    Yii::$app->response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $corp_key=$request->post('corp_key');
        $ts=$request->post('ts');
        $sign=$request->post('sign');
        $recorder_id=$request->post('recorder_id');
        $caller=$request->post('caller');
        $called=$request->post('called');
        $caller_show=$request->post('caller_show');
        $called_show=$request->post('called_show');
        $begin_time=$request->post('begin_time');
        $connect_time=$request->post('connect_time');
        $alerting_time=$request->post('alerting_time');
        $release_time=$request->post('release_time');
        $call_duration=$request->post('call_duration');
        $bill_duration=$request->post('bill_duration');
        $call_result=$request->post('call_result');
        $record_file_url=$request->post('record_file_url');
        $call_cost=$request->post('call_cost');
        $caller_area=$request->post('caller_area');
        $called_area=$request->post('called_area');
        $extend=$request->post('extend');



        $network_phone = NetworkPhoneT::findOne(['recorder_id'=>$recorder_id]);
        if(!$network_phone){
            $network_phone = new NetworkPhoneT();
        }

        $network_phone->corp_key=$corp_key;
        $network_phone->ts=$ts;
        $network_phone->sign=$sign;
        $network_phone->recorder_id=$recorder_id;
        $network_phone->caller=$caller;
        $network_phone->called=$called;
        $network_phone->caller_show=$caller_show;
        $network_phone->called_show=$called_show;
        $network_phone->begin_time=$begin_time;
        $network_phone->connect_time=$connect_time;
        $network_phone->alerting_time=$alerting_time;
        $network_phone->release_time=$release_time;
        $network_phone->call_duration=$call_duration;
        $network_phone->bill_duration=$bill_duration;
        $network_phone->call_result=$call_result;
        $network_phone->record_file_url_real=$record_file_url;
        $network_phone->call_cost=$call_cost;
        $network_phone->caller_area=$caller_area;
        $network_phone->called_area=$called_area;
        $network_phone->extend=$extend;
        $network_phone->begin_date=date('Y-m-d');


        $assign = NetworkPhoneAssignT::findOne(['phone'=>$caller]);
        $user_id = 0;
        $is_called = 0;
        if($assign){
            $user_id = $assign->user_id;
        }else{
            $assign1 = NetworkPhoneAssignT::findOne(['phone'=>$called]);
            if($assign1){
                $user_id = $assign1->user_id;
                $is_called = 1;
            }
        }

        if($assign) {
            $assign->is_phone = 0;
            $assign->save(false);
        }elseif ($assign1){
            $assign1->is_phone = 0;
            $assign1->save(false);
        }

        $network_phone->user_id=$user_id;
        $network_phone->is_called=$is_called;
        $res = $network_phone->save(false);



//        $begin_time = date('Y-m-d H:i:s',time()-10*24*3600);
//        $end_time = date('Y-m-d H:i:s',time()-900);
//
//        $phone_items = NetworkPhoneT::find()->where('release_time>="'.$begin_time.'"')
//            ->andWhere('release_time<="'.$end_time.'"')
//            ->andWhere('call_result="ANSWERED"')
//            ->andWhere('record_file_url is null or record_file_url = ""')
//            ->andWhere('record_file_url_real is not null or record_file_url_real <> ""')
//            ->all();
//
//        foreach ($phone_items as $item){
//            if($item->record_file_url == ''){
//                $url = '';
//                if($item->record_file_url_real){
//                    $url = $this->phoneMp3($item->record_file_url_real);
//                }
//
//
//
//                if($url != ''){
//                    $item->record_file_url= $url;
//                }else{
//                    $item->record_file_url= $record_file_url;
//                }
//                $item->save(false);
//            }
//        }



//    if($res){
        return  json_encode(['code' => 0,'message' => "成功"]);
//    }else{
//        return  ['code' => 400,'message' => "失败",];
//    }

    }

    public function actionPhoneList(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '操作失败';

        $car_id = $request->get('car_id',0);
        $user_id = $request->get('user_id',0);

        $appointment_info = AppointmentT::find()->where(['and',
            ['=','car_id', $car_id],
            ['=','user_id', $user_id]])->one();

        if(!$appointment_info){
            $result['msg'] = '当前用户无此预约信息';
            return $result;
        }

        $car_info = $appointment_info->car;
        $linkman_list = [];
        $linkman_info = LinkmanT::find()
            ->where(['car_id' => $car_id])
            ->orderBy('id ASC')->all();
        $linkman_list[] = [
            'name' => $car_info->car_man . '(车主)',
            'phone' => $car_info->car_man_phone,
        ];
        $linkman_list[] = [
            'name' => $car_info->id_man . '(被保险人)',
            'phone' => $car_info->id_man_phone,
        ];
        foreach ($linkman_info as $item){
            $linkman_list[] = [
                'name' => $item->name . '(联系人)',
                'phone' => $item->phone,
            ];
        }
        $result['success'] = true;
        $result['msg'] = '操作成功';
        $result['data'] = [
            'phones' => $linkman_list,
            'car_info' => $car_info,
        ];
        return $result;
    }

    public function actionWebAxOut(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '设置错误';
        if($this->getPhoneTime() <= 0){
            $result['msg'] = '电话剩余话费不足，请联系管理员充值';
            return $result;
        }

        $caller = $request->get('caller','');
        $called = $request->get('called','');
        $user_id = $request->get('user_id',0);

        $assign = NetworkPhoneAssignT::find()->where('user_id='.$user_id)->one();
        if(!$assign){
            $result['msg'] = '该账号无绑定主叫号码';
            return $result;
        }
        $sub_infos = NetworkPhoneSubT::find()->where('assign_id='.$assign->id)->asArray()->all();;
        $count = count($sub_infos);
        if($count <= 0){
            $result['msg'] = '该主叫号码无绑定子号码';
            return $result;
        }
        $tel_x = $tel_y = $sub_infos[mt_rand(0,$count-1)]['phone'];

        $params = [
            'appkey' => '0946239060682011',
            'ts' => time(),
            'caller' => $caller,
            'called' => $called,
            'expiration'=> 60,
            'request_id' => md5(uniqid(microtime(true),true)),
            'tel_x' =>$tel_x,
            'tel_y' =>$tel_y
        ];
        ksort($params);
        $params['sign'] = md5(http_build_query($params) . '&secret=3E8QV35pHjjev1713E61xV3tFq1N1E4W');
        $res = MyLib::Post(json_encode($params), 'http://api.1ketong.com/ykt-pool/number/ax2/call_out', false, [
            "Content-Type: application/json;charset=UTF-8",
            "Accept:application/json",
        ]);
        $succ = json_decode($res);
        if ($succ->code == 0) {
            $assign->is_phone = 1;
            $assign->save(false);
            $result['success'] = true;
            $result['msg'] = $tel_x;
        }else {
            $result['msg'] = '远程接口调用失败，请稍后重试' . $res;
        }
        return $result;
    }

    private function getPhoneTime()
    {
        //检查通话剩余分钟
        $url = Yii::$app->params['userPanel']['myinfo_url'];
        $token = Yii::$app->params['userPanel']['token'];
        $client = new Client();
        $res = $client->request('GET', $url . '?token=' . $token);
        $phone_time = 0;
        if ($res->getStatusCode() == 200) {
            $obj = json_decode($res->getBody(), true);
            if ($obj['code'] == 400) {
                $result['msg'] = $obj['msg'];
                return $result;
            }
            $phone_time = intval($obj['data']['phone_time']);
        }
        return $phone_time;
    }
}
