<?php
/**
 * CRM 基本模块
 * 默认接口方法，此方法内定议基础框架所需要的方法，用于验证模块合法性，模块版本，对接基础架构中需要的方法
 * 此类不作任何业务逻辑
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2017-10-17 $
 */
namespace app\crm\controller;

use think\Controller;
use think\Exception;
use think\Request;
use app\common\lib\redisQueue;
use app\crm\lib\RunStatistics;

define('IS_POST', \think\Request::instance()->isPost());
class Index extends Controller
{
    private $moduleName = 'CRM基础模块';
    private $moduleVersion = '0.0.1';

    // public function test(){
    //     $res = new RunStatistics();
    //     // var_dump($res);
    // }

    public function test(){
        // session_start();

        // $info = json_decode(think_decrypt('MDAwMDAwMDAwMMmte96cqqqmktJpoLx1eWqzjYFhfHyDsr-7tLKViXDavGadz4HN06KPvX6CuHl2lbpsioGDooKrrtDSr32cps6xiJzdhM2pa4epZKmwhoWpso2BmXx8g6vHlcqolp5wlcmMc9CBzdOijat9ma51eqfHa5ygkqVyrL-7uKeWZIjOs517lZuVurKQmGWYxImFnbF8gpyVgXuoyNHRoYObgN6xeHaYhLels4S6eWOrdnWrtKOFZH-jfmmuzN2hl2WJzb6hi9mRupWlgdCfmbp6hWazs4qciIGOa7K3s2p9m67Ox2eDzJLQvq6cvWGZvIp5nbSignOEfqGMt6mzr4F2hM6wd3vNm9CqrpKtfqO7in6urqOnmYiBjmq-3c1sjHqMmrKeft6Qq7lqkq2JYLp6hWm_kIaciIGOab63vKCMeoyYvot63IHM26KbmJimxXhpqb6QaZx5o6ihvau7ao2snpm8fIaZhs2xs5CuhWG8eYlkvYGNZYqQh6S9q7tpjYaNzbx8hpeSuq2xkK6FY7CGfWW9gY1hfo2Kar2ru22BeYyZrZ2ozZuVzK-brGmaxGSCoK6jp5mBpLGBupO4jIF2eN2tnajNkdC6rJqYZZ66ZX6jx2x6lpKmf6y_tq9ufZ6vlrKhfpiHqdxqh7qJqq9jqGWzkIqdfn-xabS6vKKOiK-Wsot2lZG53GqGmIaZr4ioZbNrkWF9j7FptLe7r4F4r5aziHPQh6atrIHTepzEeWmpv2pxqpGAcq-9lbSujnmMzrOde6eMqMyNjpeXp692dZ2xfIKgk2pyrL67sKqOionVxqGUzYfNqayB05yqumV-pq6jp6l8fIOyxqqfr4xliZrHe4bNh82prIHUepy7ZIakyaVxqpGAcq-9lbSujnmMzrOdes2Epq6pm5dpnsWfaWXIfIFmfaKwob-6m6OMZInNyHuGzYfQmWqaraejq6B-oMmArJyVjIJux9G8q5Z1rs6-e4fbkbuuaZq9hqXGeGmpvpBpnHmjqKG9q7trgoaElrx8hpWGt7VrkK6FZa95hWiuoq-ZioCPr767sGiWiY3ayHpq1JKmrW-G4Imjq59hnMaQbZaTgHKyxru4qJZkbMvGoXfYkratb4HSqGGwrIWus4-wYX6Njmizz95pgomBzbGgqZWGzcewkqyoYbB5hayyarBhfo2KabSmr6t9n2jNxYtmypuqnbOZvoKgxGRlmr5rcZuKjIJurtGnsIKGgN2ynnqWht3PaoW6l2KvdXmnrqacqYmQi6S9lrhtl3mMzrOegteB0aavm5icYMOJaam9a4amioCOobTQm2mWea7YraJ_lJG7tmqb33lmr4WnnchrbJl_ooN7uajOjIZ4hM6wd3vYkbrQrpCZlKbFn6SayYGkp4qMgm6uza-yfZuuzshmat2ZlJ1pnb5ynKucn52uoq-Zkmx7pMfPn6iOdYCbraFqzJ2rtn-Fu4Zlw4mCdrSNgWKGkHFss6qbp4dip7bIrWKYhc7PooSpeqDFY2mdv5CwppKmnKG0zberfZ-B3r2LZs-Rldyhm5l-lsOJgZ20o4WjeaZ_osmq0mqOhYCbsYiG3YXNpbOF4HWor2VgcQ'), true);
        // var_dump($info);
        // exit;
        
        $cookieStaffId = (int)cookie('staff_id');
        echo '--45--cookieStaffId：'.$cookieStaffId.'<br />';
        echo '<hr />';
        $sessionStaffId = session('staff_id');
        echo '--48--sessionStaffId：'.$sessionStaffId.'<br />';
        echo '<hr />';
        $cookieSessionId = cookie('session_id');
        echo '--51--cookieSessionId：'.$cookieSessionId.'<br />';
        $sessionId = session('session_id');
        echo '<hr />';
        echo '--54--sessionId：'.$sessionId.'<br />';
        echo '--55--senssion_id：'.session_id().'<br />';
        echo '<hr />';
        if(!$cookieStaffId || !$cookieSessionId){
            echo '--58--cookieStaffId为空，或者cookieSessionId为空 <br />';
            echo '<hr />';
            //cookie内值一定要有，5天自动登录也就是cookie存在时间长一点而以。
            // return false;
        }
        $cacheStaffInfo = cache('staffInfo_'.$cookieStaffId);
        echo '--64--cacheStaffInfo：';
        var_dump($cacheStaffInfo);
        echo '<hr />';
        var_dump(session(''));
        echo '<hr />';
        if(!$cacheStaffInfo){
            echo '--68--cacheStaffInfo为空'.'<br />';
            echo '<hr />';
            // return false;
        }
        if($cacheStaffInfo['session_id'] != $cookieSessionId){
            echo "--73--cacheStaffInfo['session_id'] 不等于 cookieSessionId".'<br />';
            echo '<hr />';
            //cookie里与cache里不一至，直接退出。
            //注意，如果5天自动登录，有可能session里没有了。
            if($detailError){
                echo '--78--$detailError =用户在别的地方登录'.'<br />';
                echo '<hr />';
                // return array('code'=>ERR_LOGIN_OTHERLOGIN,'msg'=>'用户在别的地方登录','data'=>array());
            }else{
                echo '--82--no $detailError'.'<br />';
                echo '<hr />';
                // return false;
            }
        }
        $cacheStaffInfo['active'] = time();
        if(!$sessionStaffId || $sessionStaffId != $cookieStaffId || $sessionId != $cookieSessionId){
            echo '--89--sessionStaffId不存在，或者sessionStaffId不等于cookieStaffId，或者sessionId不等于cookieSessionId'.'<br />';
            echo '<hr />';
            //session 没了，但cookie还有，且与cache里一至
            //更新cache到session
            saveLoginSessions($cacheStaffInfo);
            $sessionStaffId = $cacheStaffInfo['staff_id'];
            $sessionId = $cacheStaffInfo['session_id'];
        }
        if($cookieStaffId == $sessionStaffId && $cookieSessionId == $sessionId){
            echo '--98--cookieStaffId等于sessionStaffId，并且cookieSessionId等于sessionId'.'<br />';
            echo '<hr />';
            //登录没问题
            if($cacheStaffInfo['keep_login'] == 1){
                echo "--102--cacheStaffInfo['keep_login'] == 1".'<br />';
                echo '<hr />';
                cache('staffInfo_'.$cookieStaffId, json_encode($cacheStaffInfo),432000);
            }else{
                echo "--106--cacheStaffInfo['keep_login'] != 1".'<br />';
                echo '<hr />';
                cache('staffInfo_'.$cookieStaffId, json_encode($cacheStaffInfo));
            }
            // return true;
        }else{
            //登录有问题
            if($detailError){
                echo $detailError.'<br />';
                echo '<hr />';
                if($cookieStaffId == $sessionStaffId){
                    echo '--117--cookieStaffId等于sessionStaffId'.'<br />';
                    echo '<hr />';
                    $res = array('code'=>ERR_LOGIN_OTHERLOGIN,'msg'=>'用户在别的地方登录','data'=>array());
                }else{
                    $res = array('code'=>ERR_LOGIN_UNLOGIN,'msg'=>'用户未登录','data'=>array());
                }
            }else{
                echo '--124--'.$detailError.'<br />';
                echo '<hr />';
                $rse = false;
            }
            print_r('--128--'.$res);
            // return $res;
        }
    }
    // public function test(){
    //     // $listName = 'fpCustomerList';
    //     echo md5('nonce=1665699147&timestamp=1516171202&token=5e1ae926a4fe25ab9ca43861a252deb6');
    //     exit();
    //     $urlParams = [
    //         'cid'=>2,
    //     ];
    //     var_dump(url('crm/weixin/receiveCustomer',$urlParams,'',true));
    //     echo Request::instance()->url(true).'-------';
    //     // $msg = redisQueue::init()->blPop($listName,10);
    //     // var_dump($msg);
    //     $wxConfirmUrl = url('index/index/wxconfirm','','',true);
    //     echo $wxConfirmUrl;
    //     //return $this->fetch();
    // }

