<?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 think\Controller;
use app\common\lib\redisQueue;
class RunCustomerFp extends Controller {
    // 客资id，录入id，客资所属店shop_code
    public function run($id,$staff_id,$shop_code) {
        $this->log('----要分配的客资ID----:'.$id);
        // 获取录入人信息  如果是本人录入，分配给本人  符合某个工作类型
        $staffinfo = getStaffInfoById($staff_id);
        $workTypes = RECEIVE_WORK_TYPE;
        $this->log('----staffinfoName----:'.json_encode($staffinfo['staffname']));
        // 工作类型
        // $staffinfo = getStaffInfoById($staff_id);
        if ($staffinfo['work_type']) {
            $type = explode(',', $staffinfo['work_type']);
            array_push($type, $staffinfo['main_work_type']);
        }else{
            $type = $staffinfo['main_work_type'];
        }
        // $this->log('----type----:'.json_encode($type));
        if (is_array($type)) {
            $is_in = in_array($workTypes, $type);
        }else{
            if ($workTypes == $type) {
                $is_in = true;
            }else{
                $is_in = false;
            }
        }

        // $this->log('----is_in----:'.json_encode($is_in));
        // 数据统计用数据   // 根据客资id 获取客资详情
        $cInfo = controller("crm/Customer","lib")->getCustomerInfo($id);
        // $this->log('----当前要分配的客资信息----'.json_encode($cInfo));
        // 直接分配给提报人
        if ($is_in) {
            $this->log('----直接分配给提报人----');
            // 获取要分配的员工信息，执行分配动作 , 并发送消息
            // 分配  用数据
            $date = date('Y-m-d H:i:s');
            $data['sales_staff_id']	   = $staff_id;
            $data['sales_staff']	   = $staffinfo['staffname'];
            $data['sales_staff_number']= $staffinfo['staffnumber'];
            $data['fp_day']			   = $date;
            $data['is_fp']			   = 1;
            $data['jr_day']            = $date;

            // 进入数据统计队列
            $listName = 'historyDataList';
            $old = [
                'sales_staff_id'    => $cInfo['sales_staff_id'],
                'sales_staff'       => $cInfo['sales_staff'],
                'sales_staff_number'=> $cInfo['sales_staff_number'],
                'fp_day'            => $cInfo['fp_day'],
                'is_fp'             => $cInfo['is_fp'],
            ];
            $cinfo = [
                'id'     => $cInfo['id'],
                'dj_id'  => $cInfo['dj_staff_id'],
                'dj_day' => $cInfo['dj_day'],
                'sel_id' => $cInfo['sk_staff_id'],
                'sel_day'=> $cInfo['sk_time'],
                'jr_id'  => $staff_id,
                'jr_day' => $date,
            ];
            $messageH = array(
                'type'      => 1,
                'staff_id'  => $staff_id,
                'identity'  => 'sale',
                'cinfo'     => $cinfo,
                'old_data'  => $old,
                'new_data'  => $data,
                'controller'=> 'Customer',
                'action'    => 'addCustomer',
            );
            $fpLogData = [
                'cid'              => $cInfo['id'],
                'eid'              => $cInfo['eid'],
                'fp_model'         => 4,
                'fp_status'        => 1,
                'fp_time'          => $cInfo['fp_day'],
                'jr_time'          => $cInfo['jr_day'],
                'fp_staff_id'      => $cInfo['fp_staff_id'],
                'fp_staff_name'    => $cInfo['fp_staff'],
                'fp_shop_code'     => $cInfo['add_shop_code'],
                'fp_shop_name'     => $cInfo['add_shop_name'],
                'fp_brandclass_id' => $cInfo['brandclass_id'],
                'jr_staff_id'      => $cInfo['sales_staff_id'],
                'jr_staff_name'    => $cInfo['sales_staff'],
                'jr_shop_code'     => $cInfo['shop_code'],
                'jr_shop_name'     => $cInfo['shop_name'],
            ];
            // var_dump($fpLogData);
            // exit;
            $resLog = fpLogs($fpLogData);

            // 开启事务
            db()->startTrans();
            try {
                $data['update_time'] = date('Y-m-d H:i:s');
                db('crm_c_customerinfo')->where('id', $id)->update($data);
                // $resM = sendSystemMessage($messageD);
                // $resH = push_list($listName, $messageH);

                db()->commit();
                // $this->log('分配提报人成功：'.$id);
                return true;
            } catch (Exception $e) {
                $this->log('分配提报人保存数据库失败：'.$id);
                db()->rollback();
                return false;
            }
        }else{ // 按规则分配
            // 根据客资id 获取客资详情
            $this->log('----开始按规则分配客资----');
            $this->log('====rulesFP=====:'.$id);
            $shopCode = $shop_code;
            $cid = $id;
            // $this->log('当前客资shopcode:'.$shopCode.';CID：'.$cid);
            // $this->log('shopcode:'.$shopCode.'-----;----CID---:'.$cid);
            // 获取规则及规则下的员工集合
            // $staffs = controller("crm/Customer","lib")->getFpRuleStaffs($shopCode);
            $staffs = $this->getFpRuleStaffs($shopCode);
            // $this->log('规则及符合规则的员工集合===>'.  json_encode($staffs));
             $this->log('=====staffs=====:'.json_encode($staffs));
            foreach ($staffs as $key => $value) {
                $rid = $value['id'];
                $member= $value['member'];
                // 离线是否分配  1：分配
                // $not_online_is_fp = db_config('not_online_is_fp_'.$shop_code);
                // if ($not_online_is_fp == 1) {
                //     $member = $members;
                // }
                // else{
                //     $member = controller("crm/Customer","lib")->getMemberOnline($members);
                //     // $this->log('规则id：'.$rid.'----在线员工==>'.json_encode($member));
                // }
                // unset($members);
                // $num = count($member);
                // if ($num<=0) {
                //     continue;
                // }
                $useThisRule = false;

                // 来源渠道多选
                if($value['customer_condition'] == 'customer_channel'){
                    $channel_ids = explode(',', $value['customer_value']);
                    if ( in_array($cInfo['customer_channel_id'], $channel_ids) ) {
                        // $this->log('---- flag ----');
                        $useThisRule = true;
                    } 
                }
                // 根据 地区 省 市  分配客资
                if ( $value['customer_condition'] == 'customer_region' ) {
                    $valArr = explode(',', $value['customer_value']);
                    foreach ($valArr as $k => $v) {
                        $valArray = explode('-', $v);
                        switch ($valArray[0]) {
                            case 'region':
                                if($cInfo['customer_region_id'] == $valArray[1] ){
                                    $useThisRule = true;
                                }
                                break;
                            case 'province':
                                if($cInfo['province_id'] == $valArray[1] ){
                                    $useThisRule = true;
                                }
                                break;
                            case 'city':
                                if($cInfo['city_id'] == $valArray[1] ){
                                    $useThisRule = true;
                                }
                                break;
                            default:
                                $this->log('不支持该分配方式：'.$value['customer_value']);
                                break;
                        }
                    }
                    // $region_rull = explode('-', $value['customer_value']);
                    // if ($region_rull[0] == 'province' || $region_rull[0] == 'city') {
                    //     $value['customer_condition'] = $region_rull[0];
                    //     $value['customer_value']     = $region_rull[1];
                    // }
                }

                // 渠道深挖客资专用（^_^）
                if($value['customer_condition'] == 'add_organize'){
                    $valArr = explode(',', $value['customer_value']);
                    foreach ($valArr as $k => $v) {
                        $valArray = explode('-', $v);
                        switch ($valArray[0]) {
                            case 'shop':
                                if($cInfo['add_shop_code'] == $valArray[1] ){
                                    $useThisRule = true;
                                }
                                break;
                            case 'department':
                                if ($cInfo['customer_channel_id'] == $valArray[1] ){
                                    $useThisRule = true;
                                }
                                break;
                            case 'staff':
                                if ($cInfo['dj_staff_id'] == $valArray[1] ){
                                    $useThisRule = true;
                                }
                                break;
                            default:
                                $this->log('不支持该分配方式：'.$value['customer_value']);
                                break;
                        }
                    }

                    // $type = strtolower($valArr[0]);// shop department staff
                    // $val  = str_replace($type.'-', '', $value['customer_value']);
                    // switch ($type) {
                    //     case 'shop':
                    //         // $this->log('shop('.$cInfo['add_shop_code'].'==>'.$val.')');
                    //         if($cInfo['add_shop_code'] == $val ){
                    //             $useThisRule = true;
                    //         }
                    //         break;
                    //     case 'department':
                    //         // $this->log('department('.$cInfo['customer_channel_id'].'==>'.$val.')');
                    //         if ($cInfo['customer_channel_id'] == $val ){
                    //             $useThisRule = true;
                    //         }
                    //         break;
                    //     case 'staff':
                    //         // $this->log('staff('.$cInfo['dj_staff_id'].'==>'.$val.')');
                    //         if ($cInfo['dj_staff_id'] == $val ){
                    //             $useThisRule = true;
                    //         }
                    //         break;
                    //     default:
                    //         // $this->log('不支持该分配方式：'.$value['customer_value']);
                    //         break;
                    // }
                }

                // 分配依据，地区，来源，渠道等
                // $cusCondition = ['customer_area','customer_cource','customer_region','province','city'];
                // $cuskey = $value['customer_condition'].'_id';
                // if (in_array($value['customer_condition'], $cusCondition) && $cInfo[$cuskey] == $value['customer_value']) {
                //     $useThisRule = true;
                //     // $this->log('rule('.$value['customer_condition'].'==>'.$value['customer_value'].')');
                // }

                // 默认规则
                if ($value['customer_condition'] == "default") {
                    $useThisRule = true;
                    // $this->log('default--rule.');
                }

                if ($useThisRule) {
                    $this->log('useThisRule is true!!!'.$value['id']);
                    $this->log('-- allocationtype -- ：'.$value['allocationtype']);
                    // 条件分配
                    if ($value['allocationtype'] == 1) {
                        $param['cid']    = $cid;
                        $param['rid']    = $rid;
                        $param['member'] = $member;
                        $param['shop_code'] = $shopCode;
                        // $this->log('-- param --：'.json_encode($param));
                        $res = $this->fpCustomerT($param);
                        $this->log('------条件分配--：'.json_encode($res));
                        // $res = controller("crm/Customer","lib")->fpCustomerT($param);
                        // $res = controller("crm/Customer","lib")->fpCustomerT($cid, $rid, $member);
                        // $this->log('条件分配结果：'.json_encode($res));
                        // $this->log('规则id：'.$rid.'===>接收人:'.json_encode($res));
                        // var_dump($res);
                    }else{ // 平均分配
                        $param['cid']    = $cid;
                        $param['rid']    = $rid;
                        $param['member'] = $member;
                        $param['shop_code'] = $shopCode;
                        // $this->log('-- param --：'.json_encode($param));
                        $res = $this->fpCustomerP($param);
                        $this->log('------平均分配--：'.json_encode($res));
                        // $res = controller("crm/Customer","lib")->fpCustomerP($param);
                        // $res = controller("crm/Customer","lib")->fpCustomerP($cid, $rid, $member);
                        // $this->log('平均分配结果：'.json_encode($res));
                        // $this->log('规则id：'.$rid.'===>接收人:'.json_encode($res));
                        // var_dump($res);
                    }
                    if ($res['sales_staff_id']) {
                        $this->log('------break---分配--：');
                        break;
                    }else{
                        continue;
                    }
                }
            }
            
            // 如果存在可分配的员工
            $time = time();
            if ($res['sales_staff_id']) {
                $this->log('------开始分配动作------接收人：'.json_encode($res));
                // 获取要分配的员工信息，执行分配动作 , 并发送消息
                // 分配  用数据  mark
                $date = date('Y-m-d H:i:s');
                $data['sales_staff_id']	    = $res['sales_staff_id'];
                $data['sales_staff']		= $res['sales_staff'];
                $data['sales_staff_number'] = $res['sales_staff_number'];
                $data['fp_day']			    = $date;
                $auto_jr = db_config('auto_jr_'.$shop_code);
                $auto = db_config('fp_switch_'.$shop_code);
                if($auto_jr && $auto){
                    $data['is_fp']			    = 1;
                    $data['jr_day']             = $date;
                    // 消息  用数据  //send_type:'消息类型:1:短消息(弹窗)；2：通知',
                    $operation = [];
                }else{
                    $data['is_fp']			    = 3;
                    // 消息  用数据  //send_type:'消息类型:1:短消息(弹窗)；2：通知',
                    $operation = array(
                        [
                            'button'=>'接收',
                            'url'=>'/crm/customer/customerReceive.html?cid='.$cid.'&',
                        ],
                        [
                            'button'=>'放弃',
                            'url'=>'/crm/Customer/customerDrop.html?cid='.$cid.'&',
                        ],
                    );
                }


                $operation = json_encode($operation);
                $message['send_type']      = 1;
                $message['send_title']     = '分配提醒';
                $message['send_msg']       = '您收到一笔新客资，ID：'.$cInfo['id'].'；姓名：'.$cInfo['customer_name'].'，请查收。';
                $message['customer_id']    = $cid;
                $message['receive_id']     = $res['sales_staff_id'];
                $message['receive_name']   = $res['sales_staff'];
                $message['receive_status'] = 0;
                $message['operation_type'] = 1;
                $message['operation']      = $operation;
                // $this->log('message:'.json_encode($message));
                // include 'application/crm/common.php';
                $timeOut = db_config('fp_timeout_'.$shop_code);
                $timeOut = $timeOut ? $timeOut : 60;
                $message['time_out']       = $timeOut;
                // $this->log('timeOut:'.$timeOut);

                // 发送微信模板消息
                // 向上一级发信息  微信
                $overTime = date('Y-m-d H:i:s', ($time+$timeOut));
                $wxConfirmUrl = config('url_domain_root').'/crm/weixin/receiveCustomer/cid/'.$cid;
                $sex = $cInfo['customer_sex']?'('.$cInfo['customer_sex'].')':'';
                $content = [
                    'touser'       => $res['sales_staff_id'],
                    'template_id'  => OPENTM_FP,
                    'url'          => $wxConfirmUrl,
                    'data'         => [
                        'first'=>[
                            'value'=> '您好，您有一笔新客资啦，快去追踪吧！',
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $cInfo['customer_name'].' '.$sex.'[ID：'.$cInfo['id'].']',
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $cInfo['customer_tel'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> '系统分配',
                            'color'=> '#173177'
                        ],
                        'keyword4'=>[
                            'value'=> $overTime,
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> '请尽快接收，谢谢',
                            'color'=> '#173177'
                        ]
                    ]
                ];
                $send_data['content'] = json_encode($content);
                $remind = getRemind($cInfo['brandclass_id']);
                if(in_array('tui',$remind['auto']['send_method']) && in_array('sales',$remind['auto']['send_receive'])){
                    $resMsg = sendMsg($send_data);
                    $this->log('----发送微信模板消息:'.json_encode($resMsg));
                }

                // 分配日志
                $fpLogData = [
                    'cid'              => $cid,
                    'fp_model'         => 1,
                    'fp_status'        => 3,
                    'fp_time'          => $date,
                    'fp_staff_id'      => '0',
                    'fp_staff_name'    => 'system',
                    'fp_shop_code'     => $cInfo['add_shop_code'],
                    'fp_shop_name'     => $cInfo['add_shop_name'],
                    'fp_brandclass_id' => $cInfo['brandclass_id'],
                    'jr_staff_id'      => $res['sales_staff_id'],
                    'jr_staff_name'    => $res['sales_staff'],
                    'jr_shop_code'     => $cInfo['shop_code'],
                    'jr_shop_name'     => $cInfo['shop_name'],
                ];
                if($auto_jr && $auto){
                    $fpLogData['fp_status'] = 1;
                    $fpLogData['jr_time'] = $date;
                    $message['operation_type'] = 2;
                }
                $this->log('--- key ---'.$res['key']);
                // var_dump($fpLogData);
                // exit;

                // 开启事务
                db()->startTrans();
                try {

                    //2021-06-15 分配清除最后追踪时间：
                    if (db_config('allocation_last_tracking') == 1) {
                        $data['last_trackday'] = NULL;
                    }
                    
                    $data['fp_time_out'] = $time+$timeOut;
                    $data['update_time'] = date('Y-m-d H:i:s');
                    db('crm_c_customerinfo')->where('id', $cid)->update($data);
                    // db('crm_c_message')->insert($message);
                    if(in_array('tan',$remind['auto']['send_method']) && in_array('sales',$remind['auto']['send_receive'])){
                        $res = sendSystemMessage($message);
                        $this->log('发送消息:'.$res);
                    }

                    // 分配日志
                    $resLog = fpLogs($fpLogData);
                    db()->commit();
                    // 发消息
                    // $message['id'] = db()->getLastInsID;
                    // redisQueue::init()->publish($channel, $message);
                    // $this->log('发送消息:'.json_encode($message));
                    // $this->log('message:'.json_encode($message));
                    
                    // 根据customer_id,查c_fp_pool 如果存在，删除
                    $fpCustomer = db('crm_c_fp_pool')->where('cid', $cid)->where('pool_type', 1)->find();
                    if ($fpCustomer) {
                        $upInPool['count'] = $fpCustomer['count']+1;
                        $upInPool['fp_time_out'] = $data['fp_time_out'];
                        db('crm_c_fp_pool')->where('cid', $cid)->where('pool_type', 1)->update($upInPool);
                        $this->log('lins:'.$res);
                    }

                    // 记日志
                    $old = [
                        'sales_staff_id'    => $res['sales_staff_id'],
                        'sales_staff'       => $res['sales_staff'],
                        'sales_staff_number'=> $res['sales_staff_number'],
                        'fp_day'            => $date,
                        'is_fp'             => $fpLogData['fp_status'],
                    ];
                    history_log($data, $old, $cid, '-1', 'system','crm','Customer','fpCustomer');
                    return true;
                } catch (\Exception $e) {
                    $this->log('database-operation-error:'.json_encode($e->getTraceAsString()));
                    // $this->log('数据库操作失败:'.  json_encode($e->getTraceAsString()));
                    db()->rollback();
                    return false;
                }
                // return true;
            }else{
                $this->log('------没有可以分配的人------');
                // 根据customer_id,查c_fp_pool
                    // 如果存在，count+1，fp_time_out=(count*5*60)+time()
                    // 如果没有，insert into c_fp_pool
                    // 如果count>=10，修改状态，分配失败
                $fpCustomer = db('crm_c_fp_pool')->where('cid', $cid)->where('pool_type', 1)->find();
                // $this->log('fp_pool_sql:--->'.db()->getLastSql());
                if ($fpCustomer) {
                    $this->log('------分配池中存在该客资，cid：'.$cid);
                    if ($fpCustomer['count'] >= 10) {
                        // 分配失败
                        $upData = [
                            'is_fp'              => FP_STATUS_FALSE,
                            'sales_staff'        => null,
                            'sales_staff_id'     => null,
                            'sales_staff_number' => null,
                            'update_time'        => date('Y-m-d H:i:s')
                        ];
                        $res = db('crm_c_customerinfo')->where('id', $cid)->update($upData);
                        // $this->log('update_customerInfo:--->'.db()->getLastSql());
                        $this->log('分配重试次数超过10次，标记分配失败，更新结果:'.($res?'sucess':'false'));
                    }else{
                        $upInPool['count'] = $fpCustomer['count']+1;
                        $upInPool['fp_time_out'] = ($fpCustomer['count']*300)+$time;
                        db('crm_c_fp_pool')->where('cid', $cid)->where('pool_type', 1)->update($upInPool);
                        // $this->log('update_fp_pool:--->'.db()->getLastSql());
                        $fpCount = $fpCustomer['count'];
                        $this->log('分配失败，信息在待处理内已有此客资:'.$cid.'累计重试次数：'.$upInPool['count']);
                    }
                }else{
                    $this->log('------分配池中--不--存在该客资，cid：'.$cid);
                    // $this->log('<----insert_fp_pool---->');
                    $pool_msg =[
                        'receive'  => '-1',
                        'body'     => $cid,
                        'staff_id' => $staff_id,
                        'shop_code'=> $shop_code
                    ];
                    $inPool = [
                        'cid'         => $cid,
                        'msg'         => json_encode($pool_msg),
                        'fp_time_out' => $time+300,
                        'create_time' => date('Y-m-d H:i:s'),
                        'count'       => 1,
                        'pool_type'   => 1,
                    ];
                    $poolRes = db('crm_c_fp_pool')->insert($inPool);
                    if($poolRes){
                        $this->log('分配失败，信息存入客资待处理:'.$cid.'下次处理时间：'.date('Y-m-d H:i:s',$time+300));
                    }else{
                        $this->log('分配失败，信息存入待处表失败，失败SQL:'.db()->getLastSql());
                    }
                }
                // $this->log('分配失败，保存失败状态:'.($res?'成功':'失败' ));
                // $this->log('fp-error:'.($res?'sucess':'false'));
                return true;
            }
        }        
    }
    /**
     * 查看cache中是否存在对应规则及员工集合
     * @param  str    shop_code
     * @return array  rules 规则集合
     * @author Eric
     */
    public function getFpRuleStaffs($shop_code){
        $ruleStaffs = cache('fpRuleStaffs_'.$shop_code);
        if (!$ruleStaffs) {
            $rules  = controller("crm/Setting","lib")->getRule($shop_code);
            // echo json_encode($rules).'<br />';
            $ruleStaffs = $this->getStaffs($rules, $shop_code);
            cache('fpRuleStaffs_'.$shop_code, $ruleStaffs);
        }
        return $ruleStaffs;
    }
    /**
     * 根据规则集合，查询所有符合分配规则的员工集合
     * @param  array  rules 规则集合
     * @return array
     * @author Eric
     */
    public function getStaffs($rules, $shopCode){
        // 调mc接口
        $mc = new \app\common\lib\mcInterface();
        // $temp_staff = $mc->getAllStaffListByShopcode($param);
        foreach ($rules as $key => $value) {
            // 如果是按照 部门、职位 分配，查mc表 如果部门或者岗位为空，则查询店下所有员工
            if ($value['department_name']) {
                // $url = '5a0a624728618';
                $data = array(
                    'department_id'=>$value['department_id'],
                    'shop_code'    =>$shopCode
                );
                // $res = sx_call($url, $data);
                // if ($res['code'] == 200) {
                //     $staff = $res['data'];
                // }
                $res = $mc->getStaffInfoForFp($data);
                if ($res !== false) {
                    $staff = $res;
                }else{
                    $staff = [];
                }
                // echo '1';
                // var_dump($staff);
            }
            else if ($value['position_name']) {
                // $url = '5a0a624728618';
                $data = array(
                    'position_id'=>$value['position_id'],
                    'shop_code'  =>$shopCode
                );
                // $res = sx_call($url, $data);
                $res = $mc->getStaffInfoForFp($data);
                if ($res !== false) {
                    $staff = $res;
                }else{
                    $staff = [];
                }
                // echo '2';
                // var_dump($staff);
            }
            // exit;
            // 如果按照 小组 分配，查crm表
            else if ($value['group_name']) {
                $staff = controller("crm/Statistics","lib")->getStaffs($value['group_id']);
                // echo '3';
                // var_dump($staff);
            }else if ($value['staff_type']) {
                switch ($value['staff_type']) {
                    case 'department_name':
                        $temp = json_decode($value['staff_value'], true);
                        $did  = $temp[0]['department_id'];
                        // $url  = '5a0a624728618';
                        $data = array(
                            // 'department_id'=>$value['department_id'],
                            'department_id'=>$did,
                            'shop_code'    =>$shopCode
                        );
                        // $res = sx_call($url, $data);
                        $res = $mc->getStaffInfoForFp($data);
                        if ($res !== false) {
                            $staff = $res;
                        }else{
                            $staff = [];
                        }
                        break;
                    case 'position_name':
                        $temp = json_decode($value['staff_value'], true);
                        $pid  = $temp[0]['position_id'];
                        // $url  = '5a0a624728618';
                        $data = array(
                            // 'position_id'=>$value['position_id'],
                            'position_id'=>$pid,
                            'shop_code'  =>$shopCode
                        );
                        // $res = sx_call($url, $data);
                        $res = $mc->getStaffInfoForFp($data);
                        if ($res !== false) {
                            $staff = $res;
                        }else{
                            $staff = [];
                        }
                        break;
                    case 'group_name':
                        $temp = json_decode($value['staff_value'], true);
                        $gid  = $temp[0]['group_id'];
                        $staff= controller("crm/Statistics","lib")->getStaffs($gid);
                        break;
                    case 'staff_name':
                        $temp = json_decode($value['staff_value'], true);
                        $staff = [];
                        foreach ($temp as $k => $val) {
                            $staff[$k]['id'] = $val['staff_id'];
                            $staff[$k]['staffname'] = $val['staff_name'];
                            $saInfo = getStaffInfoById($val['staff_id']);
                            $staff[$k]['staffnumber'] = $saInfo['staffnumber'];
                        }
                        break;
                }
            }
            // exit;
            // 分配方式 传递
            $atype = $value['allocationtype'];
            $atypev= $value['allocationtype_value'];
            $atime = $value['active_time'];

            // 分配方式
            $staffs[$key]['allocationtype'] = $value['allocationtype'];
            $staffs[$key]['allocationtype_value'] = $value['allocationtype_value'];

            // 客资筛选方式
            $staffs[$key]['customer_condition'] = $value['customer_condition'];
            $staffs[$key]['customer_value'] = $value['customer_value'];

            // 规则id
            $staffs[$key]['id'] = $value['id'];
            // 员工
            $staffs[$key]['member'] = $this->getMembers($staff, $atype, $atypev, $atime);
        }
        $staffsJ = json_encode($staffs);
        return $staffs;
    }
    public function getMembers($staff, $atype, $atypev,$atime){
        // 按条件分配
        if ($atype==1) {
            // 根据分配规则排序员工  LT：录入；YT：标记有效；DT：有效成单数
            $target = new Target();
            $targetList = $target->getAllTarget();
            if(!key_exists($atypev, $targetList)){
                return $staff;
            }
            $targetMethod = $targetList[$atypev]['method'];
            $day = getdateArea($atime);
            foreach ($staff as $k => $v) {
                $condition = [
                    'staff_id'  => $v['id'],
                    'start_day' => $day[0],
                    'end_day'   => $day[1],
                ];
                $staff[$k]['rate'] = $target->$targetMethod($condition);
            }

            $staff = my_sort($staff, 'rate', 'SORT_DESC');
            return $staff;
        }else{ // 平均分配
            $staff = my_sort($staff, 'id');
        }
        return $staff;
    }
    // 按条件（T）分配客资 （极限）
    public function fpCustomerT($param){
        $this->log('------条件分配开始--：'.json_encode($param));
        $cid    = $param['cid'];
        $rid    = $param['rid'];
        $staffs = $param['member'];
        // 找出员工列表中不忙的
        $saleId = '';
        $temp   = '';
        $newStaff = [];
        foreach ($staffs as $key => $value) {
            // 店面设定 -- 离线是否分配  1：分配
            $not_online_is_fp = db_config('not_online_is_fp_'.$param['shop_code']);
            // 员工设定 -- 离线是否分配  1：分配
            //$salf_not_online_is_fp = db_config('not_online_is_fp_'.$value['id']);
            //$this->log($not_online_is_fp.'------条件分配---离线--：'.$salf_not_online_is_fp);
            if ($not_online_is_fp != 1) {
                // 员工是否在线
                $connect = $this->getStaffOnlineStatus($value['id'],$param['shop_code']);
            }
            
            if (!$connect) {
                continue;
            }
            $newStaff[$key] = $value;

            // 查找处理中的客资数量
            $where = array(
                'sales_staff_id'=> $value['id'],
                'c_end_day'     => null
            );
            $count = db('crm_c_customerinfo')->where($where)->count();
            $newStaff[$key]['count'] = $count;
        }
        $newStaff = my_sort($newStaff, 'count');
        $staff = array_shift($newStaff);

        $sales_staff['sales_staff_id']     = $staff['id'];
        $sales_staff['sales_staff']        = $staff['staffname'];
        $sales_staff['sales_staff_number'] = $staff['staffnumber'];
        return $sales_staff;
    }
    // 按条件（T）分配客资 （顺序）
    public function fpCustomerTS($param){
        # code...
    }
    // 平均（P）分配客资 customerID, ruleID, 员工集合
    public function fpCustomerP($param){
        $this->log('------平均分配开始--：'.json_encode($param));
        $cid    = $param['cid'];
        $rid    = $param['rid'];
        $staffs = $param['member'];
        // 当前应该分配的key值
        $key = cache('fpCustomerP'.$rid);
        // 如果key存在
        $num = count($staffs);
        if (!$key || $key >= $num) {
            $key = 0;
        }
        // 店面设定 -- 离线是否分配  1：分配
        $not_online_is_fp = db_config('not_online_is_fp_'.$param['shop_code']);
        // 员工设定 -- 离线是否分配  1：分配
        // $salf_not_online_is_fp = db_config('not_online_is_fp_'.$rid);
        // $this->log($not_online_is_fp.'------平均分配---离线--：'.$salf_not_online_is_fp);
        if ($not_online_is_fp != 1) {
            $res = $this->getStaffOnlineStatus($staffs[$key]['id'],$param['shop_code']);
        }
        
        if (!$res) {
            $sta = false;
            foreach ($staffs as $k => $v) {
                if ($key != 0 && $k <= $key) {
                    continue;
                }
                
                $is_online = $this->getStaffOnlineStatus($v['id'],$param['shop_code']);
                $salf_not_online_is_fp = db_config('not_online_is_fp_'.$v['id']);
                if ($is_online || $salf_not_online_is_fp) {
                    $sales_staff = [
                        'sales_staff_id'    => $v['id'],
                        'sales_staff'       => $v['staffname'],
                        'sales_staff_number'=> $v['staffnumber'],
                        'key'               => $k,
                    ];
                    $key = $k;
                    $sta = true;
                    break;
                }
            }
            // 上一次循环如果没有找到分配的人，那么重新循环一次
            if ($sta === false) {
                foreach ($staffs as $k => $v) {
                    $is_online = $this->getStaffOnlineStatus($v['id'],$param['shop_code']);
                    if ($is_online) {
                        $sales_staff = [
                            'sales_staff_id'    => $v['id'],
                            'sales_staff'       => $v['staffname'],
                            'sales_staff_number'=> $v['staffnumber'],
                            'key'               => $k,
                        ];
                        $key = $k;
                        $sta = true;
                        break;
                    }
                }
            }
        }else{
            $sales_staff = [
                'sales_staff_id'    => $staffs[$key]['id'],
                'sales_staff'       => $staffs[$key]['staffname'],
                'sales_staff_number'=> $staffs[$key]['staffnumber'],
                'key'               => $key,
            ];
        }
       
        $next = $key+1;
        cache('fpCustomerP'.$rid, $next);
        // cache('fpCustomerP-num-'.$rid, $num);
        return $sales_staff;
    }
    // 检查员工是否在线
    public function getStaffOnlineStatus($staff_id,$shop_code){
        $info = cache('staffInfo_'.$staff_id);
        $auto_jr = db_config('auto_jr_'.$shop_code);
        if ($auto_jr) {
            $this->log('--- 自动接收 --- '.$staff_id.' -- '.$info['staffname']);
            return true;
        }
        if( (time() - $info['active'] > 60) || ($info['status'] != 1) ){
            $this->log('--- 不在线 --- '.$staff_id.' -- '.$info['staffname'].' -- '.$info['status'].' -- '.date('Y-m-d H:i:s', strtotime($info['active'])) );
            return false;
        }else{
            return true;
        }
    }
    // 获取 店面 设定的 接收超时时间 Eric
    public function getShopTimeout(){
        $key = 'fp_timeout_'.session('shop_code');
        $timeOut = cache($key);
        if (!$timeOut) {
            $res = db('crm_c_sysconfig')->where('ckey', $key)->find();
            $timeOut = $res['cvalue'];
            cache($key, $timeOut);
        }
        return $timeOut;
    }

    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";
        }
    }

}  