<?php
/**
 * CRM项目默认类，此类在素玄系统内每个模块都有，供全局管理系统间握手使用
 * 
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 * 
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2017-10-17 $
 */
namespace app\index\controller;
use think\Controller;
use app\common\lib\redisQueue;
use think\Exception;
class Index extends Controller
{
    function _initialize() {
        if(!defined('IS_POST')){
            define('IS_POST', \think\Request::instance()->isPost());
        }
    }
    public function index()
    {   
       /*
        $fp = fopen('/data/git/php-securebox/test3.png', "r");
        $filesize = filesize('/data/git/php-securebox/test4.png');
        $content = fread($fp, $filesize);
        $file_content = chunk_split(base64_encode($content));
        // echo $file_content;
        // die;
        $data = [
            // 'app_code'  => $productId,
            // 'app_code'  => '',
            // 'babyId'    =>1852,
            'enName' =>'xiaozhanghai',
            'gender' =>1,
            'headPic'   =>$file_content,
            'nickName'  =>'小长还',
            'orderId'    => 'rj201110001',
            'pinyin'    =>'xiao3zhang3hai2',
            'productId' =>10055,

        ];
        $res = sx_call('5facdd623c5d9',$data);//体验单
        // $res = sx_call('5facfb0b8a233',['orderId'=>2046]);//查询
        // $res = sx_call('5facf6f6916ff',['preOrderId'=>2045,'productId'=>10058,'productType'=>3,'shop_code'=>'VVC001']);//正式单
        var_dump($res);
        die;
        */
        $a = [
            [
                'shop_code'=>'001',
                'money'=>100.12,
            ],
            [
                'shop_code'=>'002',
                'money'=>101.12,
            ],
            [
                'shop_code'=>'001',
                'money'=>101.12,
            ]
        ];
        $res = [];
        foreach ($a as $key => $value) {
            $res[$value['shop_code']]['money'] += $value['money'];
            $res[$value['shop_code']]['num'] += 1;
        }  

        dump($res);
        // /die;

        dump($a);  
        $b = array_unique(array_column($a,'shop_code'));
        dump($b);
        foreach ($b as $key => $value) {
            var_dump($value);
            $res = array_search($value, array_column($a,'shop_code'));
            var_dump($res);
        }




        // die;   
        echo '>>>>';

        $a = '13641009570';
        $key = md5('18231');
        $keyarr = str_split($key);
        $arr = str_split($a);
        var_dump($keyarr);
        var_dump($arr);
        foreach ($arr as &$v) {
            $v = decbin(ord($v));
        }
        // var_dump($arr);die;
        // echo $key;
        // echo ord($key);
        $a = '5';
        $b = 's';
        var_dump(ord($a));
        var_dump(ord($b));
        var_dump(decbin(ord($a)));
        var_dump(decbin(ord($b)));
        $c = ord($a) & ord($b);

        var_dump($c);
        $d = ($c ^ $b);
        var_dump(chr($d));

        // die;
        $this->redirect('crm/Index/index');

        // if($this->is_weixin()){
        //     $APPID='wxe1d66f5605ddc128';
        //     $REDIRECT_URI=urlencode('http://crm.sx.com/crm/Index/index/');
        //     $scope='snsapi_base';
        //     $scope='snsapi_userinfo';//需要授权
        //     $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$APPID.'&redirect_uri='.$REDIRECT_URI.'&response_type=code&scope='.$scope.'&state=STATE#wechat_redirect';
        //     $this->redirect($url);
        //     $this->redirect('crm/Index/index');
        // }else{
        //     $this->redirect('crm/Index/index');
        // }
    }
    public function menu(){
        $menuData=getAuth($type='menu');
        // $menuData=db('crm_s_menu')->where("status <> 99")->select();
        $menuList=treeData($menuData,$fid=0);
        $list = $this->toArray($menuList);
        echo $list;die;
        dump($menuList);
    }
    public function toArray($a,$i=1){
        $t1 = str_repeat("\t", $i);
        $t2 = str_repeat("\t", ++$i);
        $t3 = str_repeat("\t", ++$i);
        if(count($a) == 0){
            return "\r\n";
        }
        $str = "\r\n";
        foreach ($a as $key => $value) {
            $str .= $t1.'['."\r\n";
            $str .= $t2."'menu_name'=>'".$value['menu_name']."',\r\n";
            $str .= $t2."'menu_code'=>'".$value['menu_code']."',\r\n";
            $str .= $t2."'menu_url'=>'".$value['menu_url']."',\r\n";
            $str .= $t2."'menu_icon'=>'".$value['menu_icon']."',\r\n";
            $str .= $t2."'status'=>'".$value['status']."',\r\n";
            $children = $this->toArray($value['children'],$i);
            $str .= $t2."'children'=>"."\r\n".$t2."[".$children.$t2."]"."\r\n";
            $str .= $t1."],\r\n";
        }
        return $str;
    }
    ///判断是PC还是微信登录
    function is_weixin(){
        if ( strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') !== false ) {
            return true;
        }else{
            return false;
        }
    }
    public function histogram(){
        return $this->fetch();
    }
    public function login() {
        /*
        if(IS_POST){
            //处理登录请求
            $param['password'] = input('post.password');
            $param['staffname'] = input('post.staffname');
            $param['five'] = input('post.five');
            $res = controller('crm/Customer','lib')->login($param);
            return $res;
        }else{
            //return $this->fetch();
        }
        */
        $this->redirect('/crm/index/login');

    }
    function getClientIp(){
        $ret = [
            'code'=>200,
            'msg'=>'',
            'data'=>'',
        ];
        $ret['data']['ip'] = get_client_ip();

        return json($ret);
    }
    function loginQrShow() {

        if(\think\Request::instance()->isAjax()){
            
            
        }else{
            
        }
        $qrcodeInfo = session('qrlogincodeinfo');
        
        if(!$qrcodeInfo  || $qrcodeInfo['expire'] > time()){
            $mc = new \app\common\lib\mcInterface();
            $response = $mc->getLoginQrCode();
            if($response && $response['code'] == 200){
                $qrcodeInfo = $response['data'];
                session('qrlogincodeinfo',$qrcodeInfo);
            }
        }
        
        $qrcode = new \Endroid\QrCode\QrCode();
        $qrcode->setText($qrcodeInfo['qr_code']);
        echo $qrcode->writeString();
    }