    // public function testErp(){
    //     $url = 'http://192.168.0.15:8033/SXWebErpAppStaff/SX_OpenGuestInfo?Token=^******^';

    //     $data['Customer_name'] = '安宁';
    //     $data['Customer_tel']  = '13466661111';

    //     $dataN = json_encode($data);
    //     $response = requestERP($url, $dataN);
    //     var_dump($response);
    // }

    public function index() {
        /*  $admin_uin = 9509956;
        $uin = 9509956;
        $strid = '';
        $appid = '8a7f10ef-e6d5-4711-990a-98579bef06e7';
        $appkey = 'sign';
        $ct = time();
        $secretkey = strtoupper(md5($appid.'*(**)*'.$appkey));
        $sign = strtoupper(md5("$admin_uin&$uin&$strid&$appid&$secretkey&$ct"));
        $url = "http://vip6300.tq.cn/vip/open/auth/token?admin_uin=$admin_uin&uin=$uin&strid=$strid&appid=$appid&ct=$ct&sign=$sign";
        dump(httpRequest($url));die;
        header("Location:$url");*/
        //判断是PC还是微信登录，
        if($this->is_weixin()){
            // $appid = "wxe1d66f5605ddc128";
            // $secret = "ad1315cc82c05aea4ebdc63e20104cf0";
            $openId = session('openid');
            if(!$openId){
                $code = $_GET['code'];
                if(empty($code)){
                    get_wx_openid('index');
                }else{
                    $res = sx_call('5a0e5f4ced930', ['code'=>$code]);
                    if($res['code'] == 200){
                        $openId = $res['data']['openid'];
                    }
                    session('openid',$openId);
                }
            }
            cookie('code',$code);
            cookie('open',$openId);
            $autoLogin = sx_call('5a2a39b803dc2', ['open_id' => $openId]);
            if ($autoLogin['code'] == 200) {
                $autoLogin['data']['staff_id'] = $autoLogin['data']['id'];
                $loginres = controller('crm/Customer', 'lib')->setLoginEnv($autoLogin['data'], 'wx', 'auto');
                if (!$loginres) {
                    return $this->fetch('index/wx_login');
                }else{
                    if(session('return_url')){
                        $returnUrl = session('return_url');
                        session('return_url',null);
                        $this->redirect($returnUrl);
                    }else{
                        $this->redirect('crm/Customer/wx_index');
                    }
                }
            } else {
                return $this->fetch('index/wx_login');
            }
        }elseif (is_mobile()){
            if(check_login()){
                $this->redirect('crm/Customer/wx_index');
            }else{
                return $this->fetch('index/wx_login');
            }
        }else{
            // echo '111';
            // exit;
            if(check_login()){

                // $res = controller('crm/Customer', 'lib')->getStaffOnlineStatus(session('staff_id'));
                // var_dump($res);
                // exit;

                // redis  订阅消息
                // $message = array(
                //     'send_type' => 3,
                //     'receive_id'=>session('staff_id'),
                //     'time_out'=>60,
                // );
                // $channel = 'notice';
                // $res = \app\common\lib\redisQueue::init()->publish($channel, $message);
                // exit;
                return $this->redirect('crm/Customer/index');
            }else{
                return $this->redirect('/login.html');
            }
        }
    }

