<?php
/**
 * Created by PhpStorm.
 * User: 诚合
 * Date: 2019/2/14
 * Time: 9:22
 */

namespace frontend\controllers;

use common\models\FixCarT;
use common\models\UserT;
use GuzzleHttp\Client;
use yii\base\Controller;
use common\libs\MyLib;
use common\models\AppointmentT;
use common\models\AppointmentHistoryT;
use common\models\InvalidT;
use common\models\CarET;
use common\models\CarT;
use common\models\CarLogT;
use common\models\CarUseT;
use common\models\BrandT;
use common\models\CarTypeT;
use common\models\SeriesT;
use common\models\DisplacementT;
use common\models\GiftTicketT;
use common\models\CarGiftT;
use common\models\MeetT;
use common\models\BusinessGroupT;
use common\models\OrderT;
use common\models\InsurerTypeT;
use common\models\CarRepairT;
use common\models\RevisitConditionT;
use common\models\RevisitConditonResultT;
use common\models\NetworkPhoneT;
use common\models\NetworkPhoneAssignT;


use Yii;
use yii\data\Pagination;
use yii\web\Response;
use common\models\NetworkPhoneSubT;
use common\models\CompanyT;

class PhoneCenterController extends BaseController
{
    public $enableCsrfValidation = false;
    public $layout = 'blue-main';

    public function actionCallRecords() {
        $request = Yii::$app->request;
        $company_type = $request->get('company_type',0);

        return $this->render('call-records', [
            'company_type' => $company_type
        ]);
    }
    public function actionCallRecordsJson(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $begin_time = $request->get('begin_time',date('Y-m-d'));
        $end_time = $request->get('end_time',date('Y-m-d'));
        $username = $request->get('username','');
        $caller = $request->get('caller','');
        $called = $request->get('called','');
        $duration_begin = $request->get('duration_begin','');
        $duration_end = $request->get('duration_end','');
        $call_result = $request->get('call_result','');
        $is_called = $request->get('is_called','');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $company_type = $request->get('company_type',0);//0显示全部，1只显示江西，2只显示湖北

        $query = NetworkPhoneT::find()
        ->leftJoin('user_t','user_t.id=network_phone_t.user_id')
        ->where('user_t.is_delete=0 and user_t.is_leave=0');

        if($company_type == 3){
            $query->andWhere('user_t.id="'.$this->my->id.'"');
        }
        if($begin_time != ''){
            $query->andWhere('network_phone_t.begin_time>="'.$begin_time.'"');
        }
        if($end_time != ''){
            $query->andWhere('network_phone_t.begin_time<="'.$end_time.'"');
        }
        if($caller != ''){
            $query->andWhere('network_phone_t.caller='.$caller);
        }
        if($called != ''){
            $query->andWhere('network_phone_t.called='.$called);
        }
        if($duration_begin != ''){
            $query->andWhere('network_phone_t.call_duration>='.$duration_begin);
        }
        if($duration_end != ''){
            $query->andWhere('network_phone_t.call_duration<='.$duration_end);
        }
        if($call_result != ''){
            $query->andWhere('network_phone_t.call_result="'.$call_result.'"');
        }
        if($is_called == 1){
            $query->andWhere('network_phone_t.is_called=1');
        }elseif ($is_called ==2){
            $query->andWhere('network_phone_t.is_called=0 or network_phone_t.is_called is null');
        }
        if($username != ''){
            $query->andWhere('user_t.username="'.$username.'"');
        }
//        echo $query->createCommand()->rawSql;
        $total = $query->count();

        $query->offset($offset)->limit($limit);


        $record_items = $query->orderBy('network_phone_t.id desc')
            ->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($record_items as $item) {
            $row = $item->toArray();
            $row['username'] = $item->user ? $item->user->getShowName():'';
            $row['call_duration'] = MyLib::HMSByTime($item->call_duration);
            $row['call_result'] = MyLib::phoneCenterStatus($item->call_result);
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionDownloadFile(){
        $url = 'http://rec1.1ketong.com:8090/pull0/764/20190311/201903110955252026070922193.mp3';
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file = curl_exec($ch);
        curl_close($ch);
        if (!empty($file)) {
            $name = md5(rand(100, 200));
            $ext = 'mp3';
            $filename = $name . '.' . $ext;
            $destination = '/upload';
            $web_path = Yii::$app->getBasePath() . '/../frontend/web';
            if (!is_dir($web_path . $destination)) {
                mkdir($web_path . $destination);
            }
            $destination .= '/files';
            if (!is_dir($web_path . $destination))
                mkdir($web_path . $destination);
            $destination .= '/' . date('Ym');
            if (!is_dir($web_path . $destination))
                mkdir($web_path . $destination);
            $destination .= '/' . $filename;
            $file->saveAs($web_path . $destination);

//            $row['name'] = $file->baseName;
//            $row['size'] = $file->size;
//            $row['url'] = $destination;
//            $row['thumbnailUrl'] = $destination;
//            $row['deleteUrl'] = '';
//            $row['deleteType'] = 'DELETE';
//
//            $result['files'][] = $row;
//            return json_encode($result);
        }
    }


function getFile($url, $save_dir = '', $filename = '', $type = 0) {
    if (trim($url) == '') {
        return false;
    }
    if (trim($save_dir) == '') {
        $save_dir = './';
    }
    if (0 !== strrpos($save_dir, '/')) {
        $save_dir.= '/';
    }
    //创建保存目录
    if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
        return false;
    }
    //获取远程文件所采用的方法
    if ($type) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $content = curl_exec($ch);
        curl_close($ch);
    } else {
        ob_start();
        readfile($url);
        $content = ob_get_contents();
        ob_end_clean();
    }
    $size = strlen($content);
    //文件大小
    $fp2 = @fopen($save_dir . $filename, 'a');
    fwrite($fp2, $content);
    fclose($fp2);
    unset($content, $url);
    return array(
        'file_name' => $filename,
        'save_path' => $save_dir . $filename
    );
}

public function actionDownload(){
    $url = 'http://rec1.1ketong.com:8090/pull0/764/20190311/201903110955252026070922193.mp3';
    $save_dir = Yii::$app->getBasePath() . '/../frontend/web/download';

    $filename = "test.mp3";
    $res = $this->getFile($url, $save_dir, $filename, 1);
    var_dump($res);
}


