<?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);
        // die;
        // 获取录入人信息  如果是本人录入，分配给本人  符合某个工作类型
        $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);
        if ($cInfo['is_fp']==1 && $cInfo['sales_staff']) {
            $this->log('该客资已经存在追踪人：'.$cInfo['sales_staff']);
            return true;
        }
        
        // $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'] ? $staffinfo['staffname'] : $staffinfo['staff_name'];
            $data['sales_staff_number']= $staffinfo['staffnumber'] ? $staffinfo['staffnumber'] : $staffinfo['staff_number'];
            $data['sales_department_id']= $staffinfo['department_id'];
            $data['sales_department_name']= $staffinfo['department_name'];
            $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('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['sales_department_id']= $this->getStaffDepartment(array('staff_id'=>$res['sales_staff_id'], 'shop_code'=>$shop_code));
                $data['sales_department_name']= $this->getStaffDepartmentname(array('staff_id'=>$res['sales_staff_id'], 'shop_code'=>$shop_code));
                $data['fp_day']			    = $date;

                $gInfo = getGroupInfo($res['sales_staff_id']);
                if ($gInfo) {
                    $fData['sales_group_id']= $gInfo['id'];
                    $fData['sales_group_name']= $gInfo['group_name'];
                }
                
                $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 = [];
                    $message['read_status'] = 1;
                    $message['read_time'] = date('Y-m-d H:i:s',time());
                    $wxConfirmUrl = config('app_host').'/crm/weixin/receiveCustomerDetail/cid/'.$cid;
                }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.'&',
                        ],
                    );
                    $wxConfirmUrl = config('app_host').'/crm/weixin/receiveCustomer/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));
                $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'].'/ 微信：'.$cInfo['customer_wechat'],
                            '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 {
                    $data['fp_time_out'] = $time+$timeOut;
                    $data['update_time'] = date('Y-m-d H:i:s');
                    // $this->log('--- fpData ---'.json_encode($data));
                    $fpres = db('c_customerinfo')->where('id', $cid)->update($data);
                    $this->log('--- fpres ---'.$fpres.'====SQL:'.db()->getLastSql());
                    if ($fData) {
                        db('c_customer_from')->where('cid', $cid)->update($fData);
                    }
                    // db('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));
                    
                    // 如果自动接收 删除pool表，否则pool中的count+1
                    $fpCustomer = db('c_fp_pool')->where('cid', $cid)->where('pool_type', 1)->find();
                    if ($auto_jr) {
                        if ($fpCustomer) {
                            db('c_fp_pool')->where('cid', $cid)->where('pool_type', 1)->delete();
                        }
                    }else{
                        if ($fpCustomer) {
                            $upInPool['count'] = $fpCustomer['count']+1;
                            $upInPool['fp_time_out'] = $data['fp_time_out'];
                            db('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('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('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('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('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 />';
            $this->log('==rules:'.json_encode($rules));
            $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接口
        foreach ($rules as $key => $value) {
            $this->log('==rules-value:'.json_encode($value));

            // 分配方式
            $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'];

            // 如果是按照 部门、职位 分配，查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'];
                }
                // 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);
                if ($res['code'] == 200) {
                    $staff = $res['data'];
                }
                // echo '2';
                // var_dump($staff);
            }
            // exit;
            // 如果按照 小组 分配，查crm表
            else if ($value['group_name']) {
                $this->log('in group_name:'.json_encode($value));
                $staff = controller("crm/Statistics","lib")->getStaffs($value['group_id']);
                // echo '3';
                // var_dump($staff);
                $this->log('group staffs:'.json_encode($staff));
            }else if ($value['staff_type']) {
                // $this->log('in staff_type:'.json_encode($value['staff_type']));
                $fpColumn = isColumnExist(array('table'=>'s_allocation_rule', 'column'=>'fp_staffs'));
                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);
                        if ($res['code'] == 200) {
                            $staff = $res['data'];
                        }
                        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);
                        if ($res['code'] == 200) {
                            $staff = $res['data'];
                        }
                        break;
                    case 'group_name':
                        // $temp = json_decode($value['staff_value'], true);
                        // $gid  = '';
                        // foreach ($temp as $key => $value) {
                        //     $gid .= $value['group_id'].',';
                        // }
                        // $gid = trim($gid,',');
                        // $staffs= controller("crm/Setting","lib")->getGroupStaff($gid);
                        // if ($value['fp_staffs']) {
                        //     $temp1 = json_decode($value['fp_staffs'], true);
                        // }
                        // foreach ($staffs as $key => $value) {
                        //     if ($temp1) {
                        //         foreach ($temp1 as $k => $v) {
                        //             if ($value['staff_id']==$v['staff_id']) {
                        //                 $staff[$key]['sort'] = $v['sort'];
                        //                 $staff[$key]['max']  = $v['staff_max'];
                        //                 $staff[$key]['id']   = $value['staff_id'];
                        //                 $staff[$key]['staffname'] = $value['staff_name'];
                        //                 $saInfo = getStaffInfoById($value['staff_id']);
                        //                 $staff[$key]['staffnumber'] = $saInfo['staffnumber'] ? $saInfo['staffnumber'] : $saInfo['staff_number'];
                        //                 continue;
                        //             }
                        //         }
                        //     }else{
                        //         $staff[$key]['id'] = $value['staff_id'];
                        //         $staff[$key]['staffname'] = $value['staff_name'];
                        //         $saInfo = getStaffInfoById($value['staff_id']);
                        //         $staff[$key]['staffnumber'] = $saInfo['staffnumber'] ? $saInfo['staffnumber'] : $saInfo['staff_number'];
                        //     }
                        // }
                        $this->log('in group_name:'.json_encode($value));
                        $staff = $this->getGroupStaffs($value['staff_value'],$value['fp_staffs']);
                        $this->log('==group_staffs:'.json_encode($staff));
                        break;
                    case 'staff_name':
                        $temp = json_decode($value['staff_value'], true);
                        // 天长专用
                        // $temp = json_decode($value['staff_value1'], true);
                        if ($value['fp_staffs']) {
                            $temp1 = json_decode($value['fp_staffs'], true);
                        }
                        $staff = [];
                        foreach ($temp as $ke => $val) {
                            // $staff[$k]['id'] = $val['staff_id'];
                            // $staff[$k]['staffname'] = $val['staff_name'];
                            // $saInfo = getStaffInfoById($val['staff_id']);
                            // $staff[$k]['staffnumber'] = $saInfo['staffnumber'] ? $saInfo['staffnumber'] : $saInfo['staff_number'];

                            if ($temp1) {
                                foreach ($temp1 as $k => $v) {
                                    if ($val['staff_id']==$v['staff_id']) {
                                        $staff[$key]['sort'] = $v['sort'];
                                        $staff[$key]['max']  = $v['staff_max'];
                                        $staff[$key]['id']   = $val['staff_id'];
                                        $staff[$key]['staffname'] = $val['staff_name'];
                                        $saInfo = getStaffInfoById($val['staff_id']);
                                        $staff[$key]['staffnumber'] = $saInfo['staffnumber'] ? $saInfo['staffnumber'] : $saInfo['staff_number'];
                                        continue;
                                    }
                                }
                            }else{
                                $staff[$key]['id'] = $val['staff_id'];
                                $staff[$key]['staffname'] = $val['staff_name'];
                                $saInfo = getStaffInfoById($val['staff_id']);
                                $staff[$key]['staffnumber'] = $saInfo['staffnumber'] ? $saInfo['staffnumber'] : $saInfo['staff_number'];
                            }

                        }
                        break;
                }
            }
            // exit;
            // 分配方式 传递
            $atype = $value['allocationtype'];
            $atypev= $value['allocationtype_value'];
            $atime = $value['active_time'];

            // 员工
            $staffs[$key]['member'] = $this->getMembers($staff, $atype, $atypev, $atime);
        }
        $staffsJ = json_encode($staffs);
        $this->log('===members===>:'.json_encode($staffsJ));
        return $staffs;
    }
    // 根据人员排序，
    public function getMembers($staff, $atype, $atypev,$atime){
        $this->log('===atype===>:'.$atype);
        // 按照默认顺序分配
        if ($atype==0) {
            return $staff;
        }
        // 按照业绩顺序分配
        else 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 if ($atype==2) {
            $sids = '';
            foreach ($staff as $key => $value) {
                $sids .= $value['id'].',';
            }
            $loginInfo = db('l_login_log')->where('staff_id',$sids)->where('last_login_time','between',[])->group('staff_id')->column('last_login_time','staff_id');

            foreach ($staff as $key => $value) {
                $staff[$key]['last_login_time'] = $loginInfo[$value['id']];
            }
            $staff = my_sort($staff, 'last_login_time', 'SORT_DESC');
            return $staff;
        }
    }
    public function getMembersOld($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');
            $staff = $staff;
        }
        return $staff;
    }
    // 平均（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);
        $this->log('------平均分配排序1--：'.$key);
        // 如果key存在
        $num = count($staffs);
        $this->log('------平均分配排序num--：'.$num);
        if (!$key || $key >= $num) {
            $key = 0;
        }
        $this->log('------平均分配排序1-1--：'.$key);
        // 店面设定 -- 离线是否分配  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'],$staffs[$key]['max']);
        // }
        // $this->log('------平均分配排序2--：'.$key);
        // if (!$res && $not_online_is_fp != 1) {
            $sta = false;
            $this->log('----循环所有员工----：'.$key);
			$this->log('----所有员工----：'.json_encode($staffs));
            foreach ($staffs as $k => $v) {
				
                if ($key != 0 && $k < $key) {
                    continue;
                }
                
                $is_online = $this->getStaffOnlineStatus($v['id'],$v['max'],$not_online_is_fp);
                $this->log('------检测在线--：'.$v['id'].'==>'.$is_online);
                $salf_not_online_is_fp = db_config('not_online_is_fp_'.$v['id']);
                $this->log('------手机离线接收--：'.$v['id'].'==>'.$salf_not_online_is_fp);
                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'],$v['max'],$not_online_is_fp);
                    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,
        //     ];
        // }
        // $this->log('------平均分配排序3--：'.$key);
        $next = $key+1;
        // $this->log('------平均分配排序4--：'.$key);
        cache('fpCustomerP'.$rid, $next);
        // cache('fpCustomerP-num-'.$rid, $num);
        return $sales_staff;
    }
    // 检查员工是否在线 同时检测分配的数量
    public function getStaffOnlineStatus($staff_id,$max,$not_online_is_fp){
        // $info = cache('staffInfo_'.$staff_id);
        if(!empty(cache('staffInfo_'.$staff_id))) {
            $info = cache('staffInfo_'.$staff_id);
        }else{
            $info = getStaffInfoById($staff_id);
        }
        // 店面设定 -- 离线是否分配  1：分配
        
		$this->log('====>是否离线分配：'.$not_online_is_fp.'；员工id：'.$staff_id);
        
        $this->log('--- 在线/离线分配 --- '.$staff_id.' -- '.$info['staffname'].' -- '.$info['status'].' -- '.date('Y-m-d H:i:s', $info['active']) );
        $this->log('分配上限：'.$max);
        
        // 如果max=0 则不分配

        if($max === '' || $max > 0){
            if ($not_online_is_fp===1) {

                // 自动分配，且已接收和待接收的客资量
                $whereCountFp['l.jr_staff_id'] = $staff_id;
                $whereCountFp['l.fp_model'] = 1;
                $whereCountFp['c.is_status'] = 1;
                $whereCountFp['l.fp_status'] = ['in','1,3'];
                $whereCountFp['l.jr_time'] = ['like',date('Y-m-d').'%'];
                $count = db('l_fp_logs')->alias('l')->join('c_customerinfo c','c.id=l.cid','left')->where($whereCountFp)->count();
                $this->log('接收客资数量：'.$count.'；SQL：'.db()->getLastSql());
                if ($max==='') {
                    return true;
                }else{
                    if ($count>=$max) {
                        return false;
                    }else{
                        return true;
                    }
                }
            }else{
                if( (time() - $info['active'] > 160) || ($info['status'] != 1) ){
                    $this->log('--- 不在线 --- '.$staff_id.' -- '.$info['staffname'].' -- '.$info['status'].' -- '.date('Y-m-d H:i:s', $info['active']) );
                    return false;
                }
            }
        }else{
            return false;
        }

        return true;
    }
    // 获取 店面 设定的 接收超时时间 Eric
    public function getShopTimeout(){
        $key = 'fp_timeout_'.session('shop_code');
        $timeOut = cache($key);
        if (!$timeOut) {
            $res = db('c_sysconfig')->where('ckey', $key)->find();
            $timeOut = $res['cvalue'];
            cache($key, $timeOut);
        }
        return $timeOut;
    }
    // 根据staff_id，shop_code 获取这个人在这个店下的部门
    public function getStaffDepartment($params){
        // $this->log('----参数----'.json_encode($params));
        $mc = new \app\common\lib\mcInterface();
        // $this->getStaffDepartment(array('staff_id'=>$res['sales_staff_id'], 'shop_code'=>$shop_code));
        $staffInfo = $mc->getStaffInfo(array('id' =>$params['staff_id']));
        // $this->log('----接收人----'.json_encode($staffInfo));
        $positions = $staffInfo[0]['main_position_code'].','.$staffInfo[0]['position_code'];
        $positionInfo = $mc->getPosition(array('position_code'=>$positions));
        // $this->log('----岗位信息----'.json_encode($positionInfo));
        $department_id = '';
        foreach ($positionInfo as $key => $value) {
            if ($value['shop_code'] == $params['shop_code']) {
                $department_id = $value['department_id'];
                break;
            }
        }
        $this->log('----部门id----'.$department_id);
        return $department_id;
    }
    // 根据staff_id，shop_code 获取这个人在这个店下的部门名
    public function getStaffDepartmentname($params){
        // $this->log('----参数----'.json_encode($params));
        $mc = new \app\common\lib\mcInterface();
        // $this->getStaffDepartment(array('staff_id'=>$res['sales_staff_id'], 'shop_code'=>$shop_code));
        $staffInfo = $mc->getStaffInfo(array('id' =>$params['staff_id']));
        // $this->log('----接收人----'.json_encode($staffInfo));
        $positions = $staffInfo[0]['main_position_code'].','.$staffInfo[0]['position_code'];
        $positionInfo = $mc->getPosition(array('position_code'=>$positions));
        // $this->log('----岗位信息----'.json_encode($positionInfo));
        $department_name = '';
        foreach ($positionInfo as $key => $value) {
            if ($value['shop_code'] == $params['shop_code']) {
                $department_name = $value['department_name'];
                break;
            }
        }
        $this->log('----部门name----'.$department_name);
        return $department_name;
    }
    // 按条件（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'],$value['max']);
            }
            
            if (!$connect) {
                continue;
            }
            $newStaff[$key] = $value;

            // 查找处理中的客资数量
            $where = array(
                'sales_staff_id'=> $value['id'],
                'c_end_day'     => null
            );
            $count = db('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...
    }
    // 根据规则ID 组ID获取人员
    public function getGroupStaffs($gInfo,$sInfo){
        $groupinfo = json_decode($gInfo,true);
        $staffinfo = json_decode($sInfo,true);
        $gids = array_column($groupinfo,'group_id');
        $staffids = array_column($staffinfo,'staff_id');
        $this->log('==》group_staff：'.json_encode($gids));
        $groups = db('c_staff_group')->alias('g')->join('c_staff_group_relation r','r.group_id=g.id','left')
            ->where('g.id','in',$gids)
            ->column('r.staff_id,r.staff_name','r.staff_id');
        $this->log('==》group_Sql：'.db()->getLastSql());
		/*
        foreach ($groups as $key => $value) {
            if (!in_array($value['staff_id'],$staffids)) {
                $temp['staff_id'] = $value['staff_id'];
                $temp['staff_name'] = $value['staff_name'];
                $temp['staff_max'] = '';
                $temp['sort'] = '';
                array_push($staffinfo, $temp);
            }
        }*/
        $return = [];
        $sort = 0;
		$this->log('==》groupSta：'.json_encode($staffinfo));
		// return $staffinfo;
        foreach ($staffinfo as $key => $value) {
            $return[$key]['id'] = $value['staff_id'];
            $return[$key]['staffname'] = $value['staff_name'];
            $return[$key]['max'] = $value['staff_max'];
            if ($value['sort']<>'') {
                $sort = $value['sort'];
                $return[$key]['sort'] = $value['sort'];
            }else{
                $return[$key]['sort'] = $sort+1;
            }
        }
        $return = my_sort($return, 'sort');
        // $this->log('==》group_staff：'.json_encode($return));
        return $return;
    }
    public function log($str){
        // textlog($str,'fpLogs.log','run'.DS.'fp');
        /*
        $logPath = ROOT_PATH.'runtime'.DS.'run'.DS.date('Ym');
        if(!file_exists($logPath)){
            mkdir($logPath);
        }*/
        
        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";
        }
    }

}  