    function wxLogin(){
        return $this->fetch('index/wx_login');
    }
    ///判断是PC还是微信登录
    function is_weixin(){
        if(config('ignore_weixin_oauth')) return false;
        if ( strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') !== false ) {
            return true;
        }else{
            return false;
        }
    }
    //找回密码
    public function findPassword(){
        return $this->fetch();
    }
    //找回密码
    public function resetPassword(){
        dump(input('post.'));
    }
    public function login() {
        testTime(__FILE__,__LINE__);

        if(IS_POST){
            testTime(__FILE__,__LINE__);
            //处理登录请求
            $param['password'] = input('post.password');
            $param['staffname'] = input('post.staffname');
            $param['five'] = input('post.five');
            $pageVersion = input('post.v');
            if(version_compare($pageVersion, APP_VERSION,'<')){
                cleanStaticHtml();
            }
            testTime(__FILE__,__LINE__);
            $res = controller('crm/Customer','lib')->login($param);
            testTime(__FILE__,__LINE__);
            $remind = getRemind(session('brandclass_id'));
            if ($res['code']==200 && $remind['login']) {
                // 微信模板消息
                $content = [
                    'touser'       => session('staff_id'),
                    'template_id'  => OPENTM_DL,
                    'data'         => [
                        'first'=>[
                            'value'=> '您好,'.session('staff_name').',您已成功登录客资系统',
                            'color'=> '#173177'
                        ],
                        'time'=>[
                            'value'=> date('Y-m-d H:i:s'),
                            'color'=> '#173177'
                        ],
                        'ip'=>[
                            'value'=> get_client_ip(),
                            'color'=> '#173177'
                        ],
                        'reason'=>[
                            'value'=> '如果不是本人操作，可能您的密码已泄露，请及时更改密码。',
                            'color'=> '#173177'
                        ]
                    ]
                ];
                $send_data['content'] = json_encode($content);
                // sendMsg($send_data);

                push_list('sendMsg', $send_data);
            }
            // var_dump($res);exit();
            return $res;
        }else{
            // var_dump(session('return_url'));
            // exit;
            if(!file_exists(ROOT_PATH.'public/login.html')){
                if(!is_writable(ROOT_PATH.'public')){
                    echo "系统加载失败，服务器目录：".ROOT_PATH.'public/'."不可写。";
                    exit();
                }
                file_put_contents(ROOT_PATH.'public/login.html', $this->fetch('login'));
            }
            $this->redirect('/login.html');
            // return $this->fetch('login');
        }
    }