    public function actionAssignPhone(){
        return $this->render('assign-phone');
    }

    public function actionAssignPhoneJson(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $user_items = UserT::find()->orderBy('username')->all();

        $phone_items = NetworkPhoneAssignT::find()
            ->leftJoin('user_t','user_t.id=network_phone_assign_t.user_id')
            ->orderBy('user_t.username')
            ->all();

        $data = [];
        $data['total'] = count($phone_items);
        $data['rows'] = [];
        foreach($phone_items as $item) {
            $row = $item->toArray();
            $row['username'] = $item->user->getShowName();
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionSubIndex(){
        $request = Yii::$app->request;
        $id = $request->get('phone_id',0);

        $assign_info = NetworkPhoneAssignT::findOne($id);

        return $this->render('sub-index',[
            'assign_info' => $assign_info
        ]);
    }

    public function actionSubIndexJson(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $id = $request->get('phone_id',0);
        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 10);

        $assign_info = NetworkPhoneAssignT::findOne($id);
        $sub_items = NetworkPhoneSubT::find()->where('assign_id='.$assign_info->id)->all();

        $data = [];
        $data['total'] = count($sub_items);
        $data['rows'] = [];
        foreach($sub_items as $item) {
            $row = $item->toArray();
            $row['status'] = '';
            if($item->bind_id != '') {
                $row['status'] = '已绑定';
            }
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        if($id > 0) {
            $info = NetworkPhoneAssignT::findOne(['id'=>$id]);
        } else {
            $info = new NetworkPhoneAssignT();
        }

        $user_items = UserT::find()->where('is_delete=0 and is_leave=0')->orderBy('username')->all();

        return $this->render('edit',[
            'info' => $info,
            'user_items' => $user_items
        ]);
    }

    public function actionSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $id = $request->post('id',0);
            $user_id = $request->post('user_id',0);
            $phone = $request->post('phone','');
            $is_double = $request->post('is_double',0);

            if($user_id == 0) {
                $result['msg'] = '请输入人员名称!';
                return $result;
            }

            if($phone == '') {
                $result['msg'] = '请输入电话号码!';
                return $result;
            }

            $tran = NetworkPhoneAssignT::getDb()->beginTransaction();
            try {
                $row = null;
                if($id > 0) {
                    $row = NetworkPhoneAssignT::findOne(['id'=>$id]);

                    $url = Yii::$app->params['userPanel']['phone_url'];
                    $token = Yii::$app->params['userPanel']['token'];

                    $params = [
                        'token' => $token,
                        'op' => 'edit',
                        'phone' => $phone,
                        'old_phone' => $row->phone
                    ];
                    $client = new Client();
                    $res = $client->request('POST', $url, [
                        'form_params' => $params,
                        'http_errors' => false,
                    ]);
                    if($res->getStatusCode() == 200) {
                        $obj = json_decode($res->getBody());
                        if($obj->code == 400) {
                            $result['msg'] = $obj->msg;
                            return $result;
                        }
                    }
                } else {
                    if($is_double == 0) {
                        $t = NetworkPhoneAssignT::findOne(['phone' => $phone]);
                        if ($t) {
                            $result['msg'] = '该电话号码，已经被使用!';
                            return $result;
                        }
                    }
                    $url = Yii::$app->params['userPanel']['phone_url'];
                    $token = Yii::$app->params['userPanel']['token'];

                    $params = [
                        'token' => $token,
                        'op' => 'add',
                        'phone' => $phone
                    ];
                    $client = new Client();
                    $res = $client->request('POST', $url, [
                        'form_params' => $params,
                        'http_errors' => false,
                    ]);
                    if($res->getStatusCode() == 200) {
                        $obj = json_decode($res->getBody());
                        if($obj->code == 400) {
                            $result['msg'] = $obj->msg;
                            return $result;
                        }
                    }
                    $row = new NetworkPhoneAssignT();
                }
                $row->user_id = $user_id;
                $row->phone = $phone;
                if(!$row->save()) {
                    throw new \Exception(print_r($row->getErrors(), true));
                }
                $tran->commit();

                $result['success'] = true;
                $result['msg'] = '保存成功';

            } catch(\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }

    public function actionDelete()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '删除失败';

        if($request->isPost) {
            $id = $request->post('id',0);

            if($id > 0) {
                $tran = NetworkPhoneAssignT::getDb()->beginTransaction();
                try {
                    $count = NetworkPhoneSubT::find()->where('assign_id='.$id)->count();
                    if($count>0){
                        $result['msg'] = '请先删除小号';
                        return $result;
                    }
                    $row = NetworkPhoneAssignT::findOne(['id'=>$id]);

                    $url = Yii::$app->params['userPanel']['phone_url'];
                    $token = Yii::$app->params['userPanel']['token'];

                    $params = [
                        'token' => $token,
                        'op' => 'delete',
                        'phone' => $row->phone
                    ];
                    $client = new Client();
                    $res = $client->request('POST', $url, [
                        'form_params' => $params,
                        'http_errors' => false,
                    ]);
                    if($res->getStatusCode() == 200) {
                        $obj = json_decode($res->getBody());
                        if($obj->code == 400) {
                            $result['msg'] = $obj->msg;
                            return $result;
                        }
                    }
                    $row->delete();

                    $result['success'] = true;
                    $result['msg'] = '删除成功';

                    $tran->commit();
                } catch(\Exception $e) {
                    $tran->rollBack();
                    $result['msg'] = $e->getMessage();
                }
            }
        }
        return $result;
    }

    public function actionSubEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $assign_id = $request->get('assign_id',0);
        if($id > 0) {
            $info = NetworkPhoneSubT::findOne(['id'=>$id]);
        } else {
            $info = new NetworkPhoneSubT();
        }

        return $this->render('sub-edit',[
            'info' => $info,
            'assign_id'=>$assign_id
        ]);
    }