    // 追踪记录  erp用
    public function trackInfo(){
        $is_erp = is_install('sx_erp');
        if ($is_erp === false) {
            return $this->error('没有安装erp系统');
        }

        $data = input();

      $number = $data['customer_number'];
        $cInfo = db('crm_c_customerinfo')
             ->where('customer_number', $number)
            ->field('id,customer_name,customer_sex,customer_tel,customer_wechat,mate_name,mate_sex,mate_tel,mate_wechat,consultation_type,is_valid,dj_staff,add_shop_name,sales_staff,shop_name')
            ->order('c_end_day, id desc')
            ->find();
        $this->assign('cInfo',$cInfo);
        // 查询追踪记录表
        $trackInfo = db('crm_c_salestrackinginfo')
            ->where('customer_id', $cInfo['id'])
            ->field('gtType, customer_name, customer_tel, customer_intention, consultation_type, tel_alltime, tel_static, sales_day, sales_staff, sales_remark')
            ->order('sales_day desc')
            ->select();
        $this->assign('track',$trackInfo);
        return $this->fetch();
    }

    // 订单详情  erp用
    public function orderInfo(){
        $is_erp = is_install('sx_erp');
        if ($is_erp === false) {
            return $this->error('没有安装erp系统');
        }
        $data = input();

        $order_sn  = $data['order_sn'];
        $customer_type = $data['customer_type'];
        $sign      = $data['sign'];
        $secret    = 'oUWKYeqCEojOvbmsynvWTctJSAVeoMZv';
        
        $auth = md5($order_sn.$customer_type.$secret);
        // var_dump($auth);
        // exit;
        if ($auth === $sign) {
            $erp = config('ext.app_config')['sx_erp'];
            $shop_type = session('shop_type');
            $tel = 1;
            if ($shop_type == 2) {
                $shop_type = 1;
                $addr= $erp['addr_child'];
                $url = $addr.'SX_ChildCrmApi/All_CustomerOrderInfo?Token=^******^&CustomerType='.$shop_type.'&Tel='.$tel.'&orderId='.$order_sn;
            }else{
                $shop_type = 0;
                $addr= $erp['addr'];
                $url = $addr.'SX_CrmApi/All_CustomerOrderInfo?Token=^******^&CustomerType='.$shop_type.'&Tel='.$tel.'&orderId='.$order_sn;
            }
            $dataErp = '[]';

            $response = requestERP($url, $dataErp);

            if ($response['Code'] == 200) {
                // 基础信息  订单表
                $baseInfo = $response['Data']['C_order'];
//                 print_r($baseInfo);die;
                $this->assign('baseInfo', $baseInfo);
                // 产品信息  消费项目
                $cpInfo = $response['Data']['C_page'];
                $this->assign('cpInfo', $cpInfo);
                // 摄影信息  
                $syInfo = $response['Data']['C_photo'];
                $this->assign('syInfo', $syInfo);
                // print_r($syInfo);
                // 选片信息 
                $xpInfo = $response['Data']['C_sp'];
                $this->assign('xpInfo', $xpInfo);
                // 收款信息
                $skInfo = $response['Data']['C_payment'];
                $this->assign('skInfo', $skInfo);
                // 化妆信息
                $hzInfo = $response['Data']['C_makeup'];
                $this->assign('hzInfo', $hzInfo);
                // 礼服信息
                $lfInfo = $response['Data']['C_dress'];
                $this->assign('lfInfo', $lfInfo);
                // var_dump($lfInfo);
            }
            
            $this->assign('order_sn', $order_sn);
            return $this->fetch();
        }else{
            return $this->error('签名错误'); 
        }
    }
    // 根据客资编号 （ customer_number ） 查看追踪记录
    public function getTrackInfo(){
        $app = config('ext.app_config');
        if (empty($all['sx_erp'])) {
            // return $this->error('没有安装erp系统');
        }
        $data = input();

        $customer_number = trim($data['customer_number']);
        $cid = db('crm_c_customerinfo')->where('customer_number', $customer_number)->value('id');
        // $customer_number = (int)$data['customer_number'];
        // 查询追踪记录表
        $trackInfo = db('crm_c_salestrackinginfo')
            ->where('customer_id', $cid)
            ->field('gtType, customer_name, customer_tel, customer_intention, consultation_type, tel_alltime, tel_static, sales_day, sales_staff, sales_remark')
            ->order('sales_day',desc)
            ->select();
        // echo db()->getLastSql();
        // var_dump($trackInfo);exit;
        $this->assign('track',$trackInfo);


        // 修改日志
        $changeLogs = controller("crm/Customer","lib")->getCustomerChangeLogs($cid);
        $info = [];
        foreach($changeLogs as $k=>$v){
            if(is_json($v['old_data']) || is_json($v['data'])){
                $oldDate = json_decode($v['old_data'], true);
                $oldDateStr = '';
                foreach ($oldDate as $kk => $vv) {
                    $key = translate('c_customerinfo',$kk);
                    if($kk == 'is_valid'){
                        $vv = getIsValid($vv);
                    }
                    if($kk == 'is_intostore'){
                        $vv = getIsIntostore($vv);
                    }
                    if($kk == 'is_loss'){
                        $vv = getIsLoss($vv);
                    }
                    if($kk == 'is_status'){
                        $vv = getIsStatusAttr($vv);
                    }
                    if($key){
                        $oldDateStr .= $key.'：'.$vv.'；<br>';
                    }
                }
                $newDate = json_decode($v['data'], true);

                $newDateStr = '';
                foreach ($newDate as $kkk => $vvv) {
                    if($kkk == 'is_valid'){
                        $vvv = getIsValid($vvv);
                    }
                    if($kkk == 'is_intostore'){
                        $vvv = getIsIntostore($vvv);
                    }
                    if($kkk == 'is_loss'){
                        $vvv = getIsLoss($vvv);
                    }
                    $key1 = translate('c_customerinfo',$kkk);
                    if($key1){
                        $newDateStr .= $key1.'：'.$vvv.'；<br>';
                    }
                }
                $info[$k]['oldDateStr'] = $oldDateStr;
                $info[$k]['newDateStr'] = $newDateStr;
                $info[$k]['create_time'] = $v['create_time'];
                $info[$k]['staff_name'] = $v['staff_name'];
            }else{
                $oldDate = json_decode($v['old_data'], true);
                $oldDateStr = $v['old_data'];
                foreach ($oldDate as $kk => $vv) {
                    $oldDateStr .= $kk.'：'.$vv.'；';
                }
                $newDate = json_decode($v['data'], true);
                $newDateStr = '';
                foreach ($newDate as $kk => $vv) {
                    $newDateStr .= $kk.'：'.$vv.'；';
                }
                $oldDateStr = $v['old_data'];
                $newDateStr = $v['data'];
                $info[$k]['oldDateStr'] = $oldDateStr;
                $info[$k]['newDateStr'] = $newDateStr;
                $info[$k]['create_time'] = $v['create_time'];
                $info[$k]['staff_name'] = $v['staff_name'];
            }
        }
        $this->assign('changeLogs', $info);    
        return $this->fetch();
    }

