<?php
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace app\crm\lib;
use app\common\lib\redisQueue;
use app\crm\common;
use think\Exception;
use think\Controller;
class ListenRedis {

    protected $runtime = 0;

    // 分配队列
    public function customerFp(){
        $listName = 'fpCustomerList';
        $msg = redisQueue::init()->blPop($listName);
        $runCount = 0;
        while (!empty($msg)) {
            # 循环所有队列里的值，进行处理，如果队列里没值，则退出，
            # 原来是一次处理一条，影响效率。量大时，分配不过来。
            # 
            $runCount++;
            $send= json_decode($msg[1], true);
            $this->log('send:'.json_encode($send));
            $now = date('Y-m-d');
            $time= time();
            $timeArea = db_config('fp_time_'.$send['shop_code']);
            $fpList = new RunCustomerFp();
            $this->log('--send---eid-->>>>>'.$send['eid']);
            // 没有设定分配时间
            if (!$timeArea) {
                // 批量导入
                if ($send['type'] == 2 && $send['eid']) {

                    $customers = db('crm_c_customerinfo')->where('eid', $send['eid'])->field('id,eid,fp_staff,fp_staff_id,fp_day,sales_staff_id,sales_staff,jr_day,add_shop_code,add_shop_name,shop_code,shop_name,brandclass_id')->select();

                    // $this->log('不在分配时间段内---导入的客资---sql-->>>>>'.db()->getLastSql());
                    // $this->log('不在分配时间段内---导入的客资----->>>>>'.json_encode($customers));
                    foreach ($customers as $key => $value) {
                        // 存在追踪人 记录分配日志
                        if ($value['sales_staff_id']) {
                            $fpLogData = [
                                'cid'              => $value['id'],
                                'eid'              => $value['eid'],
                                'fp_model'         => 3,
                                'fp_status'        => 1,
                                'fp_time'          => $value['fp_day'],
                                'jr_time'          => $value['jr_day'],
                                'fp_staff_id'      => $value['fp_staff_id'],
                                'fp_staff_name'    => $value['fp_staff'],
                                'fp_shop_code'     => $value['add_shop_code'],
                                'fp_shop_name'     => $value['add_shop_name'],
                                'fp_brandclass_id' => $value['brandclass_id'],
                                'jr_staff_id'      => $value['sales_staff_id'],
                                'jr_staff_name'    => $value['sales_staff'],
                                'jr_shop_code'     => $value['shop_code'],
                                'jr_shop_name'     => $value['shop_name'],
                            ];
                            // var_dump($fpLogData);
                            // exit;
                            $resLog = fpLogs($fpLogData);
                        }
                        // 不存在追踪人  进入分配队列
                        else{
                            $this->log('未设置分配时间---ID----->>>>>'.$value['id'].'----->开始分配---->>>');
                            $fpList->run($value['id'],$send['staff_id'],$send['shop_code']);
                        }
                    }
                    // foreach ($customers as $key => $value) {
                    //     $this->log('未设置分配时间---ID----->>>>>'.$value['id'].'----->开始分配---->>>');
                    //     $fpList->run($value['id'],$send['staff_id'],$send['shop_code']);
                    // }
                }
                // 普通录入
                else
                {
                    $fpList->run($send['body'],$send['staff_id'],$send['shop_code']);
                }
            }
            // 设定了分配时间
            else{
                $this->log('timeArea:'.$timeArea);
                $timeArea = explode(' - ',$timeArea);
                $start = strtotime($now.' '.$timeArea[0]);
                $end   = strtotime($now.' '.$timeArea[1]);
                $this->log('--start==>>'.$start.'----time==>>'.$time.'----end==>>'.$end);
                // 在分配时间段内
                if ($start <= $time && $time <= $end) {
                    $this->log('fp');
                    // 批量导入
                    if ($send['type'] == 2 && $send['eid']) {

                        $customers = db('crm_c_customerinfo')->where('eid', $send['eid'])->field('id,eid,fp_staff,fp_staff_id,fp_day,sales_staff_id,sales_staff,jr_day,add_shop_code,add_shop_name,shop_code,shop_name,brandclass_id')->select();
                        $this->log('在分配时间段内---导入的客资---sql-->>>>>'.db()->getLastSql());
                        foreach ($customers as $key => $value) {
                            // 存在追踪人 记录分配日志
                            if ($value['sales_staff_id']) {
                                $fpLogData = [
                                    'cid'              => $value['id'],
                                    'eid'              => $value['eid'],
                                    'fp_model'         => 3,
                                    'fp_status'        => 1,
                                    'fp_time'          => $value['fp_day'],
                                    'jr_time'          => $value['jr_day'],
                                    'fp_staff_id'      => $value['fp_staff_id'],
                                    'fp_staff_name'    => $value['fp_staff'],
                                    'fp_shop_code'     => $value['add_shop_code'],
                                    'fp_shop_name'     => $value['add_shop_name'],
                                    'fp_brandclass_id' => $value['brandclass_id'],
                                    'jr_staff_id'      => $value['sales_staff_id'],
                                    'jr_staff_name'    => $value['sales_staff'],
                                    'jr_shop_code'     => $value['shop_code'],
                                    'jr_shop_name'     => $value['shop_name'],
                                ];
                                // var_dump($fpLogData);
                                // exit;
                                $resLog = fpLogs($fpLogData);
                            }
                            // 不存在追踪人  进入分配队列
                            else{
                                $this->log('未设置分配时间---ID----->>>>>'.$value['id'].'----->开始分配---->>>');
                                $fpList->run($value['id'],$send['staff_id'],$send['shop_code']);
                            }
                        }
                        // $this->log('在分配时间段内---导入的客资----->>>>>'.json_encode($customers));
                        // foreach ($customers as $key => $value) {
                        //     $this->log('在分配时间段内---ID----->>>>>'.$value['id'].'----->开始分配---->>>');
                        //     $fpList->run($value['id'],$send['staff_id'],$send['shop_code']);
                        // }
                    }
                    // 普通录入
                    else
                    {
                        $fpList->run($send['body'],$send['staff_id'],$send['shop_code']);
                    }
                }
                // 不在分配时间段内 insert into c_fp_pool
                else{
                    $this->log('不在分配时间段内,开始插入待处理池。');
                    $poolInfo = db('crm_c_fp_pool')->where('cid',$send['body'])->find();
                    if(!$poolInfo){
                        $inPool = [
                            'cid'        => $send['body'],
                            'msg'        => json_encode($send),
                            'fp_time_out'=> $start+86400,
                            'count'      => 1,
                            'create_time'=> date('Y-m-d H:i:s'),
                        ];
                        db()->startTrans();
                        $res = db('crm_c_fp_pool')->insert($inPool);
                        if($res === false){
                            db()->rollback();
                            $this->log('插入待处理表失败'.db()->getLastSql());
                        } else{
                            $insertId = db()->getLastSql();
                            db()->commit();
                            $this->log('插入待处理表ID：'.$insertId);
                        }
                        
                    }else{
                        $this->log('待处理表已有数据，ID：'.$poolInfo['id'].'，客资编号：'.$poolInfo['cid']);
                    }
                    
                }
            }
            if($runCount > 100){
                //如果处理了100条了，还没处理完，退出，等待下一次执行。
                //此处根据性能进行调整。
                break;
            }
            $msg = redisQueue::init()->blPop($listName);
        }
    }
    // 数据统计队列
    public function historyData(){
        $send = array();
        $listName = 'historyDataList';
        $msg = redisQueue::init()->blPop($listName);
        if ($msg) {
            $send= json_decode($msg[1], true);
            $dataList = new RunHistoryData();
            $res = $dataList->allotData($send);
        }
    }
    // 批量导入队列
    public function excelImport(){
        $send = array();
        $listName = 'excelImportRedisList';
        $msg = redisQueue::init()->blPop($listName);
        if ($msg) {
            $send= json_decode($msg[1], true);
            $importList = new RunExcelImport();
            $res = $importList->cus_import($send['body']);
        }
    }
    //每天凌晨12点清除过期联系方式
    public function clearContact(){
        //获取所有事业部信息(客资有效时间)
        $info = sx_call('5a3bbb5d0988d',[]);
        if($info['code'] == 200){
            $valid_dates = $info['data'];
            $arr = array_column($valid_dates,'valid_date','brandclass');
            $this->log('<----事业部客资过期时间---->'.json_encode($arr));
            foreach($arr as $k=>$v){
                $lastDate = date('Y-m-d H:i:s',time() - ($v * 86400));
                $ids = db('crm_c_customerinfo')->where('dj_day','<',$lastDate)->where('brandclass',$k)->column('id');
                $this->log('<----查询 '.$k.' 事业部过期的客资id-SQL--->'.db()->getLastSql());
                // $this->log('<----'.$k.'事业部过期的客资id---->'.json_encode($ids));
                if(!empty($ids)){
                    $res = db('c_customer_contact')->where('c_id','in',$ids)->where('brandclass',$k)->delete();
                    $this->log('<----删除 '.$k.' 事业部过期客资的排重信息结果---->'.$res);
                }
            }
        }
    }
    // 自动分配定时任务
    public function cronCustomerFp(){
        @set_time_limit("0");
        ini_set('memory_limit', '2048M');
        $update = new \app\index\lib\Update();
        $res = $update->runUpdate();
        if($res['code'] === 200){
            $this->log('数据库升级完成，服务重启。');
            die;
        }else if($res['code'] === 100){
            textlog($res['msg'],SX_LOG_LEVEL_ERROR);
        }
        // $this->log('开始进入分配----->');
        // $auto_month= cache('auto_month');
        // $auto_week = cache('auto_week');
        $auto_day  = cache('auto_day');
        $auto_hour = cache('auto_hour');
        $auto_min  = cache('auto_min');
        // 一月操作一次
        if (!$auto_month || $auto_month < date('Ym')) {
            cache('auto_month', date('Ym'));
        }
        // 一周操作一次 date('w') 周几 （0-6）  默认周日执行一次
        if ($auto_week===0) {
            cache('auto_week', date('w'));
        }
        //一天操作一次
        if (!$auto_day || $auto_day < date('Ymd')) {
            cache('auto_day', date('Ymd'));
            // echo ini('rundfp.autoZuofeiZeroOrders').'<br />';
            if (ini('rundfp.autoZuofeiZeroOrders')==1) {
                $zuoFeiOrderDays = ini('rundfp.autoZuofeiZeroOrderDays') ? ini('rundfp.autoZuofeiZeroOrderDays') : 7;
                // echo $zuoFeiOrderDays.'<br />';
                $this->autoZuofeiZeroOrders( array('zuoFeiOrderDays'=>$zuoFeiOrderDays) );// 每天自动作废订单
            }
            if (ini('rundfp.channelCost')==1) {
                $this->channelCost();// 根据渠道花费 统计 每个渠道客资的 成本
            }
            if (ini('rundfp.sysAutosy')==1) {
                $this->sysAutosy();// 每天自动标记预约未进店为  邀约未进店 爽约
            }
            if (ini('rundfp.sysAutoLoss')==1) {
                $this->sysAutoLoss();// 自动标记昨日进店未成交客资为流失
            }
            if (ini('rundfp.unorderReturn')==1) {
                $this->unorderReturn();// 客资分配之后，一个月内无法成单，回到客资池，待分配(醉唐风提的需求)
            }
            if (ini('rundfp.runCustomerDeposition')==1) {
                $this->runCustomerDeposition();// 客资数据沉淀方法 每天一次
            }
            if (ini('rundfp.autoSysJinianri')==1) {
                // 自动检测结婚纪念日,生日，预产期，宝宝生日，插入pool表
                $this->sysMarryDay();
                $this->sysBirthday();
                $this->sysMateBirthday();
                $this->sysReadyBabyday();
                $this->sysBabyBirthday();
            }
            if (ini('rundfp.dsLdCd')==1) {
                //电商渠道漏斗数据沉淀
                $form_id = db('crm_s_report_form')->where('report_class_name','Ds_channel_ld')->value('id');
                $shop_code = db('crm_s_report_detail')->where('form_id',$form_id)->field('shop_code')->select();
                $this->log('电商渠道漏斗数据沉淀---shop_code-->'.json_encode($shop_code));
                foreach($shop_code as $k=>$v){
                    if(empty(cache('ds_channel_ld_'.$v['shop_code'])) || cache('ds_channel_ld_'.$v['shop_code']) == 2){
                        $this->log('电商渠道漏斗数据沉淀---开始-->'.$v['shop_code']);
                        //查询当前店上月是否沉淀过
                        $id = db('crm_d_ds_channel_ld')->where('shop_code',$v['shop_code'])->where('time',date('Y-m-01'))->value('id');
                        if(empty($id)){
                            $this->DsChannelLdData($v['shop_code']);
                        }
                        $this->log('电商渠道漏斗数据沉淀---结束-->'.$v['shop_code']);
                    }
                }
            }
            if (ini('rundfp.wxXzCd')==1) {
                //网销小组数据统计
                $g_id = db('crm_s_report_form')->where('report_class_name','Wx_group1')->value('id');
                $shopcode = db('crm_s_report_detail')->where('form_id',$g_id)->field('shop_code')->select();
                $this->log('网销小组数据统计数据沉淀---shop_code-->'.json_encode($shopcode));
                foreach($shopcode as $k=>$v){
                    if(empty(cache('wx_group_'.$v['shop_code'])) || cache('wx_group_'.$v['shop_code']) == 2) {
                        $this->log('网销小组数据统计数据沉淀---开始-->' . $v['shop_code']);
                        //查询当前店上月是否沉淀过
                        $id = db('crm_d_wx_group')->where('shop_code', $v['shop_code'])->where('time', date('Y-m-01'))->value('id');
                        if (empty($id)) {
                            $this->WxGroup($v['shop_code']);
                        }
                        $this->log('网销小组数据统计数据沉淀---结束-->' . $v['shop_code']);
                    }
                }
            }

            //2021-03-15 南宁qqbaby
            if (ini('rundfp.protect ')==1) {
                //自动标记过保护期的客资
                $this->autoSignProtect();
            }
            //2021-03-15 南宁qqbaby
            if (ini('rundfp.noValid ')==1) {
                //自动标记超期未标记的客资
                $this->autoSignNoValid();
            }
        }
        //一小时操作一次
        if(!$auto_hour || $auto_hour < date('YmdH')){
            cache('auto_hour',date('YmdH'));
            if (ini('rundfp.sysAutoValid')==1) {
                $this->sysAutoValid();//自动标记有效
            }
            if (ini('rundfp.sysAutoUnValid')==1) {
                $this->sysAutoUnValid();//自动标记无效
            }
            if (ini('rundfp.sysRestartAutoFP')==1) {
                $this->sysRestartAutoFP();//过期自动分配
            }
            // 清理pool表中，超过10次的客资（已删除，已分配 从pool中删除）
        }
        //一分钟操作一次
        if (!$auto_min || $auto_min < date('YmdHi')) {
            cache('auto_min', date('YmdHi'));
            // $this->cronSk();// 定时筛客
            if (ini('rundfp.dealCustomer')==1) {
                $this->dealCustomer();// 处理分配成功，待接收，超时的客资
            }
            if (ini('rundfp.dealPool')==1) {
                $this->dealPool();// 处理pool中的数据
            }
        }
        $runtime++;
        if ($runtime>=1000) {
            $runtime = 0;
            exit;
        }
    }
    //每天自动标记过保护期的客资
    public function autoSignProtect(){
        // $// $this->log('自动检测客资标记过保护期的客资---开始-->');
        // 所有事业部
        $sign = db('crm_s_tracksign')->order('shop_code')->select();
        $this->log('客资标记信息----->'.json_encode($sign));
        foreach($sign as $k=>$v){
            if($v['protect_day']){
                $guobaohuqi = [
                    'sign_id_is_protected'=> 1,
                    'update_time' => date('Y-m-d H:i:s'),
                ];

                $time = date('Y-m-d 23:59:59',strtotime("-".$v['protect_day']." days"));

                $where['is_status'] = 1;//未删除
                $where['c_from'] = 1;//crm 客资
                $where['shop_code'] = $v['shop_code'];//crm 归属店
                $where['sign_name'] = $v['tracksign'];//客资标记
                $where['sign_id_is_protected'] = 2;//未标记超期的客资
                do {
                    $now = date('Y-m-d H:i:s');
                    $info = db('crm_c_customerinfo')
                        ->where($where)->where('sign_time','<',$time)
                        ->field('id,customer_name,customer_tel,sign_time,sign_id,sign_name,sales_staff,shop_name,shop_code')
                        ->limit('100')->select();
                    $findSql = db()->getLastSql();
                    $this->log('查询SQL==》'.$findSql);
                    if (!$info) {
                        break;
                    }
                    $ids = '';
                    $trackLog = [];
                    foreach ($info as $key => $val) {
                        // insertAll 用的数据
                        $trackLog[$key]['gtType'] = '4';
                        $trackLog[$key]['customer_id'] = $val['id'];
                        $trackLog[$key]['customer_name'] = $val['customer_name'];
                        $trackLog[$key]['customer_tel'] = $val['customer_tel'];
                        $trackLog[$key]['sales_day'] = $now;
                        $trackLog[$key]['sales_staff'] = '系统操作';
                        $trackLog[$key]['sales_staff_id'] = '0';
                        $trackLog[$key]['shop_name'] = $val['shop_name'];
                        $trackLog[$key]['shop_code'] = $val['shop_code'];
                        $trackLog[$key]['sales_remark'] = '标记过保护期。（客资标记('.$val['sign_id'].')：'.$val['sign_name'].'；标记时间：'.$val['sign_time'].'）';
                        // 更新客资表用的id
                        $ids .= $val['id'].',';
                    }
                    // $this->log('追踪记录日志==>'.json_encode($trackLog));
                    db()->startTrans();
                    try {
                        // 更新客资表
                        db('crm_c_customerinfo')->where('id','in',$ids)->update($guobaohuqi);
                        $upInfoSql = db()->getLastSql();
                        // echo $upInfoSql;
                        $this->log('更新客资SQL==》'.$upInfoSql);
                        // 写入追踪记录
                        db('crm_c_salestrackinginfo')->insertAll($trackLog);
                        $insSalSql = db()->getLastSql();
                        // $this->log('写入追踪记录SQL==》'.$insSalSql);
                        db()->commit();
                    } catch (\Exception $e) {
                        db()->rollback();
                        $this->log("系统操作超期未标记失败：".$e->getMessage());
                    }
                    $count = db('c_customerinfo')
                        ->where($where)->where('sign_time','<',$time)
                        ->count();
                } while ( $count>1);
            }
        }
    }
    //每天自动标记分配后未标记客资状态的客资
    public function autoSignNoValid(){
        $this->log('自动检测客资状态分配后未标记的客资---开始-->');
        // 所有事业部
        $bids = db('crm_c_customerinfo')->group('brandclass_id')->column('brandclass_id');
        $this->log('事业部ID==>'.json_encode($bids));
        foreach($bids as $k=>$v){
            $day = db_config('valid_day_to_fp_'.$v)+1;
            if($day){
                $chaoqi = [
                    'valid_status_is_chaoqi'=> 1,
                    'update_time' => date('Y-m-d H:i:s'),
                ];

                $time = date('Y-m-d 23:59:59',strtotime("-".$day." days"));
                // $time = date('Ymd',strtotime("-".$v." days"));
                $where['is_status'] = 1;//未删除
                $where['c_from'] = 1;//crm 客资
                $where['is_valid'] = 2;// 客资状态：待定
                $where['is_fp'] = 1;// 已分配
                do {
                    $now = date('Y-m-d H:i:s');
                    $info = db('crm_c_customerinfo')
                        ->where($where)->where('jr_day','<',$time)->where('valid_status_is_chaoqi',2)->where('brandclass_id',$v)
                        ->field('id,customer_name,customer_tel,jr_day,yx_day,sales_staff,is_valid,shop_name,shop_code')
                        ->limit('100')->select();
                    $findSql = db()->getLastSql();
                    $this->log('查询SQL==》'.$findSql);
                    if (!$info) {
                        break;
                    }
                    $ids = '';
                    $trackLog = [];
                    foreach ($info as $key => $val) {
                        // insertAll 用的数据
                        $trackLog[$key]['gtType'] = '4';
                        $trackLog[$key]['customer_id'] = $val['id'];
                        $trackLog[$key]['customer_name'] = $val['customer_name'];
                        $trackLog[$key]['customer_tel'] = $val['customer_tel'];
                        $trackLog[$key]['sales_day'] = $now;
                        $trackLog[$key]['sales_staff'] = '系统操作';
                        $trackLog[$key]['sales_staff_id'] = '0';
                        $trackLog[$key]['shop_name'] = $val['shop_name'];
                        $trackLog[$key]['shop_code'] = $val['shop_code'];
                        $trackLog[$key]['sales_remark'] = '超期未标记。（接收客资时间：'.$val['jr_day'].'）';
                        // 更新客资表用的id
                        $ids .= $val['id'].',';
                    }
                    // $this->log('追踪记录日志==>'.json_encode($trackLog));
                    db()->startTrans();
                    try {
                        // 更新客资表
                        db('crm_c_customerinfo')->where('id','in',$ids)->update($chaoqi);
                        $upInfoSql = db()->getLastSql();
                        $this->log('更新客资SQL==》'.$upInfoSql);
                        // 写入追踪记录
                        db('crm_c_salestrackinginfo')->insertAll($trackLog);
                        $insSalSql = db()->getLastSql();
                        // $this->log('写入追踪记录SQL==》'.$insSalSql);
                        db()->commit();
                    } catch (\Exception $e) {
                        db()->rollback();
                        $this->log("系统操作超期未标记失败：".$e->getMessage());
                    }
                    $count = db('crm_c_customerinfo')
                        ->where($where)->where('jr_day','<',$time)
                        ->where('valid_status_is_chaoqi',2)->where('brandclass_id',$v)
                        ->count();
                } while ( $count>1);
            }
        }
    }
    //检测结婚纪念日
    public function sysMarryDay(){
        $this->log('检测结婚纪念日---开始-->');
        $info = db('crm_c_customerinfo')->where('is_status',1)->where('c_from',1)->where('marry_day','like',date('Y-m-d',strtotime('+1 days')).'%')->field('id,customer_name,customer_tel,marry_day,dj_staff_id,dj_staff,sales_staff_id,sales_staff,brandclass_id')->select();
        $this->log('检测结婚纪念日---检测结果sql-->'.db()->getLastSql());
        $this->log('检测结婚纪念日---检测结果-->'.json_encode($info));
        $remind = getAllRemind();
        foreach($info as $k=>$v){
            if(in_array('tan',$remind[$v['brandclass_id']]['marry']['send_method']) && in_array('dj',$remind[$v['brandclass_id']]['marry']['send_receive'])){
                //登记人弹窗
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '结婚纪念日',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta的结婚纪念日！',
                    'receive_id'  => $v['dj_staff_id'],
                    'receive_name'=> $v['dj_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tan',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['marry_day']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if($v['sales_staff_id'] && in_array('tan',$remind[$v['brandclass_id']]['marry']['send_method']) && in_array('sales',$remind[$v['brandclass_id']]['marry']['send_receive'])){
                //追踪人弹窗
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '结婚纪念日',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta的结婚纪念日！',
                    'receive_id'  => $v['sales_staff_id'],
                    'receive_name'=> $v['sales_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tan',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['marry_day']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if(in_array('tui',$remind[$v['brandclass_id']]['marry']['send_method']) && in_array('dj',$remind[$v['brandclass_id']]['marry']['send_receive'])){
                //登记人推送
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '结婚纪念日',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta的结婚纪念日！',
                    'receive_id'  => $v['dj_staff_id'],
                    'receive_name'=> $v['dj_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tui',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['marry_day']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if($v['sales_staff_id'] && in_array('tui',$remind[$v['brandclass_id']]['marry']['send_method']) && in_array('sales',$remind[$v['brandclass_id']]['marry']['send_receive'])){
                //追踪人推送
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '结婚纪念日',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta的结婚纪念日！',
                    'receive_id'  => $v['sales_staff_id'],
                    'receive_name'=> $v['sales_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tui',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['marry_day']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
        }
        unset($info,$remind);
    }
    //检测客户生日
    public function sysBirthday(){
        $this->log('检测客户生日---开始-->');
        $info = db('crm_c_customerinfo')->where('is_status',1)->where('c_from',1)->where('customer_birthday','like',date('Y-m-d',strtotime('+1 days')).'%')->field('id,customer_name,customer_tel,customer_birthday,dj_staff_id,dj_staff,sales_staff_id,sales_staff,brandclass_id')->select();
        $this->log('检测客户生日---检测结果-->'.db()->getLastSql());
        $this->log('检测客户生日---检测结果-->'.json_encode($info));
        $remind = getAllRemind();
        foreach($info as $k=>$v){
            if(in_array('tan',$remind[$v['brandclass_id']]['c_birthday']['send_method']) && in_array('dj',$remind[$v['brandclass_id']]['c_birthday']['send_receive'])){
                //登记人弹窗
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '客户生日',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta的生日！',
                    'receive_id'  => $v['dj_staff_id'],
                    'receive_name'=> $v['dj_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tan',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['customer_birthday']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if($v['sales_staff_id'] && in_array('tan',$remind[$v['brandclass_id']]['c_birthday']['send_method']) && in_array('sales',$remind[$v['brandclass_id']]['c_birthday']['send_receive'])){
                //追踪人弹窗
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '客户生日',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta的生日！',
                    'receive_id'  => $v['sales_staff_id'],
                    'receive_name'=> $v['sales_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tan',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['customer_birthday']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if(in_array('tui',$remind[$v['brandclass_id']]['c_birthday']['send_method']) && in_array('dj',$remind[$v['brandclass_id']]['c_birthday']['send_receive'])){
                //登记人推送
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '客户生日',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta的生日！',
                    'receive_id'  => $v['dj_staff_id'],
                    'receive_name'=> $v['dj_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tui',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['customer_birthday']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if($v['sales_staff_id'] && in_array('tui',$remind[$v['brandclass_id']]['c_birthday']['send_method']) && in_array('sales',$remind[$v['brandclass_id']]['c_birthday']['send_receive'])){
                //追踪人推送
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '客户生日',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta的生日！',
                    'receive_id'  => $v['sales_staff_id'],
                    'receive_name'=> $v['sales_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tui',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['customer_birthday']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
        }
        unset($info,$remind);
    }
    //检测配偶生日
    public function sysMateBirthday(){
        $this->log('检测配偶生日---开始-->');
        $info = db('crm_c_customerinfo')->where('is_status',1)->where('c_from',1)->where('mate_birthday','like',date('Y-m-d',strtotime('+1 days')).'%')->field('id,customer_name,customer_tel,mate_birthday,dj_staff_id,dj_staff,sales_staff_id,sales_staff,brandclass_id')->select();
        $this->log('检测配偶生日---检测结果-->'.db()->getLastSql());
        $this->log('检测配偶生日---检测结果-->'.json_encode($info));
        $remind = getAllRemind();
        foreach($info as $k=>$v){
            if(in_array('tan',$remind[$v['brandclass_id']]['m_birthday']['send_method']) && in_array('dj',$remind[$v['brandclass_id']]['m_birthday']['send_receive'])){
                //登记人弹窗
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '配偶生日',
                    'send_msg'    => '当前名为：'.$v['mate_name'].'的客资，今天是Ta的生日！',
                    'receive_id'  => $v['dj_staff_id'],
                    'receive_name'=> $v['dj_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tan',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['mate_birthday']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if($v['sales_staff_id'] && in_array('tan',$remind[$v['brandclass_id']]['m_birthday']['send_method']) && in_array('sales',$remind[$v['brandclass_id']]['m_birthday']['send_receive'])){
                //追踪人弹窗
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '配偶生日',
                    'send_msg'    => '当前名为：'.$v['mate_name'].'的客资，今天是Ta的生日！',
                    'receive_id'  => $v['sales_staff_id'],
                    'receive_name'=> $v['sales_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tan',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['mate_birthday']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if(in_array('tui',$remind[$v['brandclass_id']]['m_birthday']['send_method']) && in_array('dj',$remind[$v['brandclass_id']]['m_birthday']['send_receive'])){
                //登记人推送
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '配偶生日',
                    'send_msg'    => '当前名为：'.$v['mate_name'].'的客资，今天是Ta的生日！',
                    'receive_id'  => $v['dj_staff_id'],
                    'receive_name'=> $v['dj_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tui',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['mate_birthday']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if($v['sales_staff_id'] && in_array('tui',$remind[$v['brandclass_id']]['m_birthday']['send_method']) && in_array('sales',$remind[$v['brandclass_id']]['m_birthday']['send_receive'])){
                //追踪人推送
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '配偶生日',
                    'send_msg'    => '当前名为：'.$v['mate_name'].'的客资，今天是Ta的生日！',
                    'receive_id'  => $v['sales_staff_id'],
                    'receive_name'=> $v['sales_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tui',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['mate_birthday']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
        }
        unset($info,$remind);
    }
    //检测预产期
    public function sysReadyBabyday(){
        $this->log('检测预产期---开始-->');
        $info = db('crm_c_customerinfo')->where('is_status',1)->where('c_from',1)->where('ready_baby_day','like',date('Y-m-d',strtotime('+1 days')).'%')->field('id,customer_name,customer_tel,ready_baby_day,dj_staff_id,dj_staff,sales_staff_id,sales_staff,brandclass_id')->select();
        $this->log('检测预产期---检测结果-->'.db()->getLastSql());
        $this->log('检测预产期---检测结果-->'.json_encode($info));
        $remind = getAllRemind();
        foreach($info as $k=>$v){
            if(in_array('tan',$remind[$v['brandclass_id']]['ready']['send_method']) && in_array('dj',$remind[$v['brandclass_id']]['ready']['send_receive'])){
                //登记人弹窗
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '预产期',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta宝宝的预产期！',
                    'receive_id'  => $v['dj_staff_id'],
                    'receive_name'=> $v['dj_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tan',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['ready_baby_day']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if($v['sales_staff_id'] && in_array('tan',$remind[$v['brandclass_id']]['ready']['send_method']) && in_array('sales',$remind[$v['brandclass_id']]['ready']['send_receive'])){
                //追踪人弹窗
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '预产期',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta宝宝的预产期！',
                    'receive_id'  => $v['sales_staff_id'],
                    'receive_name'=> $v['sales_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tan',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['ready_baby_day']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if(in_array('tui',$remind[$v['brandclass_id']]['ready']['send_method']) && in_array('dj',$remind[$v['brandclass_id']]['ready']['send_receive'])){
                //登记人推送
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '预产期',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta宝宝的预产期！',
                    'receive_id'  => $v['dj_staff_id'],
                    'receive_name'=> $v['dj_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tui',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['ready_baby_day']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if($v['sales_staff_id'] && in_array('tui',$remind[$v['brandclass_id']]['ready']['send_method']) && in_array('sales',$remind[$v['brandclass_id']]['ready']['send_receive'])){
                //追踪人推送
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '预产期',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta宝宝的预产期！',
                    'receive_id'  => $v['sales_staff_id'],
                    'receive_name'=> $v['sales_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tui',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['ready_baby_day']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
        }
        unset($info,$remind);
    }
    //检测宝宝生日
    public function sysBabyBirthday(){
        $this->log('检测宝宝生日---开始-->');
        $info = db('crm_c_customerinfo')->where('is_status',1)->where('c_from',1)->where('baby_birthday','like',date('Y-m-d',strtotime('+1 days')).'%')->field('id,customer_name,customer_tel,baby_birthday,dj_staff_id,dj_staff,sales_staff_id,sales_staff,brandclass_id')->select();
        $this->log('检测宝宝生日---检测结果-->'.db()->getLastSql());
        $this->log('检测宝宝生日---检测结果-->'.json_encode($info));
        $remind = getAllRemind();
        foreach($info as $k=>$v){
            if(in_array('tan',$remind[$v['brandclass_id']]['bb_birthday']['send_method']) && in_array('dj',$remind[$v['brandclass_id']]['bb_birthday']['send_receive'])){
                //登记人弹窗
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '宝宝生日',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta宝宝的生日！',
                    'receive_id'  => $v['dj_staff_id'],
                    'receive_name'=> $v['dj_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tan'
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['baby_birthday']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if($v['sales_staff_id'] && in_array('tan',$remind[$v['brandclass_id']]['bb_birthday']['send_method']) && in_array('sales',$remind[$v['brandclass_id']]['bb_birthday']['send_receive'])){
                //追踪人弹窗
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '宝宝生日',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta宝宝的生日！',
                    'receive_id'  => $v['sales_staff_id'],
                    'receive_name'=> $v['sales_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tan'
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['baby_birthday']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if(in_array('tui',$remind[$v['brandclass_id']]['bb_birthday']['send_method']) && in_array('dj',$remind[$v['brandclass_id']]['bb_birthday']['send_receive'])){
                //登记人推送
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '宝宝生日',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta宝宝的生日！',
                    'receive_id'  => $v['dj_staff_id'],
                    'receive_name'=> $v['dj_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tui'
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['baby_birthday']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
            if($v['sales_staff_id'] && in_array('tui',$remind[$v['brandclass_id']]['bb_birthday']['send_method']) && in_array('sales',$remind[$v['brandclass_id']]['bb_birthday']['send_receive'])){
                //追踪人推送
                $message = array(
                    'customer_id' => $v['id'],
                    'send_type'   => 1,
                    'send_title'   => '宝宝生日',
                    'send_msg'    => '当前名为：'.$v['customer_name'].'的客资，今天是Ta宝宝的生日！',
                    'receive_id'  => $v['sales_staff_id'],
                    'receive_name'=> $v['sales_staff'],
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'send_method'=>'tui',
                    'customer_name'=>$v['customer_name'],
                    'customer_tel'=>$v['customer_tel'],
                );
                $arr = array(
                    'cid' => $v['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime(date('Y-m-d 09:30:00',strtotime($v['baby_birthday']))),
                    'count'=>0,
                    'pool_type' => 4,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db('crm_c_fp_pool')->insert($arr);
            }
        }
        unset($info,$remind);
    }
    // 成本计算 lr_channel_cost_LSDS01（花费录入时间），花费修改时间（edit_channel_cost_LSDS01），花费核算日期 （accounting_channel_cost_LSDS01）
    public function channelCost(){
        // 当前日期 （几号）
        $day   = date('d');
        $today = date('Y-m-d');
        // 查最近两个月的客资的 add_shop_code （accounting_channel_cost_LSDS01）
        $shop_codes = db('crm_c_customerinfo')->whereTime('dj_day','-60 days')->group('add_shop_code')->field('add_shop_code')->select();
        $this->log(' -- 渠道花费店'.json_encode($shop_codes));
        foreach ($shop_codes as $key => $value) {
            if (!$value['add_shop_code']) {
                continue;
            }
            $this->log(' -- 渠道花费店'.$value['add_shop_code']);
            // 获取花费核算日期
            $accDay = db_config('accounting_channel_cost_'.$value['add_shop_code']);
            $this->log(' -- 核算日期：'.$accDay);
            
            // 如果存在
            if ($accDay) {
                // 如果核算日期 小于 当前日期  只统计当月 渠道花费 平均给渠道的每一个客资
                if ($accDay<$day) {
                    // $this->log(' -- <');
                    $start= date('Y-m-01');
                    $end  = $today;
                    // $time_area = getDateFromRange($start,$end);
                    // $channelCost = db('crm_s_channel_cost')->where('cost_date', 'between', [$start, $end])->field('channel_id,belong_shop_code,cost')->select();
                }
                // 如果核算日期 大于等于 当前日期  只统计当月 及上月 渠道花费 平均给渠道的每一个客资
                else{
                    // $this->log(' -- >=');
                    $start= date('Y-m-01', strtotime('-1 month'));
                    $end  = $today;
                    // $time_area  = getDateFromRange($start,$end);
                    // $channelCost= db('crm_s_channel_cost')->where('cost_date', 'between', [$start, $end])->column('channel_id,belong_shop_code,cost','cost_date');
                }
                $cStart = date('Y-m-d 00:00:00',strtotime($start));
                $cEnd = date('Y-m-d 23:59:59',strtotime($end));
                db('crm_c_customerinfo c')->where('c.dj_day','between',[$cStart,$cEnd])->update(array('c_channel_cost'=>0));

                $this->log(' -- 开始：'.$start.'；结束：'.$end);
                $channelCost= db('crm_s_channel_cost')->where('cost','>','0')->where('cost_date', 'between', [$start, $end])->order('channel_id')->field('channel_id,channel_name,belong_shop_code,cost,cost_date')->select();
                // $this->log(' -- SQL：'.db()->getLastSql());
                // $this->log(' -- 花费：'.json_encode($channelCost));
                // $i = 0;
                foreach ($channelCost as $key => $value) {
                    $where['customer_channel_id'] = $value['channel_id'];
                    $where['customer_channel'] = $value['channel_name'];
                    $where['shop_code'] = $value['belong_shop_code'];
                    $where['is_status'] = 1;
                    $cStart= date('Y-m-d 00:00:00', strtotime($value['cost_date']));
                    $cEnd  = date('Y-m-d 23:59:59', strtotime($value['cost_date']));
                    $cInfos= db('crm_c_customerinfo')->where($where)->where('dj_day','between',[$cStart, $cEnd])->field('id')->select();

                    // $this->log(' -- customerInfo-->SQL：'.db()->getLastSql());
                    // exit;
                    $num = count($cInfos);
                    $ave = round(($value['cost']/$num), 2);
                    // $this->log('--ave--：'.$ave);
                    $saveInfo = [];
                    $inData = [];
                    foreach ($cInfos as $k => $val) {
                        db('crm_c_customerinfo')->where('id', $val['id'])->update(array('c_channel_cost'=>$ave));
                    }
                }
            }
        }
        unset($shop_codes,$accDay,$start,$end,$channelCost,$where,$cInfos,$inData);
    }
    // 醉唐风 客资分配之后，一个月内（30天可设定）无法成单，回到客资池，待分配
    public function unorderReturn(){
        $bids = db('crm_c_customerinfo')->group('brandclass_id')->column('brandclass_id');
        foreach ($bids as $key => $value) {
            $orderReturn = db_config('unorderReturn_'.$value);
            if ($orderReturn>0) {
                $date = date('Y-m-d H:i:s');
                $where['brandclass_id'] = $value;
                $where['is_status'] = 1;
                $where['c_from'] = 1;
                $where['is_fp'] = 1;
                $where['is_success'] = 2;
                $start= date('Y-m-d 00:00:00',strtotime('-'.$orderReturn.' day'));
                $end  = date('Y-m-d 00:00:00');
                $temp = db('crm_c_customerinfo')->where($where)->where('jr_day', 'between time', [$start, $end])->column('customer_name,customer_number,jr_day,sales_staff','id');
                if (empty($temp)) {
                    continue;
                }
                $ids = '';
                $lData = [];
                $sData = [];
                $data['is_fp'] = 2;
                $data['sales_staff'] = NULL;
                $data['sales_staff_id'] = NULL;
                foreach ($temp as $key => $value) {
                    $ids .= $key.',';
                    // action_log 用数据
                    $tempL['module']     = 'crm';
                    $tempL['controller'] = 'Customer';
                    $tempL['action']     = 'customerInfo';
                    $tempL['old_data']   = json_encode($value);
                    $tempL['data']       = json_encode($data);
                    $tempL['customer_id']= $key;
                    $tempL['staff_name'] = 'sys-unorderReturn';
                    $tempL['staff_id']   = '0';
                    $tempL['ip']         = '';
                    $tempL['create_time']= $date;
                    array_push($lData,$tempL);
                    // 追踪记录
                    $tempS['customer_id'] = $key;
                    $tempS['customer_name'] = $value['customer_name'];
                    $tempS['customer_number'] = $value['customer_number'];
                    $tempS['sales_remark'] = '自客资'.$value['jr_day'].'以来，'.$orderReturn.'天内，没有订单，系统自动回收，待分配';
                    $tempS['sales_day'] = $date;
                    $tempS['sales_staff'] = '系统';
                    $tempS['sales_staff_id'] = '';
                    $tempS['sales_staff_number'] = '';
                    $tempS['shop_name'] = '';
                    $tempS['shop_code'] = '';                    
                    array_push($sData,$tempS);
                }
                $ids = trim($ids,',');
                db()->startTrans();
                try {
                    // 更新客资表
                    db('crm_c_customerinfo')->where('id', 'in', $ids)->update($data);
                    // insertAll action_log fp_log
                    db('crm_action_log','db_logs')->insertAll($lData);
                    // 新增追踪记录
                    db('crm_c_salestrackinginfo')->insertAll($sData);
                    db()->commit();
                } catch (\Exception $e) {
                    db()->rollback();
                    $this->log('errorMessage：==>'.$e->getMessage());
                    continue;
                }
            }
        }
        unset($bids,$where,$temp,$tempL,$tempS,$data,$lData,$sData);
    }
    // 每天自动标记预约未进店为  邀约未进店 爽约
    private function sysAutosy(){
        $this->log('开始标记爽约------');
        $data = [
            'is_intostore' => 4,
        ];
        $info = db('crm_c_customerinfo')
            ->where('syjd_day', 'null')
            ->where('yjd_day', 'not null')
            ->where('yjd_day', '<' ,date('Y-m-d 00:00:00'))
            ->where('is_success', 2)
            ->where('is_intostore', '1')
            ->field('id,yjd_day,is_intostore')
            ->select();
        $res = db('crm_c_customerinfo')
            ->where('syjd_day', 'null')
            ->where('yjd_day', 'not null')
            ->where('yjd_day', '<' ,date('Y-m-d 00:00:00'))
            ->where('is_success', 2)
            ->where('is_intostore', '1')
            ->update($data);
        $log = '>>>爽约客资处理数量：'.$res;
        $table = isTableExist('crm_c_customer_intostore');
        if ($table === true) {
            $Idata = [
                'is_intostore' => 4,
                'syjd_day' => NULL,
            ];
            $ires = db('crm_c_customer_intostore')
                ->where('yjd_day', 'not null')
                ->where('yjd_day', '<' ,date('Y-m-d 00:00:00'))
                // ->where('is_success', 2)
                ->where('is_intostore', '1')
                ->update($Idata);
            $log .= '>>>爽约进客处理数量：'.$ires;
        }

        $this->log('爽约标记完成'.$log);
        unset($info,$log);
    }
    /*
     *   每天凌晨沉淀数据
     */
    private function runCustomerDeposition(){
        $this->log('<----开始判断沉淀---->');
        // $day = date('Y-m-d');
        // 从缓存中取客资沉淀状态 (上次执行的日期)
        // $depoStatus = cache('customerDeposition');
        // $this->log('<----depoStatus---->'.$depoStatus);
        // $this->log('<----day---->'.$day);
        // if ( !$depoStatus || $day > $depoStatus) {
            // $this->log('<----InRun---->'.$depoStatus);
            // 开始处理之后，客资沉淀状态，(当前的日期)
            // cache('customerDeposition', $day);
            // 表不存在，创建表
            $dbName = 'crm_d_customerinfo_'.date('Ym');
            if(!$this->isTableExist($dbName)){
                $sql = "CREATE TABLE IF NOT EXISTS ".$dbName." (LIKE d_customerinfo)";
                db()->master()->query($sql);
            }
            
            $area = 'this_month';
            $time_area = getdateArea($area);
            $allTime = getDateFromRange($time_area[0], $time_area[1]);
            // 循环当月每天
            foreach ($allTime as $key => $value) {
                $param['day'] = $value;
                $this->customerDeposition($param);
            }
        // }
    }
    /*
     *    客资沉淀  具体方法
     */
    private function customerDeposition($param){
        $day = $param['day'];
        // $depoStatus = cache('customerDeposition');
        // $this->log('<----InDeposition---->'.$depoStatus);
        $dbName= 'd_customerinfo_'.date('Ym');
        $res = db($dbName)->where('s_date', $day)->delete();
        if ($res === false) {
            // $this->log('<----InDepositionFalse---->'.$depoStatus);
            return false;
        }else{
            $start = date('Y-m-d 00:00:00', strtotime($day));
            $end   = date('Y-m-d 23:59:59', strtotime($day));
            $customerList = db('crm_c_customerinfo')->where('c_from', 1)->where('update_time', 'between time', [$start, $end])->select();
            // var_dump($customerList);
            $count = count($customerList);
            foreach ($customerList as $key => $value) {
                $inData = $value;
                unset($inData['id']);
                $inData['cid']    = $value['id'];
                $inData['s_date'] = date('Ymd', strtotime($day));
                db($dbName)->insert($inData);
            }
            unset($customerList);
            // while ($count>0) {
            //     foreach ($customerList as $key => $value) {
            //         $customerList[$key]['s_date'] = date('Ymd', strtotime($day));
            //         $customerList[$key]['cid']    = $value['id'];
            //         unset($customerList[$key]['id']);
            //         if ($key>100) {
            //             break;
            //         }
            //     }
            //     try {
            //         $res = db($dbName)->insertAll($customerList);
            //     } catch (\Exception $e) {
            //         $this->log('<----insertAll错误信息---->'.$e->getMessage());
            //     }
            //     $count = $count-100;
            // }
        }
    }
    /*
     * 判断表是否存在 
     */
    private function isTableExist($table){
        $sql = "show tables;";
        $res = db()->master()->query($sql);
        foreach($res as $value){
            if(array_search($table, $value)){
                return true;
            }
        }
        return false;
    }
    /*
     *    开启筛客后，如果筛客人不在线，那么在pool表中定时查找在线的筛客人，随机分配给在线的筛客人
     */
    private function cronSk(){
        $time = time();
        $skList = db('crm_c_fp_pool')->where('pool_type', 7)->where('fp_time_out', '<', $time)->select();
        if (!$skList) {
            $this->log('没有需要分配筛客的客资');
            return false;
        }
        $this->log('开始分配筛客的客资');
        foreach ($skList as $key => $value) {
            $cid = $value['cid'];
            $sklistTemp = json_decode($value['msg'],true);
            // 只分配给在线的筛客
            $sklist = controller("crm/Customer","lib")->getMemberOnline($sklistTemp);
            $this->log('skList：'.json_encode($sklist));
            // 如果有在线的筛客人
            if (!empty($skList)) {
                $rand = rand(0,count($sklist)-1);
                $arr = $sklist[$rand];
                $cData['sk_staff_id']= $arr['id'];
                $cData['sk_staff']   = $arr['staffname'];
                $cInfoSk = db('crm_c_customerinfo')->where('id',$cid)->value('sk_staff_id');
                // 如果已经存在筛客人
                if ($cInfoSk['sk_staff_id']) {
                    $this->log('已有筛客人');
                    db('crm_c_fp_pool')->where('id',$value['id'])->delete();
                    continue;
                }
                $res = db('crm_c_customerinfo')->where('id',$cid)->update($cData);
                $this->log('SQL：'.db()->getLastSql());
                if ($res===false) {
                    // 更新pool表
                    db('crm_c_fp_pool')->where('id',$value['id'])->update(array('fp_time_out',time()+300));
                    $this->log('分配筛客人失败');
                    continue;
                }else{
                    $this->log('分配筛客人成功');
                    db('crm_c_fp_pool')->where('id',$value['id'])->delete();
                    // $this->log('SQLD：'.db()->getLastSql());
                }
            }else{
                // 更新pool表
                db('crm_c_fp_pool')->where('id',$value['id'])->update(array('fp_time_out',time()+300));
                // $this->log('SQLD：'.db()->getLastSql());
            }
        }
        unset($skList);
    }
    /*
     * 几小时未处理自动标记有效
     * */
    private function sysAutoValid(){
        //所有事业部
        $bids = db('crm_c_customerinfo')->group('brandclass_id')->column('brandclass_id');
        foreach($bids as $k=>$v){
            //获取设定时间
            $hour = db_config('auto_valid_'.$v);
            if($hour){
                $time = date('Y-m-d H:i:s',strtotime("-$hour hour"));
                $valid = [
                    'is_valid' => 1,
                    'yx_day' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s'),
                ];
                $where['is_fp']    = 1;
                $where['c_from']   = 1;
                $where['is_valid'] = 2;
                $where['is_status']= 1;
                $where['brandclass_id'] = $v;
                do {
                    $now = date('Y-m-d H:i:s');
                    $cusInfo = db('crm_c_customerinfo')
                        ->where($where)->where('sales_staff_id','>',0)->where('jr_day','<',$time)
                        ->field('id,c_unique,customer_number,customer_name,customer_tel,jr_day,sales_staff,is_valid,yx_day,shop_name,shop_code')
                        ->limit('100')
                        ->select();
                    $this->log("自动标记有效查询SQL :-->".db()->getLastSql());
                    if (!$cusInfo) {
                        break;
                    }
                    $ids = '';
                    $trackLog = [];
                    foreach ($cusInfo as $key => $val) {
                        // insertAll 用的数据
                        $trackLog[$key]['gtType'] = '4';
                        $trackLog[$key]['c_unique'] = $val['c_unique'];
                        $trackLog[$key]['customer_id'] = $val['id'];
                        $trackLog[$key]['customer_name'] = $val['customer_name'];
                        $trackLog[$key]['customer_tel'] = $val['customer_tel'];
                        $trackLog[$key]['customer_number'] = $val['customer_number'];
                        $trackLog[$key]['sales_day'] = $now;
                        $trackLog[$key]['sales_staff'] = '系统操作';
                        $trackLog[$key]['sales_staff_id'] = '0';
                        $trackLog[$key]['shop_name'] = $val['shop_name'];
                        $trackLog[$key]['shop_code'] = $val['shop_code'];
                        $trackLog[$key]['sales_remark'] = '系统自动将该客资标记有效。（接收时间：'.$val['jr_day'].'；系统设定：'.$hour.'小时）';
                        // 更新客资表用的id
                        $ids .= $val['id'].',';
                    }

                    $ids = trim($ids,',');
                    $this->log("客资IDS :-->".$ids);
                    db()->startTrans();
                    try {
                        db('crm_c_customerinfo')->where('id','in',$ids)->update($valid);
                        db('crm_c_salestrackinginfo')->insertAll($trackLog);
                        db()->commit();
                    } catch (\Exception $e) {
                        db()->rollback();
                        $this->log("系统自动标记有效失败：".$e->getMessage());
                    }
                    $count = db('crm_c_customerinfo')
                        ->where($where)->where('sales_staff_id','>',0)->where('jr_day','<',$time)->count();
                    $this->log("剩余数量 :-->".$count);
                } while ( $count>=1);
            }
        }
        unset($bids,$hour,$time,$valid,$where,$now,$cusInfo,$ids,$trackLog,$count);
    }
    /*
     * 几小时未处理自动标记无效
     * */
    private function sysAutoUnValid(){
        //所有事业部
        $bids = db('crm_c_customerinfo')->group('brandclass_id')->column('brandclass_id');
        $this->log("所有事业部id :-->".json_encode($bids));
        foreach($bids as $k=>$v){
            //获取设定时间
            $hour = db_config('auto_unvalid_'.$v);
            $this->log("事业部id的自动标记无效设定时间 :-->".$hour);
            if($hour){
                $time = date('Y-m-d H:i:s',strtotime("-$hour hour"));
                $unvalid = [
                    'is_valid' => 3,
                    'yx_day' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s'),
                ];
                $where['is_fp']    = 1;
                $where['c_from']   = 1;
                $where['is_valid'] = 4;
                $where['is_status']= 1;
                $where['brandclass_id'] = $v;
                do {
                    $now = date('Y-m-d H:i:s');
                    $cusInfo = db('crm_c_customerinfo')
                        ->where($where)->where('sales_staff_id','>',0)->where('yx_day','<',$time)
                        ->field('id,c_unique,customer_number,customer_name,customer_tel,jr_day,yx_day,sales_staff,is_valid,yx_day,shop_name,shop_code')
                        ->limit('100')->select();
                    $this->log("自动标记无效查询SQL :-->".db()->getLastSql());
                    if (!$cusInfo) {
                        break;
                    }
                    $ids = '';
                    $trackLog = [];
                    foreach ($cusInfo as $key => $val) {
                        // insertAll 用的数据
                        $trackLog[$key]['gtType'] = '4';
                        $trackLog[$key]['c_unique'] = $val['c_unique'];
                        $trackLog[$key]['customer_id'] = $val['id'];
                        $trackLog[$key]['customer_name'] = $val['customer_name'];
                        $trackLog[$key]['customer_tel'] = $val['customer_tel'];
                        $trackLog[$key]['customer_number'] = $val['customer_number'];
                        $trackLog[$key]['sales_day'] = $now;
                        $trackLog[$key]['sales_staff'] = '系统操作';
                        $trackLog[$key]['sales_staff_id'] = '0';
                        $trackLog[$key]['shop_name'] = $val['shop_name'];
                        $trackLog[$key]['shop_code'] = $val['shop_code'];
                        $trackLog[$key]['sales_remark'] = '系统自动将该客资标记无效。（驳回时间：'.$val['yx_day'].'；系统设定：'.$hour.'小时）';
                        // 更新客资表用的id
                        $ids .= $val['id'].',';
                    }
                    $ids = trim($ids,',');

                    db()->startTrans();
                    try {
                        db('crm_c_customerinfo')->where('id','in',$ids)->update($unvalid);
                        db('crm_c_salestrackinginfo')->insertAll($trackLog);
                        db()->commit();
                    } catch (\Exception $e) {
                        db()->rollback();
                        $this->log("系统自动标记无效失败：".$e->getMessage());
                    }
                    $count = db('crm_c_customerinfo')->where($where)->where('sales_staff_id','>',0)->where('yx_day','<',$time)->count();
                } while ( $count<=1);
            }
        }
        unset($bids,$hour,$time,$unvalid,$where,$now,$cusInfo,$ids,$trackLog,$count);
    }
    /*
     * 几天未追踪自动重新分配
     * notice:已分配;接入时间小于设定时间;最后一次追踪时间小于设定时间
     * */
    private function sysRestartAutoFP(){
        //所有事业部
        $bids = db('crm_c_customerinfo')->group('brandclass_id')->column('brandclass_id');
        $this->log("所有事业部id :-->".json_encode($bids));
        foreach ($bids as $k => $v) {
            //获取设定时间
            $day = db_config('restart_fp_time_' . $v);
            $this->log("事业部id的自动重新分配设定时间 :-->".$day);
            if($day){
                $time = date('Y-m-d H:i:s', strtotime("-$day days"));
                $info = db('crm_c_customerinfo')->where('brandclass_id', $v)->where('is_fp', 1)->where('jr_day', '<', $time)->where('c_star_day',null)->select();
                $this->log("事业部 " . $v . " 过期自动分配的客资:-->" . json_encode($info));
                //把状态改为未分配
                $ids = array_column($info,'id');
                db('crm_c_customerinfo')->where('id','in',$ids)->update(['is_fp'=>2]);
                foreach($info as $kk=>$vv){
                    $listName_fp = 'fpCustomerList';
                    $message_fp['receive']  = '-1';
                    $message_fp['body']     = $vv['id'];
                    $message_fp['staff_id'] = $vv['dj_staff_id'];
                    $message_fp['shop_code']= $vv['shop_code'];
                    push_list($listName_fp, $message_fp);
                }
                unset($ids,$info);
            }
        }
        unset($bids);
    }
    //每天自动标记所有进店未成交客资为流失 
    private function sysAutoLoss(){
        $data = [
            'erp_loss' => 2,
            'is_intostore' => 5,
            'erp_loss_reason'=> '系统自动标记流失',
            'erp_loss_time' => date('Y-m-d H:i:s'),
        ];
        $res = db('crm_c_customerinfo')
            ->where('syjd_day', 'not null')
            ->where('syjd_day', '<', date('Y-m-d 00:00:00'))
            ->where('is_success', 2)
            ->where('is_intostore', 2)
            // ->where('is_intostore', 'in', [2,3])
            ->where('erp_loss', 1)
            ->update($data);
        $table = isTableExist('crm_c_customer_intostore');
        if ($table === true) {
            $Idata = [
                'is_intostore' => 5,
                'sys_loss' => 2,
                'loss_reason'=> '系统自动标记流失',
                'loss_time' => date('Y-m-d H:i:s'),
            ];
            $info = db('crm_c_customer_intostore')
                ->where('is_success',2)
                ->where('is_intostore',2)
                ->where('syjd_day','<',date('Y-m-d 00:00:00'))
                ->where('sys_loss',1)
                ->field('id,cid,syjd_day')
                ->select();
            $res1 = db('crm_c_customer_intostore')
                ->where('is_success',2)
                ->where('is_intostore',2)
                // ->where('is_intostore','in',[2,3])
                ->where('syjd_day', 'not null')
                ->where('syjd_day','<',date('Y-m-d 00:00:00'))
                ->where('sys_loss',1)
                ->update($Idata);
            $cInfo = db('crm_c_customerinfo')->where('id','in',array_column($info,'cid'))->column('syjd_day','id');
            //处理进客表进店但没有进店时间的客资
            foreach($info as $k=>$v){
                if(empty($v['syjd_day']) && $cInfo[$v['cid']]){
                    $Idata['syjd_day'] = $cInfo[$v['cid']];
                    db('crm_c_customer_intostore')->where('id',$v['id'])->update($Idata);
                }
            }
            unset($info,$cInfo);
        }
        // $this->log('<----自动标记流失次数---客资表->'.$res.' 次，进店表：'.$res1.' 次');
    }

    // 提前一天检测生日和结婚纪念日，插入表内 有问题，暂时不调用
    private function sendDayRemind(){
        $date = date('m-d',strtotime('+1 day'));
        $info = db('crm_c_customerinfo')->where('marry_day|baby_birthday','like','%'.$date.'%')->field('id,sales_staff_id,sales_staff,customer_name,customer_tel,baby_birthday,marry_day')->where('is_status',1)->where('is_loss',2)->select();
        if(!cache('send_day_remind')){
            if(!empty($info)){
                // $this->log('<----开始检查生日和结婚纪念日---->'.json_encode($info));
                $i = 1;
                $j = 1;
                foreach($info as $k=>$v){
                    $md5_k = substr(md5($v['id'].$v['sales_staff_id'].config('SX_AUTH_KEY')),8,16);
                    if(date('m-d',strtotime($v['baby_birthday'])) == $date){
                        $msg = '您好，名为：'.$v['customer_name'].',手机号为：'.$v['customer_tel'].'的客资，明天是Ta宝宝的生日，请注意追踪';
                        $message = array(
                            'send_type' => 1,
                            'send_title'=>'宝宝生日提醒',
                            'send_msg'=>$msg,
                            'receive_id'=>$v['sales_staff_id'],
                            'receive_name'=>$v['sales_staff'],
                            'time_out'=> 43200,
                            'operation_type' => 1,
                            'operation' => '[{"button":"查看详情","url":"/crm/Customer/customerList?k='.$md5_k.'&id='.$v['id'].'"}]',
                        );
                        $res = sendSystemMessage($message);//弹窗信息
                        $this->log('<----第'.$i.'次发送生日提醒结果---->'.$res);
                        $i++;
                    }
                    if(date('m-d',strtotime($v['marry_day'])) == $date){
                        $msg = '您好，名为：'.$v['customer_name'].',手机号为：'.$v['customer_tel'].'的客资，明天是Ta的结婚纪念日，请注意提醒';
                        $message = array(
                            'send_type' => 1,
                            'send_title'=>'结婚纪念日提醒',
                            'send_msg'=>$msg,
                            'receive_id'=>$v['sales_staff_id'],
                            'receive_name'=>$v['sales_staff'],
                            'time_out'=> 43200,
                            'operation_type' => 1,
                            'operation' => '[{"button":"查看详情","url":"/crm/Customer/customerList?k='.$md5_k.'&id='.$v['id'].'"}]',
                        );
                        $res1 = sendSystemMessage($message);//弹窗信息
                        $this->log('<----第'.$j.'次发送结婚纪念日提醒结果---->'.$res1);
                        $j++;
                    }
                }
                cache('send_day_remind',1);
                unset($info);
            }
        }
    }

    // 处理客资表中的 超时未接收 的客资
    private function dealCustomer(){
        $time = time();
        $fpCustomerList = db('crm_c_customerinfo')
            ->where('is_fp', FP_STATUS_DJS)
            ->where('fp_time_out', '<', $time)
            ->where('is_status', 1)
            ->where('c_from', 1)
            ->column('id, dj_staff_id, dj_day, shop_code', 'id');
        // 如果有   待分配   未接收(已超时) 的客资  先查一下pool表里有没有，有就不管了，没有写到pool表里，马上分配，计数+1
        if ($fpCustomerList) {
            foreach ($fpCustomerList as $key => $value) {
                $pool = db('crm_c_fp_pool')->where('cid', $value['id'])->find();
                // 如果pool中不存在  insert
                if (!$pool) {
                    // 要进入分配队列的值
                    $message = [
                        'receive'  => '-1',
                        'body'     => $value['id'],
                        'staff_id' => $value['dj_staff_id'],
                        'shop_code'=> $value['shop_code']
                    ];
                    $data = [
                        'cid'         => $value['id'],
                        'msg'         => json_encode($message),
                        'fp_time_out' => $time+300,
                        'count'       => 1,
                        'create_time' => date('Y-m-d H:i:s'),
                    ];
                    db('crm_c_fp_pool')->insert($data);
                    $listName = 'fpCustomerList';
                    push_list($listName, $message);
                }
            }
            unset($fpCustomerList);
        }
    }

    // 处理pool表
    private function dealPool(){
        $this->log('<----开始处理pool表---->');
        $time = time();
        $poolGroup = db('crm_c_fp_pool')
            ->where('fp_time_out', '<=', $time)
            ->where('count', '<', 10)
            ->where('pool_type', 10)
            ->select();
        if($poolGroup){
            $this->log('----pool_type10---插入录入人和追踪人小组信息-所有数据-->'.json_encode($poolGroup));
            foreach ($poolGroup as $key => $value) {
                $this->log('开始执行---插入录入人和追踪人小组信息--->');
                $res = $this->insertImportGroupInfo($value['msg']);
                if($res){
                    $result = db('crm_c_fp_pool')->where('id',$value['id'])->delete();
                }
                $this->log('开始删除---插入录入人和追踪人小组信息--结果->'.$result);
            }
        }
        $poolList = db('crm_c_fp_pool')
            ->where('fp_time_out', '<=', $time)
            ->where('count', '<', 10)
            ->where('pool_type','<>', 10)
            ->select();
        $this->log('<----开始处理pool表---->'.db()->getLastSql());
        $this->log('<----pool表数据---->'.json_encode($poolList));
        // 已经删除的客资，已经分配，已经筛客的客资，从pool表中移除
        if ($poolList) {
            foreach ($poolList as $key => $value) {
                $cInfo = db('crm_c_customerinfo')->where('id',$value['id'])->field('is_status,is_fp')->find();
                // 客资已经删除 pool表同样删除
                if ($cInfo['is_status'] == 2) {
                    db('crm_c_fp_pool')->where('cid', $value['id'])->where('pool_type','<>', 10)->delete();
                    continue;
                }
                // 分配
                if($value['pool_type'] == 1){
                    // 已经分配
                    if ($cInfo['is_fp'] == 1) {
                        db('crm_c_fp_pool')->where('cid', $value['id'])->where('pool_type', 1)->delete();
                    }

                    $this->log('<----fp---->');
                    $msg = json_decode($value['msg'], true);
                    $msg['poo_id'] = $value['id'];
                    $result = push_list('fpCustomerList', $msg);
                    $this->log('<----fp结果---->'.$result.'<br>');
                }
                // 预约进店提醒
                else if($value['pool_type'] == 2){
                    $this->log('<----预约进店提醒---->');
                    $msg = json_decode($value['msg'], true);
                    $consulation_shop = $msg['consulation_shop'];
                    $yjd_time = $msg['yjd_time'];
                    unset($msg['consulation_shop']);
                    unset($msg['yjd_time']);
                    db()->startTrans();
                    try{
                        $this->log('msg---->'.json_encode($msg));
                        $return = sendSystemMessage($msg);
                        $this->log('发送消息结果---->'.$return);
                        // 发送微信模板消息
                        $wxConfirmUrl = config('url_domain_root').'/crm/weixin/receiveCustomer/cid/'.$msg['customer_id'];
                        $content = [
                            'touser'       => $msg['receive_id'],
                            'template_id'  => OPENTM_TX,
                            'url'          => $wxConfirmUrl,
                            'data'         => [
                                'first'=>[
                                    'value'=> $msg['send_msg'],
                                    'color'=> '#173177'
                                ],
                                'keyword1'=>[
                                    'value'=> $yjd_time,
                                    'color'=> '#173177'
                                ],
                                'keyword2'=>[
                                    'value'=> $consulation_shop,
                                    'color'=> '#173177'
                                ],
                                'keyword3'=>[
                                    'value'=>'预约进店',
                                    'color'=> '#173177'
                                ],
                                'remark'=>[
                                    'value'=> '请做好沟通工作，谢谢',
                                    'color'=> '#173177'
                                ]
                            ]
                        ];
                        $send_data['content'] = json_encode($content);
                        $res = sendMsg($send_data);
                        $this->log('发送微信模板消息:'.json_encode($res));

                        $del = db('crm_c_fp_pool')->where('id',$value['id'])->delete();
                        $this->log('信息删除结果---->'.$del);
                        db()->commit();
                    }catch (Exception $e){
                        db()->rollback();
                    }
                }
                // 进店提醒
                else if($value['pool_type'] == 3){
                    $this->log('<----进店提醒---->');
                    $msg = json_decode($value['msg'], true);
                    $consulation_shop = $msg['consulation_shop'];
                    unset($msg['consulation_shop']);
                    db()->startTrans();
                    try{
                        $this->log('msg---->'.json_encode($msg));
                        $return = sendSystemMessage($msg);
                        $this->log('发送消息结果---->'.$return);
                        //发送模板消息
                        db('crm_c_fp_pool')->where('id',$value['id'])->delete();
                        db()->commit();
                    }catch (Exception $e){
                        db()->rollback();
                    }
                }
                // 生日，预产期，结婚纪念日提醒
                else if($value['pool_type'] == 4){
                    $this->log('<----生日,预产期，结婚纪念日提醒---->');
                    $msg = json_decode($value['msg'], true);
                    db()->startTrans();
                    try{
                        $this->log('msg---->'.json_encode($msg));
                        if($msg['send_method'] == 'tan'){
                            $return = sendSystemMessage($msg);
                        }elseif($msg['send_method'] == 'tui'){
                            $content = [
                                'touser'       => $msg['receive_id'],
                                'template_id'  => OPENTM_YX,
                                'data'         => [
                                    'first'=>[
                                        'value'=> $msg['send_title'],
                                        'color'=> '#173177'
                                    ],
                                    'keyword1'=>[
                                        'value'=> $msg['customer_name'],
                                        'color'=> '#173177'
                                    ],
                                    'keyword2'=>[
                                        'value'=> '系统',
                                        'color'=> '#173177'
                                    ],
                                    'keyword3'=>[
                                        'value'=> date('Y-m-d H:i:s'),
                                        'color'=> '#173177'
                                    ],
                                    'remark'=>[
                                        'value'=> '客资ID:'.$msg['customer_id'].'，电话：'.$msg['customer_id'].',请尽快查看，谢谢',
                                        'color'=> '#173177'
                                    ],
                                ]
                            ];
                            $send_data['content'] = json_encode($content);
                            $return = sendMsg($send_data);
                        }
                        $this->log('发送消息结果---->'.$return);
                        //发送短消息
                        db('crm_c_fp_pool')->where('id',$value['id'])->delete();
                        db()->commit();
                    }catch (Exception $e){
                        db()->rollback();
                    }
                }
                // 
                else if($value['pool_type'] == 11){
                    $this->log('<----预约后未进店提醒---->');
                    $msg = json_decode($value['msg'], true);
                    $consulation_shop = $msg['consulation_shop'];
                    $yjd_time = $msg['yjd_time'];
                    unset($msg['consulation_shop']);
                    unset($msg['yjd_time']);
                    db()->startTrans();
                    try{
                        $this->log('msg---->'.json_encode($msg));
                        // 发送微信模板消息
                        $wxConfirmUrl = config('url_domain_root').'/crm/weixin/receiveCustomer/cid/'.$msg['customer_id'];
                        $content = [
                            'touser'       => $msg['receive_id'],
                            'template_id'  => OPENTM_TX,
                            'url'          => $wxConfirmUrl,
                            'data'         => [
                                'first'=>[
                                    'value'=> $msg['send_msg'],
                                    'color'=> '#173177'
                                ],
                                'keyword1'=>[
                                    'value'=> $yjd_time,
                                    'color'=> '#173177'
                                ],
                                'keyword2'=>[
                                    'value'=> $consulation_shop,
                                    'color'=> '#173177'
                                ],
                                'keyword3'=>[
                                    'value'=>'预约未进店',
                                    'color'=> '#173177'
                                ],
                                'remark'=>[
                                    'value'=> '请及时做好沟通工作，谢谢',
                                    'color'=> '#173177'
                                ]
                            ]
                        ];
                        $send_data['content'] = json_encode($content);
                        $cus = controller('crm/Customer','lib')->getCustomerInfo($msg['customer_id']);
                        if(empty($cus['syjd_day'])){
                            $return = sendSystemMessage($msg);
                            $res = sendMsg($send_data);
                            $this->log('发送消息结果---->'.$res);
                            //发送短消息
                            db('crm_c_fp_pool')->where('id',$value['id'])->delete();
                        }

                        db()->commit();
                    }catch (Exception $e){
                        db()->rollback();
                    }
                }
                // 再约电访提醒
                else if($value['pool_type'] == 6){
                    $this->log('<----再约电访提醒---->');
                    $msg = json_decode($value['msg'], true);
                    $next_time = $msg['next_time'];
                    unset($msg['next_time']);
                    db()->startTrans();
                    try{
                        $this->log('msg---->'.json_encode($msg));
                        $return = sendSystemMessage($msg);
                        $this->log('发送消息结果---->'.$return);
                        // 发送微信模板消息
                        $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);
                        $this->log('发送微信模板消息:'.json_encode($res));

                        $del = db('crm_c_fp_pool')->where('id',$value['id'])->delete();
                        $this->log('信息删除结果---->'.$del);
                        db()->commit();
                    }catch (Exception $e){
                        db()->rollback();
                    }
                }
                // 筛客
                else if ($value['pool_type'] == 7) {
                    $cid = $value['cid'];
                    $sklistTemp = json_decode($value['msg'],true);
                    // 只分配给在线的筛客
                    $sklist = controller("crm/Customer","lib")->getMemberOnline($sklistTemp);
                    $this->log('skList：'.json_encode($sklist));
                    // 如果有在线的筛客人
                    if (!empty($skList)) {
                        $rand = rand(0,count($sklist)-1);
                        $arr = $sklist[$rand];
                        $cData['sk_staff_id']= $arr['id'];
                        $cData['sk_staff']   = $arr['staffname'];
                        $cInfoSk = db('crm_c_customerinfo')->where('id',$cid)->value('sk_staff_id');
                        // 如果已经存在筛客人
                        if ($cInfoSk['sk_staff_id']) {
                            $this->log('已有筛客人');
                            db('crm_c_fp_pool')->where('id',$value['id'])->delete();
                            continue;
                        }
                        $res = db('crm_c_customerinfo')->where('id',$cid)->update($cData);
                        $this->log('SQL：'.db()->getLastSql());
                        if ($res===false) {
                            // 更新pool表
                            db('crm_c_fp_pool')->where('id',$value['id'])->update(array('fp_time_out',time()+300));
                            $this->log('分配筛客人失败');
                            continue;
                        }else{
                            $this->log('分配筛客人成功');
                            db('crm_c_fp_pool')->where('id',$value['id'])->delete();
                            // $this->log('SQLD：'.db()->getLastSql());
                        }
                    }else{
                        // 更新pool表
                        db('crm_c_fp_pool')->where('id',$value['id'])->update(array('fp_time_out',time()+300));
                        // $this->log('SQLD：'.db()->getLastSql());
                    }
                }
                else if ($value['pool_type'] == 10) {//插入录入人和追踪人小组信息
                    $this->log('开始执行---插入录入人和追踪人小组信息--->');
                    $res = $this->insertImportGroupInfo($value['msg']);
                    if($res){
                        $result= db('crm_c_fp_pool')->where('id',$value['id'])->delete();
                    }
                    $this->log('开始删除---录入人和追踪人小组信息--结果->'.$result);
                }
            }
        }
    }
    // ERP请求日志批量导入队列
    public function syncLogs(){
        $listName = 'crm_logs_queue';
        $msg = redisQueue::init()->blPop($listName);
        $send= json_decode($msg[1], true);
        $importList = new RunSyncLogs();
        $res = $importList->saveLogs($send);
    }
    /*
     * 统计当月客资 成本 （ 根据渠道花费 ）
     */
    public function runCountCustomerCost(){
        
    }
    /**
     * 自动作废7天前的线上的0收款订单
     * 
     * @return [type] [description]
     */
    public function autoZuofeiZeroOrders($param){
        $zuoFeiOrderDays = $param['zuoFeiOrderDays'] ? $param['zuoFeiOrderDays'] : 7;
        $time = date('Ymd',strtotime('-'.$zuoFeiOrderDays.' day'));
        // echo $time.'<br />';
        /*
        
select o.orderId,o.targetdate,o.storeconsuitant1,o.storeconsuitant2,o.shop_order_name from c_customerorder o join c_customerorder_servicefc fc on o.orderId=fc.orderId and fc.allfc='1'
left join c_customerphoto p on p.orderid = o.orderid left join c_paymentcontent c on c.orderid = o.orderid 
where o.blankoutannal = 0 and o.crm_order_type = 1

         */
        // $sql = 'select o.orderId,o.targetdate,o.storeconsuitant1,o.storeconsuitant2,o.shop_order_name from c_customerorder o join c_customerorder_servicefc fc on o.orderId=fc.orderId and fc.allfc=\'1\' left join c_customerphoto p on p.orderid = o.orderid left join c_paymentcontent c on c.orderid = o.orderid where o.blankoutannal = 0 and o.crm_order_type = 1 and o.targetdate < \''.$time.'\' and (p.photodate = \'\' or p.photodate is null) and c.id is null order by o.id desc';
        $sql = 'select o.orderId,o.targetdate,o.storeconsuitant1,o.storeconsuitant2,o.shop_order_name from c_customerorder o join c_customerorder_servicefc fc on o.orderId=fc.orderId and fc.allfc=\'1\' left join c_customerphoto p on p.orderid = o.orderid left join c_paymentcontent c on c.orderid = o.orderid where o.blankoutannal = 0 and o.targetdate < \''.$time.'\' and (p.photodate = \'\' or p.photodate is null) and c.id is null order by o.id desc limit 1000';
        // var_dump($sql);
        // echo $sql;die;
        $this->log('===》查询语句'.$sql);
        $res = db()->query($sql);
        $orderIds = [];
        foreach ($res as $value) {
            $orderIds[] =  $value['orderId'];
        }
        if($orderIds){
            $libOrder = new Order();
            $data = [
                'zfReason'=>'系统自动作废'.$zuoFeiOrderDays.'天无拍照日期且无收款订单',
                'orderids'=>$orderIds,
            ];
            $res = $libOrder->zfOrder($data);
        }
        // var_dump($res);
    }
    public function log($str){
        if(config('app_debug')){
            if (strtoupper(substr(php_uname(),0,3)) == 'WIN') {
                $str = iconv("UTF-8","GB2312//IGNORE",$str);
            }
            echo date('Y-m-d H:i:s').$str."\r\n";
        }
    }
    //电商渠道漏斗沉淀数据
    function DsChannelLdData($shop_code){
        set_time_limit(0);
        cache('ds_channel_ld_'.$shop_code,1);
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        //如果存在，删除上月沉淀
        $last_month_begin = date("Y-m-d",mktime(0, 0 , 0,date("m")-1,1,date("Y")));
        $id = db('crm_d_ds_channel_ld')->where('shop_code',$shop_code)->where('time',$last_month_begin)->value('id');
        if(empty($id)){
            db('crm_d_ds_channel_ld')->where('shop_code',$shop_code)->where('time','like','%'.date('Y-m',strtotime($last_month_begin)).'%')->delete();
        }
        $month = getdateArea('last_month');
        $start = $month[0];
        $end = $month[1];
        $date = getDateFromRange($start,$end);
        $channel = db('crm_s_channel')->where('shop_code',$shop_code)->order('order_sort')->select();
        $time =' 23:59:59';
        $group = 's.channel_name';
        $insert = [];
        $i = 0;
        foreach($date as $k=>$v){
            $cost = db('crm_s_channel_cost')->alias('c')
                ->where('c.cost_date',$v)
                ->where('c.shop_code', $shop_code)
                ->group('c.channel_name')
                ->column('sum(c.cost) as cost,c.id,c.channel_class_name,c.channel_info_name,c.channel_info_id,cost_date','c.channel_name');
            $sql = 's.channel_class_name,s.channel_info_name,s.id,';
            $sql .= "sum(dj_day between '$v' and '$v.$time') as mkz,";
            $sql .= "sum(is_valid=1 and yx_day between '$v' and '$v.$time') as valid,";//有效
            $sql .= "sum(is_valid=2 and yx_day between '$v' and '$v.$time') as dd,";//待定
            $sql .= "sum(is_valid=1 and c.customer_tel<>'' and yx_day between '$v' and '$v.$time') as tel,";//总手机
            $sql .= "sum(is_intostore in ('2','3','5') and syjd_day between '$v' and '$v.$time') as jd,";
            $sql .= "sum(is_success=1 and order_day between '$v' and '$v.$time') as `order`";
            $info= db('crm_c_customerinfo')->alias('c')->join('crm_s_channel s', 's.id=c.customer_channel_id')
                ->where($where)
                ->where('c.add_shop_code', $shop_code)
                ->group($group)
                ->column($sql,$group);
            $this->log('电商渠道漏斗数据沉淀---综合统计-->');
            // 营收（实际收入  不区分有效无效）
            $fact = db('crm_c_customerinfo')->alias('c')->join('crm_s_channel s', 's.id=c.customer_channel_id')->join('crm_c_order_detail d','d.order_sn=c.order_number')
                ->where($where)
                ->where('d.pay_type',1)
                ->where('d.pay_time', 'between time',[$v, $v.$time])
                ->group($group)
                ->column('count(c.id) as num',$group);
            $this->log('电商渠道漏斗数据沉淀---营收统计-->');
            // 套系均值（有效单套系应收款均值）
            $amount = db('crm_c_customerinfo')->alias('c')->join('crm_s_channel s', 's.id=c.customer_channel_id')->join('crm_c_customer_order o','o.order_sn=c.order_number')
                ->where($where)
                ->where('c.is_success', 1)
                ->where('c.order_day', 'between time',[$v, $v.$time])
                ->group($group)
                ->column('count(c.id) as num',$group);
            $this->log('电商渠道漏斗数据沉淀---套系统计-->');

            foreach($channel as $kk=>$vv){
                $this->log('电商渠道漏斗数据沉淀---渠道循环开始-->');
                $arr = [];
                $arr['shop_code'] = $shop_code;
                $arr['shop_name'] = $vv['shop_name'];
                $arr['brandclass_id'] = $vv['brandclass_id'];
                $arr['brandclass'] = $vv['brandclass_name'];
                $arr['time'] = $v;
                $arr['channel_id'] = $vv['id'];
                $arr['channel_name'] = $vv['channel_name'];
                $arr['channel_info_id'] = $vv['channel_info_id'];
                $arr['channel_info_name'] = $vv['channel_info_name'];
                $arr['cost'] = $cost[$vv['channel_name']] ? $cost[$vv['channel_name']] : 0;
                $arr['mkz'] = $info[$vv['channel_name']]['mkz'] ? $info[$vv['channel_name']]['mkz'] : 0;
                $arr['valid'] = $info[$vv['channel_name']]['valid'] ? $info[$vv['channel_name']]['valid'] : 0;
                $arr['dd'] = $info[$vv['channel_name']]['dd'] ? $info[$vv['channel_name']]['dd'] : 0;
                $arr['tel'] = $info[$vv['channel_name']]['tel'] ? $info[$vv['channel_name']]['tel'] : 0;
                $arr['jd'] = $info[$vv['channel_name']]['jd'] ? $info[$vv['channel_name']]['jd'] : 0;
                $arr['order'] = $info[$vv['channel_name']]['order'] ? $info[$vv['channel_name']]['order'] : 0;
                $arr['fact'] = $fact[$vv['channel_name']] ? $fact[$vv['channel_name']]: 0;
                $arr['amount'] = $amount[$vv['channel_name']] ? $amount[$vv['channel_name']] : 0;
                $arr['amountAVG'] = $arr['amount'] ? sprintf('%.2f',$arr['amount']/$arr['order']) : '';
                $arr['validRate'] = $arr['valid'] ? sprintf('%.2f',$arr['valid']/$arr['mkz']*100).'%' : '';
                $arr['jdRate'] = $arr['jd'] ? sprintf('%.2f',$arr['jd']/$arr['valid']*100).'%' : '';
                $arr['orderRate'] = $arr['order'] ? sprintf('%.2f',$arr['order']/$arr['jd']*100).'%' : '';
                $arr['orderValidRate'] = $arr['order'] ? sprintf('%.2f',$arr['order']/$arr['valid']*100).'%' : '';//有效客资转化率
                $arr['mkzCost'] =  $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['mkz']) : '';
                $arr['validCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['valid']) : '';
                $arr['orderCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['order']) : '';
                $arr['roi'] = sprintf('%.2f',$arr['fact']/$arr['cost']).':1';
                $insert[] = $arr;
                $this->log('电商渠道漏斗数据沉淀---渠道循环--第>'.$i.'次结果:'.json_encode($arr));
                $i++;
                unset($arr);
            }
        }
        db()->startTrans();
        try{
            $this->log('电商渠道漏斗数据沉淀---准备插入数据库-->');
            $res = db('crm_d_ds_channel_ld')->insertAll($insert);
            $this->log('电商渠道漏斗数据沉淀---插入数据库结果-->'.$res);
            $log = [];
            $log['action'] = '电商渠道漏斗--沉淀';
            $log['code'] = 200;
            $log['error_reason'] = null;
            $log['create_time'] = date('Y-m-d H:i:s');
            db('crm_l_error_log')->insert($log);
            db()->commit();
            cache('ds_channel_ld_'.$shop_code,2);
            unset($cost,$insert,$log,$info,$amount,$channel,$fact);
            return true;
        }catch (\Exception $e){
            db()->rollback();
            $log = [];
            $log['action'] = '电商渠道漏斗--沉淀';
            $log['code'] = 100;
            $log['error_reason'] = $e->getMessage();
            $log['create_time'] = date('Y-m-d H:i:s');
            db('crm_l_error_log')->insert($log);
            cache('ds_channel_ld_'.$shop_code,3);
            $this->log('电商渠道漏斗数据沉淀---插入数据库失败-->'.$e->getMessage());
            unset($cost,$insert,$log,$info,$amount,$channel,$fact);
            return false;
        }
    }
    //网销小组数据统计沉淀
    function WxGroup($shop_code){
        set_time_limit(0);
        cache('wx_group_'.$shop_code,1);
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        //如果存在，删除上月沉淀
        $last_month_begin = date("Y-m-d",mktime(0, 0 , 0,date("m")-1,1,date("Y")));
        $id = db('crm_d_wx_group')->where('shop_code',$shop_code)->where('time',$last_month_begin)->value('id');
        if(empty($id)){
            db('crm_d_wx_group')->where('shop_code',$shop_code)->where('time','like','%'.date('Y-m',strtotime($last_month_begin)).'%')->delete();
        }
        $month = getdateArea('last_month');
        $start = $month[0];
        $end = $month[1];
        $date = getDateFromRange($start,$end);
        $time =' 23:59:59';
        $group = 'r.staff_id';
        //组内所有人 0609
        $staff = db('c_staff_group')->alias('g')->join('c_staff_group_relation r','g.id=r.group_id')
            ->where('g.shop_code',$shop_code)
            ->field('g.id,g.group_name,r.staff_id,r.staff_name,g.shop_name')
            ->select();
        if(!$staff[0]['staff_name']){
            $staffIds = implode(',',array_column($staff,'staff_id'));
            $mc = new \app\common\lib\mcInterface();
            $res = $mc->getStaffByIds($staffIds);
            unset($mc);
            $staffNames = [];
            if($res !== false){
                $info = $res['data'];
                foreach($info as $key=>$val){
                    $staffNames[$val['id']] = $val['staffname'];
                }
                $this->log('网销小组数据统计--小组中没有名字的人员--'.json_encode($staffNames));
            }else{
                $log = [];
                $log['action'] = '网销小组数据统计--沉淀';
                $log['code'] = 100;
                $log['error_reason'] = '批量查询小组人员失败';
                $log['create_time'] = date('Y-m-d H:i:s');
                db('crm_l_error_log')->insert($log);
                unset($log,$staff,$staffNames);
                return false;
            }
        }
        $insert = [];
        $i = 0;
        foreach($date as $k=>$v){
            $sql = 'g.group_name,c.sales_staff,';
            $sql .= "sum(dj_day between '$v' and '$v.$time') as mkz,";
            $sql .= "sum(jr_day between '$v' and '$v.$time') as jr,";
            $sql .= "sum(is_valid=1 and yx_day between '$v' and '$v.$time') as valid,";//有效
            $sql .= "sum(is_valid=2 and yx_day between '$v' and '$v.$time') as dd,";//待定
            $sql .= "sum(is_valid=3 and yx_day between '$v' and '$v.$time') as wx,";//无效
            $sql .= "sum(is_first_tel is null and dj_day between '$v' and '$v.$time') as notel,";//电商 未获取手机数
            $sql .= "sum(is_first_tel is null and customer_tel<>'' and customer_tel is not null and dj_day between '$v' and '$v.$time') as zhuanTel,";//转手机数
            $sql .= "sum(is_valid=1 and c.customer_tel<>'' and yx_day between '$v' and '$v.$time') as tel,";//总手机
            $sql .= "sum(is_intostore in ('2','3','5') and syjd_day between '$v' and '$v.$time') as jd,";
            $sql .= "sum(is_success=1 and order_day between '$v' and '$v.$time') as `order`,";
            $sql .= "sum(is_loss=1 and loss_day between '$v' and '$v.$time') as loss";
            $info= db('crm_c_customerinfo')->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
            ('c_staff_group g','g.id=r.group_id')
                ->where($where)
                ->where('c.shop_code', $shop_code)
                ->group($group)
                ->order('g.id desc')
                ->column($sql,'r.staff_id');
            $this->log('网销小组数据统计--综合查询--');
            //套系金额 套系金额累计（按订单时间计算）设定类型
            $amount = db('crm_c_customerinfo')->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
            ('c_staff_group g','g.id=r.group_id')->join('crm_c_customer_order o','c.order_number=o.order_sn')
                ->where($where)
                ->where('c.shop_code','in',$shop_code)
                ->where('c.is_success', 1)
                ->where('o.order_valid', 2)
                ->where('c.order_start_time', 'between time', [$v, $v.$time])
                ->group('r.staff_id')
                ->order('g.id desc')
                ->column('sum(o.order_amount) as sum,c.sales_staff,g.group_name','r.staff_id');
            $this->log('网销小组数据统计--套系---');
            //实收金额累计(按订单时间计算)
            $fact = db('crm_c_customerinfo')->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
            ('c_staff_group g','g.id=r.group_id')->join('crm_c_order_detail d','d.order_sn=c.order_number')
                ->where($where)
                ->where('c.shop_code','in',$shop_code)
                ->where('d.pay_type',1)
                ->where('d.pay_time', 'between time', [$v, $v.$time])
                ->group('r.staff_id')
                ->order('g.id desc')
                ->column('sum(d.order_fact) as sum','r.staff_id');
            $this->log('网销小组数据统计--实收---');
            //预付定金 实收金额大于0，低于有效订单标准，的实收累计（订单时间计算）
            $dj = db('crm_c_customerinfo')->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
            ('c_staff_group g','g.id=r.group_id')->join('crm_c_customer_order o','o.order_sn=c.order_number')
                ->where($where)
                ->where('c.shop_code',$shop_code)
                ->where('c.is_success', 3)
                ->where('o.order_valid', 1)
                ->where('o.target_time', 'between time', [$v, $v.$time])
                ->group('r.staff_id')
                ->order('g.id desc')
                ->column('sum(o.earnest_money) as sum','r.staff_id');
            $this->log('网销小组数据统计--定金---');
            foreach($staff as $kk=>$vv){
                $arr = [];
                $arr['time'] = $v;
                $arr['group_name'] = $vv['group_name'];
                $arr['staff_name'] = $vv['staff_name'] ? $vv['staff_name'] : $staffNames[$vv['staff_id']];
                $arr['shop_code'] = $shop_code;
                $arr['shop_name'] = $vv['shop_name'];
                $arr['mkz'] = $info[$vv['id']]['mkz'] ? $info[$vv['id']]['mkz'] : 0;
                $arr['jr'] = $info[$vv['id']]['jr'] ? $info[$vv['id']]['jr'] : 0;
                $arr['valid'] = $info[$vv['id']]['valid'] ? $info[$vv['id']]['valid'] :0;
                $arr['dd'] = $info[$vv['id']]['dd'] ? $info[$vv['id']]['dd']: 0;
                $arr['wx'] = $info[$vv['id']]['wx'] ? $info[$vv['id']]['wx'] : 0;
                $arr['validRate'] = $arr['valid'] ? sprintf('%.2f',$arr['valid']/$arr['mkz']*100).'%' : '';
                $arr['wxRate'] = $arr['wx'] ? sprintf('%.2f',$arr['wx']/$arr['mkz']*100).'%' : '';
                $arr['ddRate'] = $arr['dd'] ? sprintf('%.2f',$arr['dd']/$arr['mkz']*100).'%' : '';
                $arr['notel'] = $info[$vv['id']]['notel'] ? $info[$vv['id']]['notel'] : 0;
                $arr['zhaunTel'] = $info[$vv['id']]['zhaunTel'] ? $info[$vv['id']]['zhaunTel'] :0;
                $arr['zhaunRate'] = $arr['zhaunTel'] ? sprintf('%.2f',$arr['zhaunTel']/$arr['notel']*100).'%' : '';
                $arr['tel'] = $info[$vv['id']]['tel'] ? $info[$vv['id']]['tel'] : 0;
                $arr['jd'] = $info[$vv['id']]['jd'] ? $info[$vv['id']]['jd'] : 0;
                $arr['jdRate'] = $arr['jd'] ? sprintf('%.2f',$arr['jd']/$arr['valid']*100).'%' : '';
                $arr['order'] = $info[$vv['id']]['order'] ? $info[$vv['id']]['order'] :0;
                $arr['orderRate'] = $arr['order'] ? sprintf('%.2f',$arr['order']/$arr['jd']*100).'%' : '';
                $arr['loss'] = $info[$vv['id']]['loss'] ? $info[$vv['id']]['loss'] : 0;
                $arr['lossRate'] = $arr['loss'] ? sprintf('%.2f',$arr['loss']/$arr['jd']*100).'%' : '';
                $arr['amount'] = $amount[$vv['id']] ? $amount[$vv['id']] : 0;
                $arr['fact'] = $fact[$vv['id']] ? $fact[$vv['id']] : 0;
                $arr['yk'] = $arr['fact'] ? sprintf('%.2f',$arr['amount']-$arr['fact']) : '';
                $arr['dj'] = $dj[$vv['id']]['sum'] ? sprintf('%.2f',$dj[$vv['id']]['sum']) : 0;
                $arr['orderMkzRate'] = $arr['order'] ? sprintf('%.2f',$arr['order']/$arr['mkz']*100).'%' : '';//总客资成单率
                $arr['orderValidRate'] = $arr['order'] ? sprintf('%.2f',$arr['order']/$arr['valid']*100).'%' : '';//有效客资成单率
                $this->log('网销小组数据统计--第'.$i.'条数据：'.json_encode($arr));
                $i++;
                $insert[] = $arr;
                unset($arr);
            }
        }
        db()->startTrans();
        try{
            $this->log('网销小组数据统计--沉淀--准备插入数据库');
            $res = db('crm_d_wx_group')->insertAll($insert);
            $this->log('网销小组数据统计--沉淀--插入数据库结果'.$res);
            $log = [];
            $log['action'] = '网销小组数据统计--沉淀';
            $log['code'] = 200;
            $log['error_reason'] = null;
            $log['create_time'] = date('Y-m-d H:i:s');
            db('crm_l_error_log')->insert($log);
            db()->commit();
            cache('wx_group_'.$shop_code,2);
            unset($insert,$log,$info,$amount,$dj,$fact);
            return true;
        }catch (\Exception $e){
            db()->rollback();
            $log = [];
            $log['action'] = '网销小组数据统计--沉淀';
            $log['code'] = 100;
            $log['error_reason'] = $e->getMessage();
            $log['create_time'] = date('Y-m-d H:i:s');
            db('crm_l_error_log')->insert($log);
            cache('wx_group_'.$shop_code,3);
            $this->log('网销小组数据统计--插入数据库失败'.$e->getMessage());
            unset($insert,$log,$info,$amount,$dj,$fact);
            return false;
        }
    }
}