    /**
     * 返回本模块基本配置信息
     *
     * @return String 模块名称，公共方法定义
     */
    public function getModuleInfo() {
        $info = array('name'=>  $this->moduleName,'version'=>  $this->moduleVersion);

        return json_encode($info);
    }
    //输入用户名，密码，绑定,插入session，进入主页面
    public function WX_login(){
        $param['password'] = input('post.password');
        $param['staffname'] = input('post.staffname');
        $param['five'] = input('post.five');
        $param['open_id'] = session('openid');
        $res = controller('crm/Customer','lib')->wx_login($param);
        return $res;
    }
    function scanSuccess(){
        $this->assign('qrcodeId',input('id'));
        return $this->fetch();
    }
    function loginQrShow() {
        $id  =input('id');
        $id = $id?$id:get_rand_string();
        $qrcodeInfo = session('qrlogincodeinfo_'.$id);
        $loginIp = get_client_ip();
        if(!$qrcodeInfo){
            $response = sx_call('5a1027da4e9c1',['login_ip'=>$loginIp]);
            if($response && $response['code'] == 200){
                $qrcodeInfo = $response['data'];
                session('qrlogincodeinfo_'.$id,$qrcodeInfo);
            }
        }else{
            $response = sx_call('5a1027da4e9c1',array('qr_code'=>$qrcodeInfo['qr_code'],'login_ip'=>$loginIp));
        }

        if(\think\Request::instance()->isAjax()){

            if($response && $response['code'] == 200){
                unset($response['data']['qr_code'],$response['data']['qr_code_url']);
                $response['data']['code_id'] = $id;
                if($response['data']['expire']>time()){
                    //未过期
                    $response['data']['expired'] = 0;
                    ///*
                    if($response['data']['state'] == 'logined'){
                        //本地登录
                        $res = controller('crm/Customer','lib')->setLoginEnv($response['data'],'PC','scan');
                        if($res){
                            $returnUrl = session('return_url');
                            if($returnUrl){
                                $response['data']['return_url'] = $returnUrl;
                            }
                            return $response;
                        }else{
                            session('qrlogincodeinfo_'.$id,null);
                            return ['code'=>500,'msg'=>'登录失败','data'=>array('state'=>'error')];
                        }
                    }//*/
                }else{
                    $response['data']['expired'] = 1;
                }
            }else{
                $response['data']['expired'] = 1;
            }
             return $response;

        }else{

            $qrcode = new \Endroid\QrCode\QrCode();
            $qrcode->setText($qrcodeInfo['qr_code_url']);
            echo $qrcode->writeString();

        }
    }
    function bindWeixin(){
        //绑定微信
        $wxCode = input('get.code');
        if($wxCode){
            $wxUserInfo = sx_call('5a0e5f4ced930', ['code'=>$wxCode]);
            if($wxUserInfo['code'] == 200){
                $wxUserInfo = $wxUserInfo['data'];
            }else{
                exit('无法获取用户微信信息。');
            }
            if(!$wxUserInfo){
                exit('无法获取用户微信信息。');
            }
            $bindInfo = session('bind_info');
            if(!$bindInfo['staff_id'] || !$bindInfo['bind_code']){
                $this->assign('error','信息已过期，请重新扫码绑定');
                $this->fetch('bind_error');
            }
            $cacheCode = cache('bindWX_'.$bindInfo['staff_id']);

            if(!$cacheCode || $bindInfo['bind_code'] != $cacheCode['code'] || $cacheCode['state'] != 'init'){
                $this->assign('error','信息已过期，请重新扫码绑定.');
                return $this->fetch('bind_error');
            }
            //更新用户OPENID
            $data = [
                'staffname'=>$cacheCode['staffname'],
                'password'=>$cacheCode['password'],
                'open_id'=>$wxUserInfo['openid'],
            ];
            $bindRes = sx_call('5a2239cf24883', $data);
            if($bindRes['code'] == 200){
                //绑定成功
                $cacheCode['state'] = 'binded';
                cache('bindWX_'.$bindInfo['staff_id'],$cacheCode);
                return $this->fetch('bind_success');
            }else{
                return $this->fetch('bind_error');
            }

            exit();
        }
        $cacheCode = cache('bindWX_'.input('get.staff_id'));
        if(!$cacheCode){
            $this->assign('error','信息已过期，请重新扫码绑定.');
            return $this->fetch('bind_error');
        }
        session('bind_info',array('staff_id'=>input('get.staff_id'),'bind_code'=>input('get.bind_code')));
        //生成获取OPENID的URL地址
        // $returnUrl = urlencode(url('bindWeixin','','',true));
        // $mcaddr = config('ext.app_config');
        // $mcaddr = $mcaddr['sx_mc']['addr'];
        // echo $mcaddr.'/getopenid?get_type=2&return_url='.$returnUrl;
        // exit();
        $this->assign('url',  get_wx_openid('bindWeixin',true));
        return $this->fetch('bind_confirm');
    }
    //移动端客资提报（扫码进入的页面）
    public function appTB(){
        $param = input('param.');
        $param['customer_channel'] = urldecode($param['customer_channel']);
        if($param['introducer_name']){
            $param['introducer_name'] = urldecode($param['introducer_name']);
        }
        //根据shop_code获取shop_name
        $shop = sx_call('5a005e0038270',array('shop_code'=>$param['shop_code']));
        $param['shop_name'] = $shop['data'][0]['shop_name'];
        $shop1 = sx_call('5a005e0038270',array('shop_code'=>$param['add_shop_code']));
        $param['add_shop_name'] = $shop1['data'][0]['shop_name'];
        if($param['customer_type'] == 2){//转介绍
            //客户意向
            $intention=controller("Customer","lib")->intention(array('shop_code'=>$param['shop_code']));
            $this->assign('intention',$intention);
            $this->assign('info',$param);
            return $this->fetch('jstibao');
        }else{//新客资
            //客户意向
            $intention=controller("Customer","lib")->intention(array('shop_code'=>$param['shop_code']));
            $this->assign('intention',$intention);
            $this->assign('info',$param);
            return $this->fetch('kztibao');
        }
    }
    public function appAddCustomer(){
        $param = input('post.');
        $str = md5(trim($param['customer_tel']).trim($param['customer_qq']).trim($param['customer_wechat']));
        if(session('sub_validate') == $str){
            session('sub_validate',null);
            $returnData = array('code' => 700, 'msg' => '客资录入正在处理中，请稍后...');
            return json($returnData);
        }else {
            session('sub_validate', $str);
            /*$arr = controller('Customer', 'lib')->isRepeat($param['brandclass'], $param['customer_tel'], $param['customer_wechat'], $param['customer_qq']);
            if ($arr['id']) {
                session('sub_validate',null);
                $returnData = array('code' => 300, 'msg' => '手机号，微信，qq中有一项已存在客资中');
                return json($returnData);
            }*/
            if (empty($param['add_shop_code']) || $param['add_shop_code'] == '0') {
                session('sub_validate',null);
                $returnData = array('code' => 301, 'msg' => '无法获取门店信息，不可录入客资');
                return json($returnData);
            }
            //查询归属地是否筛客
            $b_is_sk = controller("Customer", "lib")->is_sk($param['shop_code']);
            if ($b_is_sk == 1 || session('is_sk') == 1) {
                $param['is_sk'] == 1;
                //未选择筛客人则随机
                if (!$param['sk_staff_id']) {
                    $sklist = controller("Customer", "lib")->sklist($param['shop_code'] . ',' . $param['add_shop_code']);
                    $rand = rand(0, count($sklist) - 1);
                    $arr = $sklist[$rand];
                    if (!empty($arr)) {
                        $param['sk_staff_id'] = $arr['id'];
                        $param['sk_staff'] = $arr['staffname'];
                    }

                }
            }
            $staffInfo = getStaffInfoById($param['dj_staff_id']);
            $param['dj_department_id']=$staffInfo['department_id'];

            $res = controller("Customer", "lib")->addCustomer($param);
            if($res['code'] == 201){
                session('sub_validate',null);
                $returnData = array('code' => 300, 'msg' => '手机号，微信，qq中有一项已存在客资中');
                return json($returnData);
            }
            if ($res) {
                $customerInfo = db('CCustomerinfo')->where('id', $res)->find();
                $record['gtType'] = 4;
                $record['customer_id'] = $res;
                $record['customer_name'] = $customerInfo['customer_name'];
                $record['customer_number'] = $customerInfo['customer_number'];
                $record['sales_staff_id'] = $customerInfo['dj_staff_id'];
                $record['sales_staff'] = $customerInfo['dj_staff'];
                $record['sales_staff_number'] = $customerInfo['dj_staff_number'];
                $record['shop_name'] = $customerInfo['shop_name'];
                $record['shop_code'] = $customerInfo['shop_code'];

                $record['sales_remark'] = '手机二维码录入';

                $record['sales_day'] = date('Y-m-d H:i:s', time());
                db('c_salestrackinginfo')->insert($record);
                cache('getCustomerTrackInfos' . $res, null);
//                getSalesTracking($res);
                session('sub_validate',null);
                return json(array('msg' => '提报成功', 'code' => 200));
            } else {
                session('sub_validate',null);
                return json(array('msg' => '提报失败', 'code' => 100));
            }
        }
    }