    //呼叫中心(七陌) 推送接口 通话结束Hangup 
    public function callCenterSevenStrangerHangup()
    {
        $params = input('get.');
        if(!$params){
            return json(['success'=>'false','message'=>'未获取到数据']);
        }
        // {"CallNo":"13581505156","CallSheetID":"268f1f0d-1dcc-4078-8b6c-b4ba797cb5de","CalledNo":"02136180048","CallID":"cc-ali-0-1622196178.196602","CallType":"normal","RecordFile":"monitor\/bj.txc.10.5\/20210528\/20210528-180300_T00000021813_10051260_13581505156_02136180048_10051260_cc-ali-0-1622196178.196602.mp3","Account":"T00000021813","Ring":"2021-05-28 18:02:58","Begin":"2021-05-28 18:03:09","End":"2021-05-28 18:03:15","QueueTime":"2021-05-28 18:03:00","ManyQueue_number":"10051260","Queue":"\u5750\u5e2d","HangupPart":"agent","Agent":"8000","Exten":"8000","AgentName":"8000","ActionID":"","DialoutStrVar":"","CallState":"Unlink","State":"dealing","FileServer":"https:\/\/pbx-bj-txc10.7moor.com","RT_UUID":"","CallStatus":"dealing","RT_SEND_URL":"","MonitorFilename":"https:\/\/pbx-bj-txc10.7moor.com\/monitor\/bj.txc.10.5\/20210528\/20210528-180300_T00000021813_10051260_13581505156_02136180048_10051260_cc-ali-0-1622196178.196602.mp3","RingTime":"1622196182.584156","RealState":"Ringing","Province":"\u5317\u4eac\u5e02","District":"\u5317\u4eac\u5e02","DistrictCode":"010","RingingTimestamp":"1622196182.584156","RingingDate":"2021-05-28 18:03:02"}

        $json = is_array($params) ? json_encode($params) : $params;

        $res = json_decode($json,true);
        //通话类型：dialout外呼通话,normal普通来电,transfer呼入转接,dialTransfer外呼转接
        if($res['CallType']){

            $log['hash'] = '呼叫中心(七陌)-通话结束';
            $log['api_url'] = '/index/index/callCenterSevenStrangerHangup';
            $log['result_code'] = '';
            $log['api_start_time'] = time();
            $log['api_end_time'] = microtime(true);
            $log['data'] = $json;

            api_log($log);

            $data = json_decode($params['DialoutStrVar'],true);
            if ($data['cid'] > 0 && $data['sales_staff_id'] > 0 && strlen($data['time']) == 10) {
                $data_t['cid'] = $data['cid'];
                $data_t['sales_staff_id'] = $data['sales_staff_id'];
                $data_t['time'] = $data['time'];
                $data_t['times'] = date("Y-m-d H:i:s",$data['time']);
                $data_t['txt'] = $json;
            }else{
                $data_t['time'] = $res['CallNo'];
                $data_t['times'] = $res['Ring'];
            }
            $data_t['create_time'] = date("Y-m-d H:i:s");

            try{
                db('crm_c_call_temporary')->insert($data_t);

                db()->commit();
                return true;
            }catch (\Exception $e){
                db()->rollBack();
                return false;
            }
        }
    }