    public function actionSubSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $id = $request->post('id',0);
            $assign_id = $request->post('assign_id',0);
            $phone = $request->post('phone');
            $is_called = $request->post('is_called');
            $is_double = $request->post('is_double');

            if($phone == '') {
                $result['msg'] = '请输入电话号码!';
                return $result;
            }

            $phone_info = NetworkPhoneAssignT::findOne(['id'=>$assign_id]);

            $tran = NetworkPhoneSubT::getDb()->beginTransaction();

            try {
                $row = null;
                if($id > 0) {
                    $row = NetworkPhoneSubT::findOne(['id'=>$id]);

                    $url = Yii::$app->params['userPanel']['phone_url'];
                    $token = Yii::$app->params['userPanel']['token'];
                    $params = [
                        'token' => $token,
                        'op' => 'sub_edit',
                        'phone' => $phone_info->phone,
                        'sub_phone' => $phone,
                        'old_sub_phone' => $row->phone
                    ];
                    $client = new Client();
                    $res = $client->request('POST', $url, [
                        'form_params' => $params,
                        'http_errors' => false,
                    ]);
                    if($res->getStatusCode() == 200) {
                        $obj = json_decode($res->getBody());
                        if($obj->code == 400) {
                            $result['msg'] = $obj->msg;
                            return $result;
                        }
                    }
                } else {
                    if($is_double == 0) {
                        $t = NetworkPhoneSubT
                            ::findOne(['phone' => $phone]);
                        if ($t) {
                            $result['msg'] = '该电话号码，已经被使用!';
                            return $result;
                        }
                    }

                    $url = Yii::$app->params['userPanel']['phone_url'];
                    $token = Yii::$app->params['userPanel']['token'];
                    $params = [
                        'token' => $token,
                        'op' => 'sub_add',
                        'phone' => $phone_info->phone,
                        'sub_phone' => $phone
                    ];
                    $client = new Client();
                    $res = $client->request('POST', $url, [
                        'form_params' => $params,
                        'http_errors' => false,
                    ]);
                    if($res->getStatusCode() == 200) {
                        $obj = json_decode($res->getBody());
                        if($obj->code == 400) {
                            $result['msg'] = $obj->msg;
                            return $result;
                        }
                    }

                    $row = new NetworkPhoneSubT();
                }
                $row->assign_id = $assign_id;
                $row->phone = $phone;
                $row->is_called = $is_called;
                $row->save();

                $tran->commit();
            } catch(\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }

            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }

    public function actionSubDelete()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '删除失败';

        if($request->isPost) {
            $id = $request->post('id',0);

            if($id > 0) {
                $tran = NetworkPhoneSubT::getDb()->beginTransaction();
                try {
                    $row = NetworkPhoneSubT::findOne(['id'=>$id]);
                    if($row->bind_id == ''){
                        $url = Yii::$app->params['userPanel']['phone_url'];
                        $token = Yii::$app->params['userPanel']['token'];
                        $params = [
                            'token' => $token,
                            'op' => 'sub_delete',
                            'sub_phone' => $row->phone
                        ];
                        $client = new Client();
                        $res = $client->request('POST', $url, [
                            'form_params' => $params,
                            'http_errors' => false,
                        ]);
                        if($res->getStatusCode() == 200) {
                            $obj = json_decode($res->getBody());
                            if($obj->code == 400) {
                                $result['msg'] = $obj->msg;
                                return $result;
                            }
                        }

                        $row->delete();

                        $result['success'] = true;
                        $result['msg'] = '删除成功';
                    }


                    $tran->commit();
                } catch(\Exception $e) {
                    $tran->rollBack();
                    $result['msg'] = $e->getMessage();
                }
            }
        }
        return $result;
    }

    public function actionUsercallIndex() {
        $request = Yii::$app->request;
        $company_type = $request->get('company_type',0);
        return $this->render('usercall-index',[
            'company_type' => $company_type
        ]);
    }
    public function actionUsercallIndexJson(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        set_time_limit(0);
        ini_set('memory_limit', '3072M');

        $request = Yii::$app->request;
        $begin_date = $request->get('begin_date',date('Y-m-d'));
        $end_date = $request->get('end_date',date('Y-m-d'));
        $caller = $request->get('caller','');
        $company_id = $request->get('company_id',0);
        $company_type = $request->get('company_type',0);//0显示全部，1只显示江西，2只显示湖北,3只显示个人
        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 10);

        $user_id = 0;

        $query = UserT::find()
            ->rightJoin('network_phone_assign_t','`network_phone_assign_t`.`user_id`=`user_t`.`id`');


        if($company_type == 3){
            $query->andWhere('user_t.id="'.$this->my->id.'"');
        }

        if($caller != ''){
            $query->andWhere('user_t.username="'.$caller.'"');
        }

        $query->andWhere('user_t.is_delete=0 and user_t.is_leave=0')->orderBy('user_t.username');

        if($caller != ''){
            $query1 = clone $query;
            $user = $query1->one();
            if($user){
                $user_id = $user->id;
            }
        }

        $total = $query->count();

        $query = $query->offset($offset)->limit($limit);

        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['total_call_num'] = $item->totalCallNum($begin_date,$end_date);
            $row['total_call_time_out'] = $item->totalCallTimeOut($begin_date,$end_date);
            $row['total_call_time'] = $item->totalCallTime($begin_date,$end_date);
            $row['call_in_total_num'] = $item->callInTotalNum($begin_date,$end_date);
            $row['call_in_suc_num'] = $item->callInSucNum($begin_date,$end_date);
            $row['call_in_suc_num_rate'] = number_format($item->callInTotalNum($begin_date,$end_date)? $item->callInSucNum($begin_date,$end_date)/$item->callInTotalNum($begin_date,$end_date) :0,2);
            $row['call_out_total_num'] = $item->callOutTotalNum($begin_date,$end_date);
            $row['call_out_suc_num'] = $item->callOutSucNum($begin_date,$end_date);
            $row['call_out_suc_num_rate'] = number_format($item->callOutTotalNum($begin_date,$end_date)?$item->callOutSucNum($begin_date,$end_date)/$item->callOutTotalNum($begin_date,$end_date):0,2) ;
            if($item->phoneStatus) {
                if($item->phoneStatus->is_phone==1) {
                    $row['phone_status'] = '<div style="background: #00B83F;width: 50px;">通话中</div>';
                } else {
                    $row['phone_status'] = '<div style="background: #b03d3d;width: 50px;">未通话</div>';
                }
            } else {
                $row['phone_status'] = '<div style="background: #b03d3d;width: 50px;">未通话</div>';
            }
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionUsercallIndexbak(){

        $request = Yii::$app->request;
        $begin_date = $request->get('begin_date','');
        $end_date = $request->get('end_date','');
        $caller = $request->get('caller','');

        $query = NetworkPhoneT::find()
            ->leftJoin('network_phone_assign_t','`network_phone_assign_t`.`phone`=`network_phone_t`.`caller`')
            ->leftJoin('user_t','`user_t`.`id`=`network_phone_assign_t`.`user_id`');

        if($begin_date != ''){
            $query = $query->where('network_phone_t.begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('network_phone_t.begin_date<="'.$end_date.'"');
        }
        if($caller != ''){
            $query = $query->andWhere('user_t.username="'.$caller.'"');
        }


        $record_items = $query
            ->groupBy('network_phone_t.begin_date, network_phone_assign_t.user_id')
            ->orderBy('network_phone_t.begin_date DESC, network_phone_assign_t.user_id ASC')
            ->all();






        return $this->render('usercall-index',[
            'record_items' => $record_items,
            'begin_date' => $begin_date,
            'end_date' => $end_date,
            'caller' => $caller
        ]);
    }


    public function actionAllcalltimeout(){

        $request = Yii::$app->request;
        $begin_date = $request->post('begin_date','');
        $end_date = $request->post('end_date','');
        $company_id = $request->post('company_id','');

        $result['success'] = false;
        $result['msg'] = '获取错误';
return $result;

        $query = NetworkPhoneT::find()->where('is_called=0')
            ->leftJoin('user_t','user_t.id=network_phone_t.user_id');
        if($begin_date != ''){
            $query = $query->andWhere('network_phone_t.begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('network_phone_t.begin_date<="'.$end_date.'"');
        }
        if($company_id != 0){
            $query = $query->andWhere('user_t.company_id='.$company_id);
        }
        $items =  $query->all();
        $i_all = 0;
        foreach ($items as $item){
            $i = $item->call_duration;
            $i_all += MyLib::HMSByTimeBuy($i);

        }

        $result['success'] = true;
        $result['msg'] = $i_all;
        return $result;
    }


}