    //客资录入第三方接口
    public function addCustomerThird(){
        $param = input();
        $token = $param['token'];
        $info = db('s_customer_interface')->where('token',$token)->find();
        $arr = json_decode($info['field_config'],true);

        $id = db('s_customer_interface')->where('token',$token)->where('status',1)->where('is_delete',2)->value('id');

        $dData['data'] = json_encode($param);
        $dData['ip'] = getThirdParams($arr['ip'],$param);//$param[$arr['ip']];
        $dData['pid'] = $id;
        $dData['create_time'] = date('Y-m-d H:i:s');
        $dData['result_code'] = 200;
        $dData['error_reason'] = '';

        $staff_name = getThirdParams($arr['staff_name'],$param);//$param[$arr['staff_id']];
        $url = '5a19201a33c20';
        $res = sx_call($url,['staffname'=>$staff_name,'get_leave'=>2]);
        if($res['code'] == 200){
            $staffId = $res['data'][0]['id'];
            $staffInfo = $res['data'][0];
        }else{
            $dData['result_code'] = 300;
            $dData['error_reason'] = '未获取到提报人ID';
            db('s_customer_interface_detail')->insert($dData);
            $returnData = array('code' => 200,'msg' =>'未获取到提报人ID');
            return json($returnData);
        }
        $data['customer_tel'] = getThirdParams($arr['customer_tel'],$param);//$param[$arr['customer_tel']];
        if (!check_tel($data['customer_tel'])) {
        	$dData['result_code'] = 300;
            $dData['error_reason'] = '手机号输入错误';
            db('s_customer_interface_detail')->insert($dData);
            $returnData = array('code' => 200,'msg' =>'手机号输入错误');
            return json($returnData);
        };
        $data['customer_name'] = getThirdParams($arr['customer_name'],$param);//$param[$arr['customer_name']];
        $data['customer_sex'] = getThirdParams($arr['customer_sex'],$param);//$param[$arr['customer_sex']];
        $data['customer_qq'] = getThirdParams($arr['customer_qq'],$param);//$param[$arr['customer_qq']];
        $data['customer_wechat'] = getThirdParams($arr['customer_wechat'],$param);//$param[$arr['customer_wechat']];
        $data['customer_channel'] = getThirdParams($arr['customer_channel'],$param);//$param[$arr['customer_channel']];
        $data['access_model'] = getThirdParams($arr['access_model'],$param);//$param[$arr['access_model']];
        $data['consultation_type'] = getThirdParams($arr['consultation_type'],$param);//$param[$arr['consultation_type']];
        $data['customer_remark'] = getThirdParams($arr['customer_memo'],$param);//$param[$arr['consultation_type']];
        $data['customer_cource'] = $arr['customer_cource'];//$param[$arr['consultation_type']];
        $data['channel_plan_number'] = getThirdParams($arr['channel_plan_number'],$param);
        $data['ad_page'] = getThirdParams($arr['ad_page'],$param);
        $data['customer_label'] = getThirdParams($arr['customer_label'],$param);
        $dData['staff_id'] = $staffId;
        if(empty($id)){
            $dData['result_code'] = 300;
            $dData['error_reason'] = '未获取到接口ID';
            db('s_customer_interface_detail')->insert($dData);
            $returnData = array('code' => 200,'msg' =>'未获取到接口ID');
            return json($returnData);
        }

        if(empty($staffId)){
            $dData['result_code'] = 300;
            $dData['error_reason'] = '未获取到登记人ID';
            db('s_customer_interface_detail')->insert($dData);

            $returnData = array('code' => 200,'msg' =>'未获取到登记人ID,客资录入失败');
            return json($returnData);
        }
        if(empty($data['customer_tel']) && empty($data['customer_qq']) && empty($data['customer_wechat'])){
            $dData['result_code'] = 300;
            $dData['error_reason'] = '联系方式未填写';
            db('s_customer_interface_detail')->insert($dData);

            $returnData = array('code' => 200,'msg' =>'客资录入失败，至少要填写一项联系方式');
            return json($returnData);
        }
        //登记人信息
        // $staffInfo = controller('crm/Customer','lib')->get_staff_info(['staff_id'=>$staffId]);
        $shopInfo = controller('crm/Customer','lib')->get_shop(['shop_code'=>$staffInfo['shop_code']]);
        $shopInfo = $shopInfo[0];
        /*//检查客资是否重复
        $arr=controller('crm/Customer','lib')->isRepeat($shopInfo['brandclass'],$data['customer_tel'],$data['customer_wechat'],$data['customer_qq']);

        if(!empty($data['customer_tel'])){
            if(!preg_match("/^1[3|4|5|7|8|9][0-9]{9}$/", $data['customer_tel'])){//手机号格式
                $dData['result_code'] = 300;
                $dData['error_reason'] = '手机号格式错误';
                db('s_customer_interface_detail')->insert($dData);

                $returnData = array('code' => 200,'msg' =>'手机号格式错误,客资录入失败');
                return json($returnData);
            }
        }

        if($arr){
            $dData['result_code'] = 100;
            $dData['error_reason'] = '客资重复';
            db('s_customer_interface_detail')->insert($dData);

            $returnData = array('code' => 200,'msg' =>'客资重复,录入失败');
            return json($returnData);
        }*/
        if(empty($staffInfo['shop_code'])){
            $dData['result_code'] = 300;
            $dData['error_reason'] = '无法获取门店信息，不可录入客资';
            db('s_customer_interface_detail')->insert($dData);

            $returnData = array('code' => 200,'msg' =>'无法获取门店信息,客资录入失败');
            return json($returnData);
        }
        //检查渠道，来源，消费类型
        $conditions['customer_channel'] = $data['customer_channel'];
        $conditions['access_model'] = $data['access_model'];
        $conditions['consultation_type'] = $data['consultation_type'];
        $lrMust = db_config('lr_must_'.$staffInfo['brandclass_id']);
        $lrMust = explode(',',$lrMust);
        if(in_array('customer_channel',$lrMust) && empty($data['customer_channel'])){
            $dData['result_code'] = 301;
            $dData['error_reason'] = '渠道名称未填写';
            db('s_customer_interface_detail')->insert($dData);

            $returnData = array('code' => 200,'msg' =>'渠道名称未填写,客资录入失败');
            return json($returnData);
        }
        if(in_array('consultation_type',$lrMust) && empty($data['consultation_type'])){
            $dData['result_code'] = 302;
            $dData['error_reason'] = '消费类型未填写';
            db('s_customer_interface_detail')->insert($dData);

            $returnData = array('code' => 200,'msg' =>'消费类型未填写,客资录入失败');
            return json($returnData);
        }
        if(in_array('access_model',$lrMust) && empty($data['access_model'])){
            $dData['result_code'] = 303;
            $dData['error_reason'] = '获取方式未填写';
            db('s_customer_interface_detail')->insert($dData);

            $returnData = array('code' => 200,'msg' =>'获取方式未填写,客资录入失败');
            return json($returnData);
        }
        $all_id=controller('crm/Customer','lib')->get_set_id($conditions,$staffInfo['shop_code'],$shopInfo['belong_shop_code']);
        if(!empty($all_id)){
            if($data['customer_channel']&&empty($all_id['customer_channel_id'])){
                $dData['result_code'] = 300;
                $dData['error_reason'] = '渠道名称填写有误';
                db('s_customer_interface_detail')->insert($dData);

                $returnData = array('code' => 200,'msg' =>'渠道名称填写有误,客资录入失败');
                return json($returnData);
            }else{
                $data['customer_channel_id'] = $all_id['customer_channel_id'];
            }
            if($data['consultation_type']&&empty($all_id['consultation_type_id'])){
                $dData['result_code'] = 300;
                $dData['error_reason'] = '消费类型填写有误';
                db('s_customer_interface_detail')->insert($dData);

                $returnData = array('code' => 200,'msg' =>'消费类型填写有误,客资录入失败');
                return json($returnData);
            }else{
                $data['consultation_type_id'] = $all_id['consultation_type_id'];
            }
            if($data['access_model']&&empty($all_id['access_model_id'])){
                $dData['result_code'] = 300;
                $dData['error_reason'] = '获取方式填写有误';
                db('s_customer_interface_detail')->insert($dData);

                $returnData = array('code' => 200,'msg' =>'获取方式填写有误,客资录入失败');
                return json($returnData);
            }else{
                $data['access_model_id'] = $all_id['access_model_id'];
            }
            if($data['customer_cource']&&$all_id['customer_cource_id']){
                $data['customer_cource_id'] = $all_id['customer_cource_id'];
            }
        }
        //准备插入数据库
        $data['dj_staff_id']=$staffId;
        $data['dj_staff']=$staffInfo['staffname'];
        $data['dj_staff_number']=$staffInfo['staffnumber'];
        $data['customer_type']=1;
        $data['add_shop_name']=$staffInfo['shop_name'];
        $data['add_shop_code']=$staffInfo['shop_code'];
        $data['shop_name']= $shopInfo['belong_shop_name'];
        $data['shop_code']= $shopInfo['belong_shop_code'];
        $data['brandclass']= $staffInfo['brandclass'];
        $data['brandclass_id']= $staffInfo['brandclass_id'];

        //筛客
        $work_type=explode(',',trim($staffInfo['main_work_type'].','.$staffInfo['work_type'],','));
        if(!in_array(RECEIVE_WORK_TYPE,$work_type)) {//工作类型不是话务
            //查询归属店是否筛客
            $b_is_sk = controller("Customer", "lib")->is_sk($shopInfo['belong_shop_code']);
            if($b_is_sk ==1 || session('is_sk') == 1){
                $data['is_sk'] == 1;
                //未选择筛客人则随机
                if(!$data['sk_staff_id']){
                    $sklist = controller("Customer", "lib")->sklist('',24);
                    $rand = rand(0,count($sklist)-1);
                    $arr = $sklist[$rand];
                    if(!empty($arr)){
                        $data['sk_staff_id'] = $arr['id'];
                        $data['sk_staff'] = $arr['staffname'];
                    }
                }
            }
        }
        if($data['is_sk']!=1)  $data['is_already_sk']=1;
        $data['dj_department_id']=$staffInfo['department_id'];
        $res = controller("crm/Customer", "lib")->addCustomer($data);
        if($res['code'] == 201){
            $dData['result_code'] = 100;
            $dData['error_reason'] = '客资重复';
            db('s_customer_interface_detail')->insert($dData);

            $returnData = array('code' => 200,'msg' =>'客资重复,录入失败');
            return json($returnData);
        }
        if($res === false){
            $dData['result_code'] = 400;
            $dData['error_reason'] = '插入客资表出错';
            db('s_customer_interface_detail')->insert($dData);

            $returnData = array('code' => 200,'msg' =>'客资录入失败');
            return json($returnData);
        }else{
            db()->startTrans();
            try{
                db('s_customer_interface_detail')->insert($dData);
                action_log($param,[],$res,$data['staff_id'],$staffInfo['staffname']);
                db()->commit();
                $returnData = array('code' => 200,'msg' =>'客资录入成功','data'=>$data,'cid'=>$res);
                return json($returnData);
            }catch (Exception $e){
                $dData['result_code'] = 400;
                $dData['error_reason'] = '插入详情表出错';
                db('s_customer_interface_detail')->insert($dData);

                $returnData = array('code' => 200,'msg' =>'客资录入成功,插入详情表失败','data'=>$e->getMessage());
                return json($returnData);
            }
        }
    }
    // 获取订单所有服务信息
    public function getAllServiceInfo(){
        $data = input();
        $order_sn = $data['order_sn'];
        // $order_sn = 'SY18020600018';
        // 是否安装erp
//        $is_erp = is_install('sx_erp');
//        if ($is_erp) {
        // 店面类型crm （1：婚纱；2：儿童；3：旅拍；4：艺术；5：其他）
            //erp  shop_type 0：婚纱；1:儿童
            $erp = config('ext.app_config')['sx_erp'];
            $tel = 1;
            $shop_type = session('shop_type');
            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;
            }
            $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'];
                // var_dump($baseInfo);
                $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);
            }