    //呼叫中心(七陌) 推送接口 被呼振铃Ringing
    public function callCenterSevenStrangerRinging()
    {
        $params = input('get.');
        if(!$params){
            return json(['success'=>'false','message'=>'未获取到数据']);
        }
        //{"CallNo":"13581505156","CallSheetID":"c04813dd-37f8-4ba0-83b1-f22633fbdd14","CalledNo":"02136180048","CallID":"cc-ali-0-1622448260.203604","CallType":"normal","RecordFile":"","Account":"T00000021813","Ring":"2021-05-31 16:04:20","Begin":"","End":"","QueueTime":"2021-05-31 16:04:22","Queue":"\u5750\u5e2d","Agent":"8000","Exten":"8000","AgentName":"8000","ActionID":"","DialoutStrVar":"","CallState":"Ringing","State":"notDeal","FileServer":"https:\/\/pbx-bj-txc10.7moor.com","RT_SEND_URL":"","RT_UUID":"","CallStatus":"leak","RealState":"Ringing","Province":"\u5317\u4eac\u5e02","District":"\u5317\u4eac\u5e02","DistrictCode":"010","RingingTimestamp":"1622448264.531438","RingingDate":"2021-05-31 16:04:24"}

        $json = is_array($params) ? json_encode($params) : $params;

        $res = json_decode($json,true);
        //通话类型：dialout外呼通话,normal普通来电,transfer呼入转接,dialTransfer外呼转接
        if($res['CallType'] == 'normal' || $res['CallType'] == 'transfer'){

            $log['hash'] = '呼叫中心(七陌)-被呼振铃';
            $log['api_url'] = '/index/index/callCenterSevenStrangerRinging';
            $log['result_code'] = '';
            $log['api_start_time'] = time();
            $log['api_end_time'] = microtime(true);
            $log['data'] = $json;

            api_log($log);


            $ros = db('crm_s_call_man')->where('user',$res['Exten'])->find();

            try{
                
                $data_t['type'] = 2;
                $data_t['txt'] = $json;
                $data_t['create_time'] = date("Y-m-d H:i:s");
                $data_t['sales_staff_id'] = $ros['staff_id'];
                $data_t['time'] = $res['CallNo'];
                $data_t['times'] = $res['Ring'];

                db('crm_c_call_temporary')->insert($data_t);

                $message['id'] = db()->getLastInsID();
                
                if ($ros['staff_id']) {
                    
                    redisQueue::init()->publish('callCenterSeven'.$ros['staff_id'], $message);
                }

                db()->commit();
                return true;
            }catch (\Exception $e){
                db()->rollBack();
                return false;
            }
        }

    }

}
