<?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 $dfpCount = 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('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('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
                    {
                        $this->log('infp--'.$send['body'].'--'.$send['staff_id'].'--'.$send['shop_code']);
                        $fpList->run($send['body'],$send['staff_id'],$send['shop_code']);
                    }
                }
                // 不在分配时间段内 insert into c_fp_pool
                else{
                    $this->log('不在分配时间段内,开始插入待处理池。');
                    $poolInfo = db('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('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(){
        $this->log('rundata 服务已不再使用。');
        sleep(3600);
        // $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 insertImportGroupInfo($eid){
        $info = db('c_customerinfo')->field('id,dj_staff_id,sales_staff_id')->where('eid',$eid)->select();
        $this->log('找到导入ID为：'.count($info).'条数据，处理部门及小组信息');
        $group = [];
        $groupInfo = [];
        foreach($info as $k=>$v){
            if(!$groupInfo){
                $groupInfo = getGroupInfo($v['dj_staff_id']);
            }
            $cid = db('c_customer_from')->where('cid',$v['id'])->value('cid');
            //不存在,批量插入
            if(empty($cid)) {
                $group[$k]['cid'] = $v['id'];
                $group[$k]['dj_group_id'] = $groupInfo['id'] ? $groupInfo['id'] : null;
                $group[$k]['dj_group_name'] = $groupInfo['group_name'] ? $groupInfo['group_name'] : null;
                if ($v['sales_staff_id']) {
                    $salesgroupInfo = getGroupInfo($v['sales_staff_id']);
                    if (!empty($salesgroupInfo)) {
                        $group[$k]['sales_group_id'] = $salesgroupInfo['id'] ? $salesgroupInfo['id'] : null;
                        $group[$k]['sales_group_name'] = $salesgroupInfo['group_name'] ? $salesgroupInfo['group_name'] : null;
                    }else {
                        $group[$k]['sales_group_id'] = null;
                        $group[$k]['sales_group_name'] = null;
                    }
                } else {
                    $group[$k]['sales_group_id'] = null;
                    $group[$k]['sales_group_name'] = null;
                }
                unset($salesgroupInfo);
            }else{ //已有此数据，修改
                $update['dj_group_id'] = $groupInfo['id'] ? $groupInfo['id'] : null;
                $update['dj_group_name'] = $groupInfo['group_name'] ? $groupInfo['group_name'] : null;
                if ($v['sales_staff_id']) {
                    $salesgroupInfo = getGroupInfo($v['sales_staff_id']);
                    if (!empty($salesgroupInfo)) {
                        $update['sales_group_id'] = $salesgroupInfo['id'] ? $salesgroupInfo['id'] : null;
                        $update['sales_group_name'] = $salesgroupInfo['group_name'] ? $salesgroupInfo['group_name'] : null;
                    }else {
                        $update['sales_group_id'] = null;
                        $update['sales_group_name'] = null;
                    }
                } else {
                    $update['sales_group_id'] = null;
                    $update['sales_group_name'] = null;
                }
                $result = db('c_customer_from')->where('cid',$v['id'])->update($update);
                if($result){
                    $this->log($v['id'].'---修改录入人和追踪人小组信息结果--->'.$result);
                }
            }
        }
        if(!empty($group)){
            $res = db('c_customer_from')->insertAll($group);
            $this->log('---插入录入人和追踪人小组信息结果--->'.$res);
            return $res;
        }
        $this->log('没有需要插入录入人和追踪人小组的数据');
        unset($info,$groupInfo,$group);
        return true;
    }
    // 批量导入队列
    public function excelImport(){
        $send = array();
        $listName = 'excelImportRedisList';
        $msg = redisQueue::init()->blPop($listName);
        // var_dump($msg);
        if ($msg) {
            $send= json_decode($msg[1], true);
            // var_dump($send);
            // exit;
            $importList = new RunExcelImport();
            $res = $importList->cus_import($send['body']);
        }
        // exit;

    }
    //每天凌晨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('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);
                }
            }
        }
        unset($info,$valid_dates,$arr,$k,$v,$lastDate,$ids,$res);
    }
    public function clearFPRuleDJ(){
        cache('fpRuleStaffs_*',null);
        $this->log('<----每天清除分配分配规则---->');
        $ret = cache('fpCustomerP*',null);
        $this->log('<----每天清除分配人员次序---->'.$ret);
        $res = db('s_allocation_rule')->where('brandclass_id','not null')->update(['staff_value1'=>NULL]);
        $this->log('<----每天清除分配人员信息结果---->'.$res);
    }
    // 自动分配定时任务
    public function cronCustomerFp(){
        // $this->log('开始进入分配----->');
        $auto_day = cache('auto_day');
        $auto_hour= cache('auto_hour');
        $auto_min = cache('auto_min');

        // 一月操作一次
        if (!$auto_month || $auto_month < date('Ym')) {
            
            //删除c_message表一个月前的消息
            db('c_message')->where('send_time','<',date("Y-m-d 00:00:00",strtotime('-1 month')))->delete();
        }
        // 一周操作一次 date('w') 周几 （0-6）
        // if (!$auto_week || $auto_week < date('w')) {
        //     # code...
        // }
        //一天操作一次
        if (!$auto_day || $auto_day < date('Ymd')) {
            cache('auto_day', date('Ymd'));
            //天长清除登记人员分配规则
            // $this->clearFPRuleDJ();
            //修复部门名称
            if (ini('rundfp.repairDepartmentname')==1) {
                $this->repairDepartmentname();
            }
            // 根据渠道花费 统计 每个渠道客资的 成本
            // $this->channelCost();
            // 把渠道花费分摊到每个追踪人上，如果没有追踪人，则给一个空追踪人
            if (ini('rundfp.channelCostByStaff')==1) {
                $this->channelCostByStaff();
            }
            // $this->clearContact(); //  每天清除一次过期联系方式
            /**/
            // 每天自动标记预约未进店为  邀约未进店 爽约
            if (ini('rundfp.sysAutosy')==1) {
                $this->sysAutosy();
            }
            // 自动标记昨日进店未成交客资为流失
            if (ini('rundfp.sysAutoLoss')==1) {
                $this->sysAutoLoss();
            }
            // 醉唐风 客资分配之后，一个月内无法成单，回到客资池，待分配
            if (ini('rundfp.unorderReturn')==1) {
                $this->unorderReturn();
            }
            // 客资数据沉淀方法 每天一次
            // $this->runCustomerDeposition();
            //自动检测结婚纪念日,生日，预产期，宝宝生日，插入pool表
            if (ini('rundfp.sysMarryDay')==1) {
                $this->sysMarryDay();
            }
            if (ini('rundfp.sysBirthday')==1) {
                $this->sysBirthday();
            }
            if (ini('rundfp.sysMateBirthday')==1) {
                $this->sysMateBirthday();
            }
            if (ini('rundfp.sysReadyBabyday')==1) {
                $this->sysReadyBabyday();
            }
            if (ini('rundfp.sysBabyBirthday')==1) {
                $this->sysBabyBirthday();
            }
            //电商渠道漏斗数据沉淀
            if (ini('rundfp.DsChannelLdData')==1) {
                $form_id = db('s_report_form')->where('report_class_name','Ds_channel_ld')->value('id');
                $shop_code = db('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('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']);
                    }
                }
                unset($form_id,$shop_code,$id,$k,$v);
            }
            //网销小组数据统计
            if (ini('rundfp.WxGroup')==1) {
                $g_id = db('s_report_form')->where('report_class_name','Wx_group1')->value('id');
                $shopcode = db('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('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']);
                    }
                }
                unset($g_id,$shopcode,$k,$v,$id);
            }
        }
        /**/
        //一小时操作一次
        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();
            }
            // 处理pool中的数据
            if (ini('rundfp.dealPool')==1) {
                $this->dealPool();
            }
            // 收款后核对订单
            if (ini('rundfp.checkCustomerOrder')==1) {
                $this->log('=== checkCustomerOrder ===');
                $this->checkCustomerOrder();
            }

        }
        // unset($auto_day,$auto_hour,$auto_min);


        //发消息
        $listName1 = 'sendSystemMessage';
        $msg1 = redisQueue::init()->blPop($listName1);
        if(!empty($msg1)) {
            $send1 = json_decode($msg1[1], true);

            if(sendSystemMessage($send1)){
                $send_messge = 'sendSystemMessage-ok:'.json_encode($send_messge);
            }else{
                $send_messge = 'sendSystemMessage-no:'.json_encode($send_messge);
            };

            $this->log($send_messge);
        }

        //发消息
        $listName2 = 'sendMsg';
        $msg2 = redisQueue::init()->blPop($listName2);
        if(!empty($msg2)) {
            $send2 = json_decode($msg2[1], true);

            if(sendMsg($send2)){
                $send_msg = 'sendMsg-ok:'.json_encode($send_msg);
            }else{
                $send_msg = 'sendMsg-no:'.json_encode($send_msg);
            };

            $this->log($send_msg);
        }

        $dfpCount = $this->dfpCount;
        if ($dfpCount<100) {
            $this->dfpCount++;
        }else{
            $this->dfpCount = 0;
            exit;
        }
    }
    // 订单收款之后，erp操作本单作废之后，erp删除订单之后 会存入一条数据到 c_fp_pool表  type 11 直接查erp库，同步核对订单信息 类似于erp的算总钱方法
    public function checkCustomerOrder(){
        $this->log('<----开始处理pool表中的订单---->');
        // echo '<----开始处理pool表中的订单----> <br />';
        $time = time();
        $orderPool = db('c_fp_pool')
            ->where('fp_time_out', '<=', $time)
            ->where('count', '<', 10)
            ->where('pool_type', 11)
            ->select();
        foreach ($orderPool as $key => $value) {
            $order_sn = $value['msg'];
            $cid = $value['cid'];
            if ($order_sn) {
                try {
                    $field = 'o.orderId,o.consumption_type,o.package_name,o.targetdate,o.total_money,o.payment_money,o.bargain_money,o.yixiaopaid_money,o.supplementary_money,o.erxiaopaid_money,o.blankoutannal,o.blankoutannalremark,o.is_effectiveday,o.bargainoverdate,c.cssname,c.customer_channel,c.customer_from_index';
                    $orderInfo = db('c_customerorder','sx_erp_hs')->alias('o')
                        ->join('c_customerinfo c','c.customerid=o.customerid','left')
                        ->where('o.orderId', $order_sn)
                        ->field($field)
                        ->find();
                } catch (\Exception $e) {
                    $this->log('<----获取订单信息报错---->'.$e->getMessage());
                    // echo '<----获取订单信息报错---->'.$e->getMessage().' <br />';
                    continue;
                }
                // 订单存在
                if ($orderInfo) {
                    $this->log('<----开始处理客资订单---->'.json_encode($orderInfo));
                    // echo '<----开始处理客资订单---->'.json_encode($orderInfo).' <br />';
                    $cOrder = db('c_customer_order')->where('order_sn',$order_sn)->find();
                    $upCusOrder = [];
                    // 有效时间
                    if ( date('Ymd',strtotime($orderInfo['is_effectiveday']))!=date('Ymd',strtotime($cOrder['valid_time'])) ) {
                        $upCusOrder['valid_time'] = date('Y-m-d H:i:s', strtotime($orderInfo['is_effectiveday']));
                    }
                    // 一销全款时间
                    if ( date('Ymd',strtotime($orderInfo['bargainoverdate']))!=date('Ymd',strtotime($cOrder['bargainoverdate'])) ) {
                        $upCusOrder['bargainoverdate'] = date('Y-m-d H:i:s', strtotime($orderInfo['bargainoverdate']));
                    }
                    // 消费类型
                    if ($orderInfo['consumption_type']!=$cOrder['consultation_type']) {
                        $upCusOrder['consultation_type'] = $orderInfo['consumption_type'];
                    }
                    // 套系名称
                    if ($orderInfo['package_name']!=$cOrder['package_name']) {
                        $upCusOrder['package_name'] = $orderInfo['package_name'];
                    }
                    // 一销营收
                    if ($orderInfo['bargain_money']!=$cOrder['order_amount']) {
                        $upCusOrder['order_amount'] = $orderInfo['bargain_money'];
                    }
                    // 一销已付
                    if ($orderInfo['yixiaopaid_money']!=$cOrder['order_fact']) {
                        $upCusOrder['order_fact'] = $orderInfo['yixiaopaid_money'];
                    }
                    // 二销营收
                    if ($orderInfo['supplementary_money']!=$cOrder['two_pin_amount']) {
                        $upCusOrder['two_pin_amount'] = $orderInfo['supplementary_money'];
                    }
                    // 二销已付
                    if ($orderInfo['erxiaopaid_money']!=$cOrder['two_pin_fact']) {
                        $upCusOrder['two_pin_fact'] = $orderInfo['erxiaopaid_money'];
                    }
                    // 是否作废 erp作废，crm没作废
                    if ($orderInfo['blankoutannal']==1 && $cOrder['refund']=!2) {
                        $upCusOrder['refund'] = 2;
                        $upCusOrder['unvalid_time'] = date('Y-m-d H:i:s');
                    }
                    // 是否作废 erp没作废，crm作废
                    else if ($orderInfo['blankoutannal']!=1 && $cOrder['refund']==2) {
                        $upCusOrder['refund'] = 1;
                        $upCusOrder['unvalid_time'] = NULL;
                    }
                    // 更新客资订单表
                    if (!empty($upCusOrder)) {
                        $this->log('<----订单信息---->'.json_encode($upCusOrder));
                        db('c_customer_order')->where('id',$cOrder['id'])->update($upCusOrder);
                    }
                    $dealParam['cid'] = $cOrder['customer_id'];
                    dealCustomerOrder($dealParam);
                }
                db('c_fp_pool')->where('id',$value['id'])->delete();
            }else{
                db('c_fp_pool')->where('id',$value['id'])->delete();
            }
        }
        unset($time,$orderPool,$order_sn,$cid,$field,$orderInfo,$cOrder,$upCusOrder,$dealParam,$key,$value);
    }

    //检测结婚纪念日
    public function sysMarryDay(){
        $this->log('检测结婚纪念日---开始-->');
        $info = db('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('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('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('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('c_fp_pool')->insert($arr);
            }
        }
        unset($info,$k,$v,$remind,$message,$arr);
    }
    //检测客户生日
    public function sysBirthday(){
        $this->log('检测客户生日---开始-->');
        $info = db('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('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('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('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('c_fp_pool')->insert($arr);
            }
        }
        unset($info,$k,$v,$remind,$message,$arr);
    }
    //检测配偶生日
    public function sysMateBirthday(){
        $this->log('检测配偶生日---开始-->');
        $info = db('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('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('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('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('c_fp_pool')->insert($arr);
            }
        }
        unset($info,$k,$v,$remind,$message,$arr);
    }
    //检测预产期
    public function sysReadyBabyday(){
        $this->log('检测预产期---开始-->');
        $info = db('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('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('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('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('c_fp_pool')->insert($arr);
            }
        }
        unset($info,$k,$v,$remind,$message,$arr);
    }
    //检测宝宝生日
    public function sysBabyBirthday(){
        $this->log('检测宝宝生日---开始-->');
        $info = db('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('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('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('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('c_fp_pool')->insert($arr);
            }
        }
        unset($info,$k,$v,$remind,$message,$arr);
    }
    // 成本计算 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('c_customerinfo')
            ->where('c_from', 1)->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('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('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('c_customerinfo c')->join('c_customer_from f','c.id=f.cid','left')->where('c.dj_day','between',[$cStart,$cEnd])->update(array('f.c_channel_cost'=>0));

                // $this->log(' -- 开始：'.$start.'；结束：'.$end);
                $channelCost= db('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 $k => $v) {
                    $where['customer_channel_id'] = $v['channel_id'];
                    $where['customer_channel'] = $v['channel_name'];
                    $where['shop_code'] = $v['belong_shop_code'];
                    $where['is_status'] = 1;
                    $cStart= date('Y-m-d 00:00:00', strtotime($v['cost_date']));
                    $cEnd  = date('Y-m-d 23:59:59', strtotime($v['cost_date']));
                    $cInfos= db('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(($v['cost']/$num), 2);
                    // $this->log('--ave--：'.$ave);
                    $saveInfo = [];
                    $inData = [];
                    foreach ($cInfos as $ke => $val) {
                        // $this->log(' -- ID：'.$val['id']);
                        $res = db('c_customer_from')->where('cid',$val['id'])->value('cid');
                        // $this->log(' -- cidSql：'.db()->getLastSql());
                        // $this->log(' -- cidRes：'.$res);
                        // // 判断客资补充表里是否存在
                        if ($res) {
                            // $this->log(' -- inRes：');
                            // $temp['cid'] = $val['id'];
                            // $temp['c_channel_cost'] = $ave;
                            // array_push($saveInfo, $temp);
                            db('c_customer_from')->where('cid', $val['id'])->update(array('c_channel_cost'=>$ave));
                            // $this->log(' -- fromSql：'.db()->getLastSql());
                        }else{
                            // $this->log(' -- elseRes：');
                            $temp['cid'] = $val['id'];
                            $temp['c_channel_cost'] = $ave;
                            array_push($inData, $temp);
                        }
                    }
                    // $this->log(' -- inData：'.json_encode($inData));
                    // exit;
                    if (!empty($inData)) {
                        db('c_customer_from')->insertAll($inData);
                    }
                    // 批量更新 erp临时数据
                    // $fInfo = Model('c_customer_from');
                    // $fInfo->saveAll($saveTInfo);
                }
            }
        }
        unset($day,$today,$start,$end,$cStart,$cEnd);
        unset($shop_codes,$key,$value,$accDay,$channelCost,$k,$v,$where,$num,$cInfos,$ke,$val,$inData,$res,$temp);
    }
    // 根据追踪店面，group by 追踪人 将电商的花费平均到每个追踪人上
    public function channelCostByStaff(){
        // set_time_limit(0);
        // 当前日期 （几号）
        $day   = date('d');
        $today = date('Y-m-d');
        // 查最近两个月的客资的 add_shop_code （accounting_channel_cost_LSDS01）
        $shop_codes = db('c_customerinfo')
            ->where('c_from', 1)->whereTime('dj_day','-60 days')
            ->group('add_shop_code')
            ->field('add_shop_code')
            ->select();
        $this->log(' -- 客资录入店列表'.json_encode($shop_codes));

        // 部门数据
        $departments = controller('crm/Customer', 'lib')->getDepartment();
        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;
                }
                // 如果核算日期 大于等于 当前日期  只统计当月 及上月 渠道花费 平均给渠道的每一个客资
                else{
                    // $this->log(' -- >=');
                    $start= date('Y-m-01', strtotime('-1 month'));
                    $end  = $today;
                }
                // $this->log(' -- 开始：'.$start.'；结束：'.$end);
                $channelCost= db('s_channel_cost')->where('cost','>','0')->where('shop_code',$value['add_shop_code'])->where('cost_date', 'between', [$start, $end])->order('channel_id,belong_shop_code')->field('channel_id,channel_name,belong_shop_code,belong_shop_name,cost,cost_date')->select();
                // $this->log(' -- SQL：'.db()->getLastSql());
                // $i = 0;
                foreach ($channelCost as $k => $v) {
                    // var_dump($v);
                    // exit;
                    $where['customer_channel_id'] = $v['channel_id'];
                    $where['customer_channel'] = $v['channel_name'];
                    $where['shop_code'] = $v['belong_shop_code'];
                    $where['is_status'] = 1;
                    $where['c_from']    = 1;
                    $cStart= date('Y-m-d 00:00:00', strtotime($v['cost_date']));
                    $cEnd  = date('Y-m-d 23:59:59', strtotime($v['cost_date']));
                    $cInfos= db('c_customerinfo')
                        ->where($where)->where('dj_day','between',[$cStart, $cEnd])
                        ->field('count(id) as num,sales_staff,sales_staff_id,sales_department_id')
                        ->group('sales_staff')
                        ->select();
                    // $this->log(' -- customerInfo-->SQL：'.db()->getLastSql());
                    $c_all_num = 0;
                    foreach ($cInfos as $k1 => $v1) {
                        $c_all_num +=  $v1['num'];
                    }
                    // $this->log('--ave--：'.$ave);
                    $ave = $v['cost']/$c_all_num;
                    $inData = [];
                    foreach ($cInfos as $k2 => $v2) {
                        $isId = db('c_staff_channel_cost')
                            ->where('staff_id',$v2['sales_staff_id'])
                            ->where('channel_id',$v['channel_id'])
                            ->where('day',$v['cost_date'])
                            ->delete();
                        $costData['c_num']    = $v2['num'];
                        $costData['c_all_num']= $c_all_num;
                        $costData['cost']     = $v2['num']*$ave;
                        $costData['all_cost'] = $v['cost'];
                        // 
                        $costData['staff_id']       = $v2['sales_staff_id'];
                        $costData['staff_name']     = $v2['sales_staff'];
                        $gInfo = getGroupInfo($v2['sales_staff_id']);
                        $costData['group_id']       = $gInfo['id'];
                        $costData['group_name']     = $gInfo['group_name'];
                        $costData['department_id']  = $v2['sales_department_id'];
                        $costData['department_name']= $departments[$v2['sales_department_id']]['department_name'];
                        $costData['shop_code']      = $v['belong_shop_code'];
                        $costData['shop_name']      = $v['belong_shop_name'];
                        $costData['day']            = $v['cost_date'];
                        $costData['channel_id']     = $v['channel_id'];
                        $costData['channel_name']   = $v['channel_name'];
                        array_push($inData,$costData);
                        unset($isId,$costData,$gInfo);
                    }
                    if (!empty($inData)) {
                        db('c_staff_channel_cost')->insertAll($inData);
                        unset($inData);
                    }
                    unset($where,$cStart,$cEnd,$cInfos,$c_all_num,$ave);
                }
            }
        }
        unset($day,$today,$shop_codes,$departments);
        unset($key,$k,$k1,$k2,$value,$v,$v1,$v2);
        unset($accDay,$start,$end,$channelCost,$where,$cStart,$cEnd,$cInfos,$c_all_num,$ave,$inData,$isId,$costData);
    }
    // 醉唐风 客资分配之后，一个月内（30天可设定）无法成单，回到客资池，待分配
    public function unorderReturn(){
        $bids = db('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('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('c_customerinfo')->where('id', 'in', $ids)->update($data);
                    // insertAll action_log fp_log
                    db('action_log','db_logs')->insertAll($lData);
                    // 新增追踪记录
                    db('c_salestrackinginfo')->insertAll($sData);
                    db()->commit();
                } catch (\Exception $e) {
                    db()->rollback();
                    $this->log('errorMessage：==>'.$e->getMessage());
                    continue;
                }
            }
        }
        unset($bids,$orderReturn,$date,$where,$start,$end,$ids,$temp,$data,$tempL,$tempS,$lData,$sData);
    }
    // 每天自动标记预约未进店为  邀约未进店 爽约
    private function sysAutosy(){
        $this->log('开始标记爽约------');
        $data = [
            'is_intostore' => 4,
        ];
        $info = db('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('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('c_customer_intostore');
        if ($table === true) {
            $Idata = [
                'is_intostore' => 4,
                'syjd_day' => NULL,
            ];
            $ires = db('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($data,$info,$res,$log,$table,$Idata,$ires);
    }
    /*
     *   每天凌晨沉淀数据
     */
    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 = '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('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('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('c_customerinfo')->where('id',$cid)->value('sk_staff_id');
                // 如果已经存在筛客人
                if ($cInfoSk['sk_staff_id']) {
                    $this->log('已有筛客人');
                    db('c_fp_pool')->where('id',$value['id'])->delete();
                    continue;
                }
                $res = db('c_customerinfo')->where('id',$cid)->update($cData);
                $this->log('SQL：'.db()->getLastSql());
                if ($res===false) {
                    // 更新pool表
                    db('c_fp_pool')->where('id',$value['id'])->update(array('fp_time_out',time()+300));
                    $this->log('分配筛客人失败');
                    continue;
                }else{
                    $this->log('分配筛客人成功');
                    db('c_fp_pool')->where('id',$value['id'])->delete();
                    // $this->log('SQLD：'.db()->getLastSql());
                }
            }else{
                // 更新pool表
                db('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('c_customerinfo')->group('brandclass_id')->column('brandclass_id');
        $this->log("所有事业部id :-->".json_encode($bids));
        foreach($bids as $k=>$v){
            //获取设定时间
            $hour = db_config('auto_valid_'.$v);
            $this->log("事业部id的自动标记有效设定时间 :-->".$hour);
            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('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('c_customerinfo')->where('id','in',$ids)->update($valid);
                        db('c_salestrackinginfo')->insertAll($trackLog);
                        db()->commit();
                    } catch (\Exception $e) {
                        db()->rollback();
                        $this->log("系统自动标记有效失败：".$e->getMessage());
                    }
                    $count = db('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('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('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('c_customerinfo')->where('id','in',$ids)->update($unvalid);
                        db('c_salestrackinginfo')->insertAll($trackLog);
                        db()->commit();
                    } catch (\Exception $e) {
                        db()->rollback();
                        $this->log("系统自动标记无效失败：".$e->getMessage());
                    }
                    $count = db('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('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('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('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,$k,$v,$day,$time,$info,$kk,$vv,$ids,$listName_fp,$message_fp);
    }
    //每天自动标记所有进店未成交客资为流失 
    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('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('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('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('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('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('c_customer_intostore')->where('id',$v['id'])->update($Idata);
                }
            }
            unset($data,$res,$table,$Idata,$info,$res1,$cInfo,$k,$v);
        }
        // $this->log('<----自动标记流失次数---客资表->'.$res.' 次，进店表：'.$res1.' 次');
    }
    // 提前一天检测生日和结婚纪念日，插入表内 有问题，暂时不调用
    private function sendDayRemind(){
        $date = date('m-d',strtotime('+1 day'));
        $info = db('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){
                    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'],
                            'operation_type'=> 2,
                            'time_out'=> 43200,
                        );
                        $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'],
                            'operation_type'=> 2,
                            'time_out'=> 43200,
                        );
                        $res1 = sendSystemMessage($message);//弹窗信息
                        $this->log('<----第'.$j.'次发送结婚纪念日提醒结果---->'.$res1);
                        $j++;
                    }
                }
                cache('send_day_remind',1);
                unset($info);
            }
        }
    }
    // 处理客资表中的 超时未接收 的客资
    private function dealCustomer(){
        $time = time();
        $fpCustomerList = db('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('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('c_fp_pool')->insert($data);
                    $listName = 'fpCustomerList';
                    push_list($listName, $message);
                }
            }
            unset($fpCustomerList,$key,$value,$pool,$message,$data,$listName);
        }
        unset($time);
    }
    // 处理pool表
    private function dealPool(){
        $this->log('<----开始处理pool表---->');
        $time = time();
        $poolGroup = db('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('c_fp_pool')->where('id',$value['id'])->delete();
                }
                // $this->log('开始删除---插入录入人和追踪人小组信息--结果->'.$result);
            }
        }
        $poolList = db('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('c_customerinfo')->where('id',$value['id'])->field('is_status,is_fp')->find();
                // 客资已经删除 pool表同样删除
                if ($cInfo['is_status'] == 2) {
                    db('c_fp_pool')->where('cid', $value['id'])->where('pool_type','<>', 10)->delete();
                    continue;
                }
                // 分配
                if($value['pool_type'] == 1){
                    // 已经分配
                    if ($cInfo['is_fp'] == 1) {
                        db('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>');
                    unset($msg,$result);
                }
                // 预约进店提醒
                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'],$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('c_fp_pool')->where('id',$value['id'])->delete();
                        $this->log('信息删除结果---->'.$del);
                        db()->commit();
                    }catch (Exception $e){
                        db()->rollback();
                    }
                    unset($msg,$consulation_shop,$yjd_time,$return,$wxConfirmUrl,$content,$send_data,$res,$del);
                }
                // 进店提醒
                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('c_fp_pool')->where('id',$value['id'])->delete();
                        db()->commit();
                    }catch (Exception $e){
                        db()->rollback();
                    }
                    unset($msg,$consulation_shop,$return);
                }
                // 生日，预产期，结婚纪念日提醒
                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('c_fp_pool')->where('id',$value['id'])->delete();
                        db()->commit();
                    }catch (Exception $e){
                        db()->rollback();
                    }
                    unset($msg,$return,$content,$send_data);
                }
                //
                else if($value['pool_type'] == 55){
                    $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('c_fp_pool')->where('id',$value['id'])->delete();
                        }

                        db()->commit();
                    }catch (Exception $e){
                        db()->rollback();
                    }
                    unset($msg,$consulation_shop,$yjd_time,$wxConfirmUrl,$content,$send_data,$cus,$return,$res);
                }
                // 再约电访提醒
                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('c_fp_pool')->where('id',$value['id'])->delete();
                        $this->log('信息删除结果---->'.$del);
                        db()->commit();
                    }catch (Exception $e){
                        db()->rollback();
                    }
                    unset($msg,$next_time,$return,$wxConfirmUrl,$content,$send_data,$res,$del);
                }
                // 筛客
                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('c_customerinfo')->where('id',$cid)->value('sk_staff_id');
                        // 如果已经存在筛客人
                        if ($cInfoSk['sk_staff_id']) {
                            $this->log('已有筛客人');
                            db('c_fp_pool')->where('id',$value['id'])->delete();
                            continue;
                        }
                        $res = db('c_customerinfo')->where('id',$cid)->update($cData);
                        $this->log('SQL：'.db()->getLastSql());
                        if ($res===false) {
                            // 更新pool表
                            db('c_fp_pool')->where('id',$value['id'])->update(array('fp_time_out',time()+300));
                            $this->log('分配筛客人失败');
                            continue;
                        }else{
                            $this->log('分配筛客人成功');
                            db('c_fp_pool')->where('id',$value['id'])->delete();
                            // $this->log('SQLD：'.db()->getLastSql());
                        }
                    }else{
                        // 更新pool表
                        db('c_fp_pool')->where('id',$value['id'])->update(array('fp_time_out',time()+300));
                        // $this->log('SQLD：'.db()->getLastSql());
                    }
                    unset($cid,$sklistTemp,$sklist,$rand,$arr,$cData,$cInfoSk,$res);
                }
                else if ($value['pool_type'] == 10) {//插入录入人和追踪人小组信息
                    $this->log('开始执行---插入录入人和追踪人小组信息--->');
                    $res = $this->insertImportGroupInfo($value['msg']);
                    if($res){
                        $result= db('c_fp_pool')->where('id',$value['id'])->delete();
                    }
                    $this->log('开始删除---录入人和追踪人小组信息--结果->'.$result);
                    unset($res,$result);
                }
            }
            unset($poolList,$key,$value,$cInfo);
        }
        unset($time,$poolGroup,$res,$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 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";
        }
    }
    //电商渠道漏斗沉淀数据
    public 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('d_ds_channel_ld')->where('shop_code',$shop_code)->where('time',$last_month_begin)->value('id');
        if(empty($id)){
            db('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('s_channel')->where('FIND_IN_SET("'.$shop_code.'",share_shops)','shop_code')->order('order_sort')->select();
        $time =' 23:59:59';
        $group = 's.channel_name';
        $insert = [];
        $i = 0;
        foreach($date as $k=>$v){
            $cost = db('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('c_customerinfo')->alias('c')->join('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('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')->join('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('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')->join('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('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('l_error_log')->insert($log);
            db()->commit();
            cache('ds_channel_ld_'.$shop_code,2);
            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('l_error_log')->insert($log);
            cache('ds_channel_ld_'.$shop_code,3);
            $this->log('电商渠道漏斗数据沉淀---插入数据库失败-->'.$e->getMessage());
            return false;
        }
        unset($last_month_begin,$month,$start,$end,$date,$k,$v,$time,$i);
        unset($shop_code,$where,$id,$channel,$group,$cost,$sql,$info,$fact,$amount,$arr);
        unset($insert,$log);
    }
    //网销小组数据统计沉淀
    public 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('d_wx_group')->where('shop_code',$shop_code)->where('time',$last_month_begin)->value('id');
        if(empty($id)){
            db('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';
        //组内所有人
        $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'));
            $url = "5a18e3fa516a1";
            $res = sx_call($url,array('staff_id'=>$staffIds));
            $staffNames = [];
            if($res['code'] == 200){
                $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('l_error_log')->insert($log);
                unset($last_month_begin,$month,$start,$end,$date,$k,$v,$time);
                unset($shop_code,$log,$staff,$staffNames,$staffIds,$url,$res);
                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('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('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('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('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('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('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('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('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('l_error_log')->insert($log);
            db()->commit();
            cache('wx_group_'.$shop_code,2);
            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('l_error_log')->insert($log);
            cache('wx_group_'.$shop_code,3);
            // $this->log('网销小组数据统计--插入数据库失败'.$e->getMessage());
            return false;
        }
        unset($last_month_begin,$month,$start,$end,$date,$k,$v,$time,$i);
        unset($shop_code,$where,$id,$staff,$group,$sql,$info,$fact,$amount,$fact,$dj,$arr);
        unset($insert,$log);
    }
    //修复分配部门名，登记部门名，追踪部门名
    public function repairDepartmentname(){
        $this->log('-----------------开始修复部门名称----------------------->>>>');
        $dep = controller('crm/Customer','lib')->getDepartment();
        //所有有登记或追踪部门id但没有名字的数据
        $info = db('c_customerinfo')
            ->where('status',1)
            ->where('c_from',1)
            ->where('dj_department_id|sales_department_id','not null')
            ->where('dj_department_name|sales_department_name','null')
            ->field('id,dj_department_id,sales_department_id')
            ->select();
        $this->log('-----------------需修复的数据条数----------------------->>>>'.count($info));
        foreach($info as $k=>$v){
            $arr = [];
            if($v['dj_department_id'] && empty($v['dj_department_name'])){
                $arr['dj_department_name'] = $dep[$v['dj_department_id']]['department_name'];
            }
            if($v['sales_department_id'] && empty($v['sales_department_name'])){
                $arr['sales_department_name'] = $dep[$v['sales_department_id']]['department_name'];
            }
            db('c_customerinfo')->where('id',$v['id'])->update($arr);
            $this->log('-----------------修复id为【'.$v['id'].'】的部门信息：----------------------->>>>'.json_encode($arr));
        }
        $this->log('-----------------修复部门名称完成----------------------->>>>');
    }
}