//        }
        // exit;
        $this->assign('order_sn', $order_sn);
        return $this->fetch();
    }
    //进店码
    public function jindianma(){
        $param = input('param.');
        $this->assign('param',$param);
        return $this->fetch();
    }
    public function jdEwmShow(){
        $code = input('param.code');
        $this->assign('code',$code);
        return $this->fetch();
    }
    //进店码生成二维码
    public function jdEwm(){
        $code = input('param.code');
        $qrcode = new \Endroid\QrCode\QrCode();
        $qrcode->setText($code);
        echo $qrcode->writeString();
        exit();
    }
    //进店码提交
    public function jdSub(){
        $data = input();
        $time = date('Y-m-d H:i:s');
        $arr = [
            'is_intostore'=> 2,
            'syjd_day' => $time,
        ];
        $upd = [
            'shop_code'=>$data['shop_code'],
            'shop_name'=>$data['shop_name'],
            'is_jd'=>1,
            'jd_time'=> $time,
        ];
        $info = db('c_customer_jdm')->where('jd_code',$data['jd_code'])->find();
        
        if(empty($info)){
            return array('code'=>101,'msg'=>'未找到此进店码','data'=>'');
        }
        // if($info['shop_code'] != $data['shop_code']){
        //     return array('code'=>102,'msg'=>'此进店码有误，非本店进店码，请联系网络客服重新发送进店码','data'=>'');
        // }
        if($info['is_jd'] == 1){
            return array('code'=>102,'msg'=>'此进店码已使用。','data'=>'');
        }
        $number = db('c_customerinfo')->where('id',$info['c_id'])->value('customer_number');
        //店面信息
        $shop = controller('crm/Customer','lib')->get_shop(['shop_code'=>$data['shop_code']]);
        try{
            db()->startTrans();
            db('c_customer_jdm')->where('jd_code',$data['jd_code'])->update($upd);
            db('c_customerinfo')->where('id',$info['c_id'])->update($arr);
            $isTable = isTableExist('c_customer_intostore');
            // 如果进店表存在
            if ($isTable) {
                $iData = [
                    'syjd_day' => $time,
                    // 'status' => '',
                    'is_intostore' => 2,
                ];
                $into = db('c_customer_intostore')->where('cid', $info['c_id'])->where('status',1)->where('yjd_day','>=',date('Y-m-d'))->find();
                if($into){
                    db('c_customer_intostore')->where('id',$into['id'])->update($iData);
                }else{
                    db()->rollback();
                    return array('code'=>102,'msg'=>'进店码已过期，请联系网络客服重新发送进店码','data'=>db()->getLastSql());
                }
            }else{
                //通知erp进店   c_erp_save erp接口调用失败，缓存表
                $erp = config('ext.app_config');
                if($shop[0]['shop_type'] == 2){
                    $addr = $erp['sx_erp']['addr_child'];
                    // 婚纱0，儿童1
                    $url = $addr.'SX_ChildCrmApi/Set_Guest_intostore?Token=^******^&CustomerType=1&From_index='.$number;
                }else{
                    $addr = $erp['sx_erp']['addr'];
                    // 婚纱0，儿童1
                    $url = $addr.'SX_CrmApi/Set_Guest_intostore?Token=^******^&CustomerType=0&From_index='.$number;
                }
                // 调 erp 接口
                $response = requestERP($url, []);
                // print_r($response);
                // die;
                if ($response['Code'] != 200) {
                    db()->rollback();
                    return array('code'=>100,'msg'=>$response['Msg'],'error'=>json_encode($response));
                }
            }

            db()->commit();
            action_log($data,[],$info['c_id'],'-1','customer');
            return array('code'=>200,'msg'=>'进店成功','data'=>'');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'进店失败','data'=>$e->getMessage());
        }
    }
    function send(){
        $poolList = db('c_fp_pool')
            ->where('fp_time_out', '<=', time())
            ->where('count', '<', 10)
            ->select();
        foreach ($poolList as $key => $value) {
            if($value['pool_type'] == 6){
                $msg = json_decode($value['msg'], true);
                $next_time = $msg['next_time'];
                unset($msg['next_time']);
                // 发送微信模板消息
                $wxConfirmUrl = config('url_domain_root').'/crm/weixin/receiveCustomer/cid/'.$msg['customer_id'];
                $content = [
                    'touser'       => $msg['receive_id'],
                    'template_id'  => OPENTM_ZY,
                    'url'          => $wxConfirmUrl,
                    'data'         => [
                        'first'=>[
                            'value'=> $msg['send_msg'],
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> '再约提醒',
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> '再约成功',
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=>$next_time,
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> '您再约的客户正在等待中，请选择合适的时间电访',
                            'color'=> '#173177'
                        ]
                    ]
                ];
                $send_data['content'] = json_encode($content);
                $res = sendMsg($send_data);
            }
        }

    }
    /*******************公众号提报*******start*********************/
    public function forms(){
        $data = input();
        $info = db('s_third')->where('id',$data['id'])->find();
        $info['columns'] = explode(',',$info['columns']);
        $this->assign('info',$info);
        return $this->fetch();
    }
    public function addForms(){
        $data = input();
        if(empty($data['f'])){
            $dData['result_code'] = 99;
            $dData['error_reason'] = '参数有误:'.$data['f'];
            db('s_third_detail')->insert($dData);
            return array('code'=>101,'msg'=>'参数有误，不能提报');
        }
        $info = db('s_third')->where('id',$data['f'])->find();
        unset($data['f']);
        $dData['data'] = json_encode($data);
        $dData['ip'] = get_client_ip();
        $dData['pid'] = $info['id'];
        $dData['create_time'] = date('Y-m-d H:i:s');
        $dData['result_code'] = 200;
        $dData['error_reason'] = '';

        if(empty($data['customer_tel'])){
            $dData['result_code'] = 300;
            $dData['error_reason'] = '联系方式未填写';
            db('s_third_detail')->insert($dData);

            $returnData = array('code' => 104,'msg' =>'客资录入失败，联系方式未填写');
            return $returnData;
        }
        if(empty($data['customer_name'])){
            $dData['result_code'] = 400;
            $dData['error_reason'] = '客户姓名未填写';
            db('s_third_detail')->insert($dData);

            $returnData = array('code' => 105,'msg' =>'客资录入失败，客户姓名未填写');
            return ($returnData);
        }
        $staffinfo = getStaffInfoById($info['dj_staff_id']);
        $data['dj_staff_id'] = $info['dj_staff_id'];
        $data['dj_staff'] = $info['dj_staff'];
        $data['dj_staff_number'] = $staffinfo['staffnumber'];
        $data['dj_department_id'] = $staffinfo['department_id'];
        $data['add_shop_code'] = $info['add_shop_code'];
        $data['add_shop_name'] = $info['add_shop_name'];
        $data['shop_code'] = $info['belong_shop_code'];
        $data['shop_name'] = $info['belong_shop_name'];
        $data['brandclass_id'] = $info['brandclass_id'];
        $data['brandclass'] = $info['brandclass'];
        $data['customer_cource_id'] = $info['customer_cource_id'];
        $data['customer_cource'] = $info['customer_cource'];
        $data['customer_type'] = 1;
        if($data['baby_name']){
            $res = controller('crm/Customer','lib')->addCustomer_child($data);
        }else{
            $res = controller('crm/Customer','lib')->addCustomer($data);
        }
        if($res['code'] == 201){
            $dData['result_code'] = 100;
            $dData['error_reason'] = '客资重复';
            db('s_third_detail')->insert($dData);

            $returnData = array('code' => 100,'msg' =>'客资重复,录入失败');
            return ($returnData);
        }
        if($res === false){
            $dData['result_code'] = 400;
            $dData['error_reason'] = '插入客资表出错';
            db('s_third_detail')->insert($dData);

            $returnData = array('code' => 101,'msg' =>'客资录入失败','data'=>$res);
            return ($returnData);
        }else{
            db()->startTrans();
            try{
                db('s_third_detail')->insert($dData);
                db()->commit();
                $returnData = array('code' => 200,'msg' =>'客资录入成功','data'=>$data);
                return ($returnData);
            }catch (Exception $e){
                $dData['result_code'] = 400;
                $dData['error_reason'] = '插入详情表出错';
                db('s_third_detail')->insert($dData);

                $returnData = array('code' => 103,'msg' =>'客资录入成功,插入详情表失败','data'=>$e->getMessage());
                return ($returnData);
            }
        }
    }
    /*******************公众号提报********end*********************/
    // 订单详情  app用
    public function orderDetail(){
        $data = input();
        $order_sn = $data['order_sn'];
        // $order_sn = 'SY18020600018';
        // 是否安装erp
        $is_erp = is_install('sx_erp');
        if ($is_erp) {
            $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 = trim($addr,'/').'/SX_ChildCrmApi/All_CustomerOrderInfo?Token=^******^&CustomerType='.$shop_type.'&Tel='.$tel.'&orderId='.$order_sn;
            }else{
                $shop_type = 0;
                $addr= $erp['addr'];
                $url = trim($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'];
                // var_dump($baseInfo);
                $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);
            }
        }
        // exit;
        $this->assign('order_sn', $order_sn);
        return $this->fetch();
    }
}
