<?php
/**
 * app用接口
 * User: sx01
 * Date: 2018/12/14
 * Time: 19:01
 */

namespace app\index\controller;
use think\Controller;
use app\crm\lib\Target;
use app\common\lib\mcInterface;
class App extends Controller
{
    protected $token = '';
    protected $staff_id = 0;
    protected $staff_name = '';
    protected $data = '';
    protected $module = '';
    protected $controller = '';
    protected $action = '';
    protected $api_start_time = 0;
    protected $result_code = 0;
    protected $customer_id = 0;
    public function _initialize()
    {
        $data = input();
        $this->token = $data['token'];
        $this->staff_id = $data['staff_id'];
        $this->staff_name = $data['staff_name'];
        $info = checkAppLogin($this->staff_id,$this->token);
        $this->data = $data;
        $this->module = request()->module();
        $this->controller = request()->controller();
        $this->action = request()->action();
        $this->customer_id = $data['customer_id'] ? $data['customer_id'] : 0;
        $this->api_start_time = microtime(true);
        if(empty($info)){
            $info = json_encode(array('code'=>99,'msg'=>'token验证失败','token'=>$this->token,'info'=>$info,'session'=>$_SESSION));
            response($info)->contentType('json')->send();
            die;
        }else{
        /*
         * 第一步：通过token去MC取用户信息
         * 第二部：通过MC返回值置session信息
         * 第三步：判断有没有传position_code，如果传了，调用：changeMyPosition($position_code))方法  切换岗位
         */
            //置session信息
            if(empty($info['staffname'])){
                $info['staffname'] = $info['staff_name'];
            }
            if(empty($info['staffnumberr'])){
                $info['staffnumber'] = $info['staff_number'];
            }
            $res = controller('crm/Customer','lib')->setLoginEnv($info,'app','token');
            // $info = json_encode(array('code'=>99,'msg'=>'session环境','res'=>$res,'info'=>$info,'session'=>$_SESSION));
            // response($info)->contentType('json')->send();
            // die;
            if($data['main_position_code'] != $info['main_position_code']){
                changeMyPosition($data['main_position_code']);
            }
        }

    }
    /*
     * 所有操作的返回值，并记录日志
     * */
    public function appApiLog(){
        $log['hash'] = $this->module.'/'.$this->controller.'/'.$this->action;
        $log['api_url'] = $this->module.'/'.$this->controller.'/'.$this->action;
        $log['result_code'] = $this->result_code;
        $log['api_start_time'] = $this->api_start_time;
        $log['api_end_time'] = microtime(true);
        $log['data'] = json_encode($this->data);
        $log['create_time'] = date('Y-m-d H:i:s');
        $log['create_ip'] = get_client_ip();

        try{
            db('api_logs','db_logs')->insert($log);
        }catch (\Exception $e){
            \think\Log::error('接口日志保存错误:module:'.$this->module.';controller:'.$this->controller.';action:'.$this->action.';data:'.json_encode($this->data).";error:".$e->getMessage());
        }
    }
    /*
     * index
     * app首页
     *  staff_id       人员id
     *  main_position_code 主岗位code
     *  shop_code     店面编码
     * */
    public function index(){
        $param = input();
        if(empty($param['staff_id'])){
            return json_encode(array('code'=>100,'msg'=>'未获取到员工ID'));
        }
        //根据主岗位获取显示内容
        $res = db('s_home_show')->where('shop_code',$param['shop_code'])->where('position_code',$param['main_position_code'])->find();
        $info = getStaffInfoById($param['staff_id']);

        if(empty($res)){
            $res['position_id'] = $info['main_position_id'];
            $res['position_name'] = $info['main_position_name'];
            $res['position_code'] = $info['main_position_code'];
            $res['shop_code'] = $info['shop_code'];
            $res['shop_name'] = $info['shop_name'];
            $res['department_id'] = $info['department_id'];
            $res['department_name'] = $info['department_name'];
        }
        if(empty($res['content'])){
            $res['content'] = '毛客资,有效客资,有效率';
        }

        $content = explode(',',$res['content']);
        $content_new = [];
        foreach($content as $k=>$v){
            if(strpos($v, '率') !== false ){
                $content_new[$v] = '0%';
            }else{
                $content_new[$v] = 0;
            }
        }
        if(empty($res['time'])){
            $res['time'] = 'today,yestoday,this_week';
        }
        $time = explode(',',$res['time']);

        $time_new = [];
        foreach($time as $k=>$v) {
            if ($v == 'today') {
                $time_new[$v] = '今天';
            } elseif ($v == 'yestoday') {
                $time_new[$v] = '昨天';
            } elseif ($v == 'this_week') {
                $time_new[$v] = '本周';
            } elseif ($v == 'last_week') {
                $time_new[$v] = '上周';
            } elseif ($v == 'this_month') {
                $time_new[$v] = '本月';
            } elseif ($v == 'last_month') {
                $time_new[$v] = '上月';
            }
        }
        $res['content'] = $content_new;
        $res['time'] = $time_new;
        $res['version'] = APP_VERSION;
        return json(array('code'=>200,'data'=>$res));
    }
    /**
     * 岗位查询 
     * 
     * @param  position_code  岗位code(支持多个code，用用英文逗号分隔)
     * 
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getPosition($params){

        $mc = new \app\common\lib\mcInterface();
        $positions = $mc->getPosition(['position_code'=>$params['position_code']]);
        if ($positions===false) {
            $positions = [];
        }
        return json(array('code'=>200,'data'=>$positions));
    }
    /*
     * getHomeShow
     * 获取客资简析
     *  staff_id       人员id
     *  main_position_code 主岗位code
     *  shop_code     店面编码
     *  time   today,yestoday,this_week,last_week,this_month,last_month
     * */
    public function getHomeShow(){
        $param = input();
        if(empty($param['staff_id'])){
            return json_encode(array('code'=>100,'msg'=>'未获取到员工ID'));
        }

        $info['data'] = [
            'staff_id' => $param['staff_id'],
            'department_id' => session('department_id'),
            'staffname' => session('staff_name'),
            'shop_code' => session('shop_code'),
            'main_position_code' => session('main_position_code'),
        ];

        $staffId = $param['staff_id'];
        if(check_right('menu1512637269')) {//查看所有客资权限
            $staff_id =  controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>session('shop_code')]);
            $staff_id = array_column($staff_id,'id');
            $staffId = implode(',',$staff_id);
        }elseif(check_right('menu1531471639')){//查看部门客资权限
            $staff_id = controller('crm/Customer')->getDepartmentStaffs(session('department_id'));
            $staff_id = array_column($staff_id,'id');
            $staffId = implode(',',$staff_id);
        }elseif(check_right('menu1529653231')) {//查看小组客资权限
            $staff_id = getGroupStaffByStaffId($param['staff_id']);
            $staff_id = array_column($staff_id,'staff_id');
            $staffId = implode(',',$staff_id);
        }

        //根据主岗位获取显示内容
        $res = db('s_home_show')->where('shop_code',$info['data']['shop_code'])->where('position_code',$info['data']['main_position_code'])->find();
        if(empty($res['content'])){
            $res['content'] = '毛客资,有效客资,有效率';
        }
        if(empty($res['time'])){
            $res['time'] = 'today,yestoday,this_week';
        }
        $content = explode(',',$res['content']);
        $where = '';
        if ($param['time'] == 'this_month') {
            $where = 'month';
        } elseif ($param['time'] == 'last_month') {
            $where = 'last month';
        } elseif ($param['time'] == 'this_week') {
            $where = 'week';
        } elseif ($param['time'] == 'last_week') {
            $where = 'last week';
        } elseif ($param['time'] == 'today') {
            $where = 'today';
        } elseif ($param['time'] == 'yestoday') {
            $where = 'yestoday';
        }
        $tar = new Target();
        //时间
        $day = getdateArea($where);

        $arr = array(
            'start_day' => $day[0],
            'end_day' => $day[1],
            'staff_id' => $staffId,
            'department_id' => $info['data']['department_id'] ? $info['data']['department_id'] : $info['department_id'],
            'shop_code' => $info['data']['shop_code'] ? $info['data']['shop_code'] : $info['shop_code'],
        );
        $return = [];
        foreach($content as $k=>$v){
            if($v == '花费'){
                $cost = $tar->cost($arr);;
                $return[$v] = ceil($cost);
            }
            if($v == '毛客资'){
                $mkz = $tar->newCustomerNum($arr);
                $return[$v] = ceil($mkz);
            }
            if($v == '有效客资'){
                $validCRM = $tar->validCustomerNumber($arr);
                $return[$v] = $validCRM;
            }
            if($v == '有效客资(登记时间)'){
                $validDJ = $tar->validCustomerNumberDJ($arr);
                $return[$v] = $validDJ;
            }
            if($v == '有效新单'){
                $validOrder = $tar->orderNumber($arr);
                $return[$v] = $validOrder;
            }
            if($v == '总订单(订单开始时间)'){
                $order = $tar->orderNumberStart($arr);
                $return[$v] = $order;
            }
            if($v == '总订单(登记时间)'){
                $order_dj = $tar->orderNumberByDJday($arr);
                $return[$v] = $order_dj;
            }
            if($v == '毛客资成本'){
                $all_cost = $tar->ObtainCost($arr);
                $return[$v] = sprintf('%.2f',$all_cost);
            }
            if($v == '新单成本'){
                $order_cost = $tar->newOrderCost($arr);
                $return[$v] = sprintf('%.2f',$order_cost);
            }

            if($v == '获取电话'){
                $tel = controller('crm/Customer','lib')->getTelCount($arr);
                $return[$v] = $tel;
            }
            if($v == '电话转换率'){
                $tel = controller('crm/Customer','lib')->getTelCount($arr);
                $validCRM = $tar->validCustomerNumber($arr);
                $return[$v] = sprintf('%.1f',$tel/$validCRM*100)."%";
            }

            if($v == 'QQ/微信'){
                $qq = controller('crm/Customer','lib')->getQQCount($arr);
                $return[$v] = $qq;
            }

            if($v == '有效进店'){
                $validJD = $tar->actualIntoCustomerNumber($arr);
                $return[$v] = $validJD;
            }
            if($v == '走单'){
                $zd = $tar->zouDan($arr);
                $return[$v] = $zd;
            }
            if($v == '网付订单'){
                $line = $tar->orderOnline($arr);
                $return[$v] = $line;
            }
            if($v == '毛客资进店率'){
                $mkzZD = $tar->mkzToJDRate($arr);
                $return[$v] = sprintf('%.1f',$mkzZD*100).'%';
            }
            if($v == '毛客资订单率'){
                $mkzOrder = $tar->mkzToOrderRate($arr);
                $return[$v] = sprintf('%.1f',$mkzOrder*100).'%';
            }
            if($v == '无效新单'){
                $invalidOrder = $tar->unvalidOrder($arr);
                $return[$v] = $invalidOrder;
            }
            if($v == '营收'){
                $fact = $tar->dealAmount($arr);
                $return[$v] = $fact;
            }

            if($v == '流失客资'){
                $loss = controller('crm/Customer','lib')->loss($arr);
                $return[$v] = $loss;
            }
            if($v == '待追踪'){
                $jdwd_crm = controller('crm/Customer','lib')->jdwd_crm($arr);
                $return[$v] = $jdwd_crm;
            }
            if($v == 'A客资'){
                $cus_a = $tar->aCustomerNum($arr);
                $return[$v] = $cus_a;
            }
            if($v == '有效率'){
                //有效率  有效/所有
                $valid = $tar->valueCustomerRate($arr);
                $return[$v] = sprintf('%.1f',$valid*100)."%";
            }

            if($v == '进店率'){
                //进店转化率 进店/有效
                $zhuanhua = $tar->intoValueRate($arr);
                $return[$v] = sprintf('%.1f',$zhuanhua*100)."%";
            }
            if($v == '订单转换率'){
                //成交率  DT/YT  YT：标记有效；DT：有效成单数
                $orderzhuanhuan = $tar->orderValueRate($arr);
                $return[$v] = sprintf('%.1f',$orderzhuanhuan*100)."%";
            }
            if($v == '成交率'){
                //成交率  DT/YT  YT：进店；DT：有效成单数
                $chengjiao = $tar->succRate($arr);
                $return[$v] = sprintf('%.1f',$chengjiao*100)."%";
            }
            if($v == 'A客转化率'){
                //  A客/有效
                $ake = $tar->ACustomerRate($arr);
                $return[$v] = sprintf('%.1f',$ake*100)."%";
            }
            if($v == '一销实收'){
                $one_fact = $tar->oneFact($arr);
                $return[$v] = sprintf('%.2f',$one_fact);
            }
            if($v == '一销均价'){
                //  套系/订单量
                $one_avg = $tar->oneAVG($arr);
                $return[$v] = sprintf('%.2f',$one_avg);
            }
            if($v == '总实收'){
                $total_fact = $tar->totalFact($arr);
                $return[$v] = sprintf('%.2f',$total_fact);
                $sql = db()->getLastSql();
            }
        }
        return json(array('code'=>200,'data'=>$return,'sql'=>$sql));
    }

    /*
     * getHomeShowAll
     * 获取客资简析
     *  staff_id       人员id
     *  shop_code     店面编码
     *  token
     * */
    public function getHomeShowAll(){
        $param = input();
        if(empty($param['staff_id'])){
            return json_encode(array('code'=>100,'msg'=>'未获取到员工ID'));
        }
        $info['data'] = [
            'staff_id' => $param['staff_id'],
            'department_id' => session('department_id'),
            'staffname' => session('staff_name'),
            'shop_code' => session('shop_code'),
            'main_position_code' => session('main_position_code'),
        ];
        $staffId = $param['staff_id'];
        if(check_right('menu1512637269')) {//查看所有客资权限
            $staff_id =  controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>$param['shop_code']]);
            $staff_id = array_column($staff_id,'id');
            $staffId = implode(',',$staff_id);
        }elseif(check_right('menu1531471639')){//查看部门客资权限
            $staff_id = controller('crm/Customer')->getDepartmentStaffs($info['data']['department_id']);
            $staff_id = array_column($staff_id,'id');
            $staffId = implode(',',$staff_id);
        }elseif(check_right('menu1529653231')) {//查看小组客资权限
            $staff_id = getGroupStaffByStaffId($param['staff_id']);
            $staff_id = array_column($staff_id,'staff_id');
            $staffId = implode(',',$staff_id);
        }
        //根据主岗位获取显示内容
        $res = db('s_home_show')->where('shop_code',$info['data']['shop_code'])->where('position_code',$info['data']['main_position_code'])->find();
        if(empty($res['content'])){
            $res['content'] = '毛客资,有效客资,有效率';
        }
        if(empty($res['time'])){
            $res['time'] = 'today,yestoday,this_week';
        }
        $content = explode(',',$res['content']);
        $tar = new Target();
        $return = [];
        $time = explode(',',$res['time']);
        foreach($time as $kk=>$vv){
            $where = '';
            if ($vv == 'this_month') {
                $where = 'month';
            } elseif ($vv == 'last_month') {
                $where = 'last month';
            } elseif ($vv == 'this_week') {
                $where = 'week';
            } elseif ($vv == 'last_week') {
                $where = 'last week';
            } elseif ($vv == 'today') {
                $where = 'today';
            } elseif ($vv == 'yestoday') {
                $where = 'yestoday';
            }
            //时间
            $day = getdateArea($where);
            $arr = array(
                'start_day' => $day[0],
                'end_day' => $day[1],
                'staff_id' => $staffId,
                'department_id' => $info['data']['department_id'] ? $info['data']['department_id'] : $info['department_id'],
                'shop_code' => $info['data']['shop_code'] ? $info['data']['shop_code'] : $info['shop_code'],
            );
            foreach($content as $k=>$v){
                if($v == '花费'){
                    $cost = $tar->cost($arr);;
                    $return[$vv][$v] = ceil($cost);
                }
                if($v == '毛客资'){
                    $mkz = $tar->newCustomerNum($arr);
                    $return[$vv][$v] = ceil($mkz);
                }
                if($v == '有效客资'){
                    $validCRM = $tar->validCustomerNumber($arr);
                    $return[$vv][$v] = $validCRM;
                }
                if($v == '有效客资(登记时间)'){
                    $validDJ = $tar->validCustomerNumberDJ($arr);
                    $return[$vv][$v] = $validDJ;
                }
                if($v == '有效新单'){
                    $validOrder = $tar->orderNumber($arr);
                    $return[$vv][$v] = $validOrder;
                }
                if($v == '总订单(订单开始时间)'){
                    $order = $tar->orderNumberStart($arr);
                    $return[$vv][$v] = $order;
                }
                if($v == '总订单(登记时间)'){
                    $order_dj = $tar->orderNumberByDJday($arr);
                    $return[$vv][$v] = $order_dj;
                }
                if($v == '毛客资成本'){
                    $all_cost = $tar->ObtainCost($arr);
                    $return[$vv][$v] = sprintf('%.2f',$all_cost);
                }
                if($v == '新单成本'){
                    $order_cost = $tar->newOrderCost($arr);
                    $return[$vv][$v] = sprintf('%.2f',$order_cost);
                }

                if($v == '获取电话'){
                    $tel = controller('crm/Customer','lib')->getTelCount($arr);
                    $return[$vv][$v] = $tel;
                }
                if($v == '电话转换率'){
                    $tel = controller('crm/Customer','lib')->getTelCount($arr);
                    $validCRM = $tar->validCustomerNumber($arr);
                    $return[$vv][$v] = sprintf('%.1f',$tel/$validCRM*100)."%";
                }

                if($v == 'QQ/微信'){
                    $qq = controller('crm/Customer','lib')->getQQCount($arr);
                    $return[$vv][$v] = $qq;
                }

                if($v == '有效进店'){
                    $validJD = $tar->actualIntoCustomerNumber($arr);
                    $return[$vv][$v] = $validJD;
                }
                if($v == '走单'){
                    $zd = $tar->zouDan($arr);
                    $return[$vv][$v] = $zd;
                }
                if($v == '网付订单'){
                    $line = $tar->orderOnline($arr);
                    $return[$vv][$v] = $line;
                }
                if($v == '毛客资进店率'){
                    $mkzZD = $tar->mkzToJDRate($arr);
                    $return[$vv][$v] = sprintf('%.1f',$mkzZD*100).'%';
                }
                if($v == '毛客资订单率'){
                    $mkzOrder = $tar->mkzToOrderRate($arr);
                    $return[$vv][$v] = sprintf('%.1f',$mkzOrder*100).'%';
                }
                if($v == '无效新单'){
                    $invalidOrder = $tar->unvalidOrder($arr);
                    $return[$vv][$v] = $invalidOrder;
                }
                if($v == '营收'){
                    $fact = $tar->dealAmount($arr);
                    $return[$vv][$v] = $fact;
                }

                if($v == '流失客资'){
                    $loss = controller('crm/Customer','lib')->loss($arr);
                    $return[$vv][$v] = $loss;
                }
                if($v == '待追踪'){
                    $jdwd_crm = controller('crm/Customer','lib')->jdwd_crm($arr);
                    $return[$vv][$v] = $jdwd_crm;
                }
                if($v == 'A客资'){
                    $cus_a = $tar->aCustomerNum($arr);
                    $return[$vv][$v] = $cus_a;
                }
                if($v == '有效率'){
                    //有效率  有效/所有
                    $valid = $tar->valueCustomerRate($arr);
                    $return[$vv][$v] = sprintf('%.1f',$valid*100)."%";
                }

                if($v == '进店率'){
                    //进店转化率 进店/有效
                    $zhuanhua = $tar->intoValueRate($arr);
                    $return[$vv][$v] = sprintf('%.1f',$zhuanhua*100)."%";
                }
                if($v == '订单转换率'){
                    //成交率  DT/YT  YT：标记有效；DT：有效成单数
                    $orderzhuanhuan = $tar->orderValueRate($arr);
                    $return[$v][$v] = sprintf('%.1f',$orderzhuanhuan*100)."%";
                }
                if($v == '成交率'){
                    //成交率  DT/YT  YT：进店；DT：有效成单数
                    $chengjiao = $tar->succRate($arr);
                    $return[$vv][$v] = sprintf('%.1f',$chengjiao*100)."%";
                }
                if($v == 'A客转化率'){
                    //  A客/有效
                    $ake = $tar->ACustomerRate($arr);
                    $return[$v][$v] = sprintf('%.1f',$ake*100)."%";
                }
                if($v == '一销实收'){
                    $one_fact = $tar->oneFact($arr);
                    $return[$vv][$v] = sprintf('%.2f',$one_fact);
                }
                if($v == '一销均价'){
                    //  套系/订单量
                    $one_avg = $tar->oneAVG($arr);
                    $return[$vv][$v] = sprintf('%.2f',$one_avg);
                }
                if($v == '总实收'){
                    $total_fact = $tar->totalFact($arr);
                    $return[$vv][$v] = sprintf('%.2f',$total_fact);
                }
            }
        }

        return json(array('code'=>200,'data'=>$return));
    }
    /*
     * customerAdd
     * 客资提报界面
     * staff_id
     * brandclass_id
     * customer_type 1:新客资;2:转介绍
     * token
     * */
    public function customerAdd(){
        $param = input();
        $bid = intval($param['brandclass_id']);
        //录入必选项配置
        $lrMust = db_config('lr_must_'.$bid);
        $lrMust = trim($lrMust,',');
        $lrMust = explode(',',$lrMust);
        if($param['customer_type'] ==2 && in_array('customer_channel',$lrMust)){
            foreach($lrMust as  $k=>$v){
                if($v == 'customer_channel'){
                    unset($lrMust[$k]);
                }
            }
        }
        return json(array('code'=>200,'data'=>$lrMust));
    }
    /*
     * getSalesMust
     * 获取追踪必选项配置
     * staff_id
     * brandclass_id
     * token
     * */
    public function getSalesMust(){
        $param = input();
        $bid = intval($param['brandclass_id']);
        //追踪必选项配置
        $dfMust = db_config('df_must_'.$bid);
        $dfMust = explode(',',$dfMust);
        //追踪选项隐藏配置
        $dfHidden = db_config('df_hidden_'.$bid);
        $dfHidden = explode(',',$dfHidden);
        return json(array('code'=>200,'must'=>$dfMust,'hidden'=>$dfHidden));
    }
    /*客资提报
     * 参数：staff_id 员工id  必填
     *       customer_name[]  客户姓名
     *       customer_sex[]  客户性别
     *       customer_tel[]  客户手机
     *       customer_wechat[]  客户微信
     *       customer_qq  客户qq
     *       add_shop_code 提报店code
     *       add_shop_name 提报店name
     *       shop_code 归属店code 选填：转介绍必填
     *       shop_name 归属店name 选填：转介绍必填
     *       customer_remark 客户备注 选填
     *       customer_type 1:新客资;2:转介绍
     *       introducer_name 介绍人姓名 选填  老顾客转介绍必填
     *       introducer_tel  介绍人手机 选填 老顾客转介绍必填
     *       introducer_ordernum 介绍人单号 选填  老顾客转介绍必填
     *       introducer_number   介绍人编号 选填  老顾客转介绍必填
     *       baby_birthday       宝宝生日
     *       baby_address        出生医院
     *       marray_day          结婚日期
     *       customer_channel_id 渠道id 必填    转介绍时不用展示，默认当前部门
     *       customer_channel 渠道id    必填    转介绍时不用展示，默认当前部门
     *       consultation_type_id   消费类型id
     *       consultation_type      消费类型
     *       customer_cource_id
     *       customer_cource        来源
     *       access_model_id        获取方式id
     *       access_model           获取方式
     *       zjs_from          转介绍类型 :   1:老顾客转介绍;2:员工亲友转介绍
     *       sales_staff_id    追踪人id
     *       sales_staff    追踪人
     *
     * */
    public function addNewCustomer(){
        $param = input('param.');
        if(empty($param['staff_id'])){
            $returnData = array('code' => 100, 'msg' => '未获取到操作人ID');
            return json($returnData);
        }
        $info = getStaffInfoById($param['staff_id']);
        $data['add_shop_code'] = $param['add_shop_code'] ? $param['add_shop_code'] : $info['shop_code'];
        $data['add_shop_name'] = $param['add_shop_name'] ? $param['add_shop_name'] : $info['shop_name'];
        $data['shop_code'] = $param['shop_code'] ? $param['shop_code'] : $info['belong_shop_code'];
        $data['shop_name'] = $param['shop_name'] ? $param['shop_name'] : $info['belong_shop_name'];
        if(empty($data['shop_code'])){
            $returnData = array('code' => 100, 'msg' => '未获取到店面，不能提报');
            return json($returnData);
        }

        $data['brandclass_id'] = $param['brandclass_id'] ? $param['brandclass_id'] : $info['brandclass_id'];
        $data['brandclass'] = $param['brandclass'] ? $param['brandclass'] : $info['brandclass'];
        $data['dj_department_id']=$param['department_id'];
        $data['dj_staff_id'] = $param['staff_id'];
        $data['dj_staff'] = $info['staff_name'] ? $info['staff_name'] : $info['staffname'];
        $data['dj_staff_number'] = trim($info['staffnumber']);
        $data['consulation_shop_code'] = trim($param['consulation_shop_code']);
        $data['consulation_shop'] = trim($param['consulation_shop']);
        $data['customer_channel_id'] = intval($param['customer_channel_id']);
        $data['customer_channel'] = trim($param['customer_channel']);

        $data['customer_cource_id'] = trim($param['customer_cource_id']);
        $data['customer_cource'] = trim($param['customer_cource']);

        $data['customer_intention_id'] = intval($param['customer_intention_id']);
        $data['customer_intention'] = trim($param['customer_intention']);
        $data['consultation_type_id'] = intval($param['consultation_type_id']);
        $data['consultation_type'] = trim($param['consultation_type']);
        $data['access_model_id'] = intval($param['access_model_id']);
        $data['access_model'] = trim($param['access_model']);
        $data['customer_type'] = intval($param['customer_type']);
        $data['sales_staff_id'] = $param['sales_staff_id'] ? intval($param['sales_staff_id']) : NULL;
        $data['sales_staff'] = $param['sales_staff'] ? $param['sales_staff'] : NULL;

        $data['introducer_name'] = trim($param['introducer_name']);
        $data['introducer_tel'] = trim($param['introducer_tel']);
        $data['introducer_ordernum'] = trim($param['introducer_ordernum']);
        $data['introducer_number'] = trim($param['introducer_number']);
        
        if($data['customer_type'] == 2 && !trim($param['customer_channel'])){
            $data['customer_channel_id'] = intval($param['department_id']);
            $data['customer_channel'] = trim($param['department_name']);
        }

        // return json(array('code'=>101,'msg'=>'test','data'=>$param,'count'=>count($param['customer_name'])));
        $data['customer_remark'] = trim($param['customer_remark']);
        if(!is_array($param['customer_name'])){
            $param['customer_name'] = json_decode($param['customer_name'],true);
        }
        if(!is_array($param['customer_tel'])){
            $param['customer_tel'] = json_decode($param['customer_tel'],true);
        }
        if(!is_array($param['customer_wechat'])){
            $param['customer_wechat'] = json_decode($param['customer_wechat'],true);
        }
        if(!is_array($param['customer_qq'])){
            $param['customer_qq'] = json_decode($param['customer_qq'],true);
        }
        if(!is_array($param['customer_remark'])){
            $param['customer_remark'] = json_decode($param['customer_remark'],true);
        }
        if(!is_array($param['channel_plan_number'])){
            $param['channel_plan_number'] = json_decode($param['channel_plan_number'],true);
        }
        if(!is_array($param['img'])){
            $param['img'] = json_decode($param['img'],true);
        }
        if($info['shop_type'] == 2){
            if(!is_array($param['baby_sex'])){
                $param['baby_sex'] = json_decode($param['baby_sex'],true);
            }
            if(!is_array($param['baby_name'])){
                $param['baby_name'] = json_decode($param['baby_name'],true);
            }
            if(!is_array($param['baby_birthday'])){
                $param['baby_birthday'] = json_decode($param['baby_birthday'],true);
            }
            if(!is_array($param['baby_address'])){
                $param['baby_address'] = json_decode($param['baby_address'],true);
            }
        }else{
            if(!is_array($param['marry_day'])){
                $param['marry_day'] = json_decode($param['marry_day'],true);
            }
        }

        $count = count($param['customer_name']);//提报客资数量
        // return json(array('code'=>222,'msg'=>'测试参数','count'=>$count,'name is array'=>is_array($param['customer_name']),'tel is array'=>is_array($param['customer_tel']), 'name'=>$param['customer_name'][0],'tel'=>$param['customer_tel'][0]));

        $param['customer_sex'] = array_values($param['customer_sex']);
        if($param['customer_type'] == 2){
            if(!$param['zjs_from']){
                return json(array('code'=>120,'msg'=>'转介绍时必须选择类型'));
            }
            //转介绍类型 :   1:老顾客转介绍;2:员工亲友转介绍
            $data['zjs_from'] = $param['zjs_from'];
        }
        // $returnData = array('code' => 900, 'msg' => '测试','count'=>$count,'param'=>$param,'tel'=>$param['customer_tel']);
        $source=controller("crm/Customer","lib")->source();
        if(empty($data['customer_cource_id'])){
            $cusTypeId = $data['customer_type'] == 2?2:3;
            if($cusTypeId == 2){
                if(in_array('转介绍',array_column($source,'cus_name'))){
                    foreach($source as $k=>$v){
                        if($v['cus_name'] == '转介绍'){
                            $data['customer_cource_id'] = $v['id'];
                            $data['customer_cource'] = '转介绍';
                        }
                    }
                }else{
                    foreach ($source as $k => $v) {
                        if($v['type_id'] == $cusTypeId || $v['type_id'] == 0){
                            $data['customer_cource_id'] = $v['id'];
                            $data['customer_cource'] = $v['cus_name'];
                            break;
                        }
                    }
                }
            }else{
                if(in_array('电商',array_column($source,'cus_name'))){
                    foreach($source as $k=>$v){
                        if($v['cus_name'] == '电商'){
                            $data['customer_cource_id'] = $v['id'];
                            $data['customer_cource'] = '电商';
                        }
                    }
                }else{
                    foreach ($source as $k => $v) {
                        if($v['type_id'] == $cusTypeId || $v['type_id'] == 0){
                            $data['customer_cource_id'] = $v['id'];
                            $data['customer_cource'] = $v['cus_name'];
                            break;
                        }
                    }
                }
            }
        }
        $cource = array_column($source,'id,cus_name,type_id','cus_name');
        if($cource[$data['customer_cource']]['type_id'] == 1){
            $data['customer_channel_id'] = null;
            $data['customer_channel'] = null;
        }
        // 这里后面要加上，必选项是否填写
        for($i=0;$i<$count;$i++){
            $data['customer_name'] = $param['customer_name'][$i];
            if(empty($data['customer_name'])){
                // $returnData = array('code' => 800, 'msg' => '客资姓名不能为空');
                // return json($returnData);
            }
            $data['channel_plan_number'] = $param['channel_plan_number'][$i];
            $data['customer_wechat'] = $param['customer_wechat'][$i];
            $data['customer_qq'] = $param['customer_qq'][$i];
            $data['customer_remark'] = $param['customer_remark'][$i].($param['img'][$i] ? '<img src="'.$param['img'][$i].'">' : '');
            if($info['shop_type'] == 2){
                $data['baby_name'] = $param['baby_name'][$i];
                $data['baby_sex'] = $param['baby_sex'][$i];
                $data['baby_birthday'] = $param['baby_birthday'][$i];
                $data['baby_address'] = $param['baby_address'][$i];
            }else{
                $data['marry_day'] = $param['marry_day'][$i];
            }
            $data['customer_tel'] = $param['customer_tel'][$i];
            if(empty($data['customer_tel']) && empty($data['customer_wechat']) && empty($data['customer_qq'])){
                $returnData = array('code' => 900, 'msg' => '联系方式不能为空');
                return json($returnData);
            }

            if($data['customer_tel'] && !preg_match("/^1[3|4|5|6|7|8|9][0-9]{9}$/", $data['customer_tel'])){
                $returnData = array('code' => 500, 'msg' => '【'.$data['customer_tel'].'】手机号格式错误');
                return json($returnData);
            }
            $data['customer_sex'] = $param['customer_sex'][$i];

            if (empty($param['shop_code']) || $param['shop_code'] == '0') {
                $returnData = array('code' => 301, 'msg' => '无法获取门店信息，不可录入客资');
                return json($returnData);
            }
            //查询归属地是否筛客
            $b_is_sk = controller("crm/Customer", "lib")->is_sk($data['belong_shop_code']);
            if ($data['customer_type'] == 1) {
                if ($b_is_sk == 1 || $info['is_sk'] == 1) {
                    $data['is_sk'] = 1;
                    //未选择筛客人则随机
                    if (!$param['sk_staff_id']) {
                        $sklist = controller("crm/Customer", "lib")->sklist($data['shop_code'], 24);
                        $rand = rand(0, count($sklist) - 1);
                        $arr = $sklist[$rand];
                        if (!empty($arr)) {
                            $data['sk_staff_id'] = $arr['id'];
                            $data['sk_staff'] = $arr['staffname'];
                        }
                    }
                }
            } else { //手机提报不筛客
                /*if ($b_is_sk == 1) {
                    $data['is_sk'] = 1;
                    //未选择筛客人则随机
                    if (!$data['sk_staff_id']) {
                        $sklist = controller("crm/Customer", "lib")->sklist($data['belong_shop_code'], 24);
                        $rand = rand(0, count($sklist) - 1);
                        $arr = $sklist[$rand];
                        if (!empty($arr)) {
                            $data['sk_staff_id'] = $arr['id'];
                            $data['sk_staff'] = $arr['staffname'];
                        }
                    }
                }*/
            }
            //录入必选项配置
            $lrMust = db_config('lr_must_'.session('brandclass_id'));
            $lrMust = trim($lrMust,',');
            $lrMust = $lrMust ? explode(',',$lrMust) : [];
            foreach($lrMust as $key=>$value){
                if(empty($data[$value]) || !$data[$value] || $data[$value] == '' || $data[$value] == 'undefined'){
                    return json( array('code' => 100, 'msg' => translate('c_customerinfo',$value).'不能为空！'));
                }
            }
            // 省市区
            $data['province'] = $param['province'][$i] ? $param['province'][$i] : null;
            $data['province_id'] = $param['province_id'][$i] ? $param['province_id'][$i] : null;
            $data['city'] = $param['city'][$i] ? $param['city'][$i] : null;
            $data['city_id'] = $param['city_id'][$i] ? $param['city_id'][$i] : null;
            $data['county'] = $param['county'][$i] ? $param['county'][$i] : null;
            $data['county_id'] = $param['county_id'][$i] ? $param['county_id'][$i] : null;
            if($info['shop_type'] == 2){
                $res = controller("crm/Customer", "lib")->addCustomer_child($data);
            }else{
                $res = controller("crm/Customer", "lib")->addCustomer($data);
            }
            if($res['code'] == 200){
                $this->data = input();
            }else{
                $this->data = array_push(input(),['error'=>$res['data']]);
            }
            $this->result_code = $res['code'];
            $this->appApiLog();

            if($res['code'] == 201){
                $returnData = array('code' => 300, 'msg' => $res['msg']);
                return json($returnData);
            }
            if ($res) {
                $customerInfo = db('CCustomerinfo')->where('id', $res)->find();
                $record['gtType'] = 4;
                $record['customer_id'] = $res;
                $record['customer_name'] = $customerInfo['customer_name'];
                $record['customer_number'] = $customerInfo['customer_number'];
                $record['sales_staff_id'] = $customerInfo['dj_staff_id'];
                $record['sales_staff'] = $customerInfo['dj_staff'];
                $record['sales_staff_number'] = $customerInfo['dj_staff_number'];
                $record['shop_name'] = $customerInfo['shop_name'];
                $record['shop_code'] = $customerInfo['shop_code'];

                // $record['sales_remark'] = '手机APP录入 ' . trim($param['customer_remark'][$i]).'<img src="'.$param['img'][$i].'">';
                $record['sales_remark'] = '手机APP录入 ' . trim($param['customer_remark'][$i]);
                if($param['img'][$i]){
                    $record['sales_remark'] .= '<img src="'.$param['img'][$i].'">';;
                }

                $record['sales_day'] = date('Y-m-d H:i:s', time());
                db()->startTrans();
                try {
                    db('c_salestrackinginfo')->insert($record);
                    cache('getCustomerTrackInfos' . $res, null);
                    getSalesTracking($res);
                    //日志
                    action_log($data,'', $res, $data['dj_staff_id'], $data['dj_staff']);
                    db()->commit();
                } catch (\Exception $e) {
                    db()->rollback();
                }
                if($param['img'][$i]){ //拼接备注
                    $img = '<img src="'.$param['img'][$i].'">';
                    $a =  array('exp',"concat(`customer_remark`,'$img')");
                    db('c_customerinfo')->where('id',$res)->update(['customer_remark'=>$a]);
                }
                if($i == $count-1){
                    return json(array('msg' => '提报成功', 'code' => 200,'customer_id'=>$res,'sql'=>db()->getLastSql()));
                }
            } else {
                return json(array('msg' =>'客资 '.trim($data['customer_name']). ' 提报失败', 'code' => 100,'res'=>$res));
            }
        }
    }

    /*获取渠道
     *getChannel
     * 参数：shop_code staff_id
     * 返回值：code:200  data：渠道
     * */
    public function getChannel(){
        $shop_code = input('param.shop_code');
       /* $login = checkAppLogin($shop_code['staff_id'],$shop_code['token']);
        if(!$login){
            return json(array('code'=>-2,'msg'=>'用户未登录或登录过期'));
        }*/
        $channel = controller('crm/Customer','lib')->getChannel($shop_code);
        if(!empty($channel)){
            $return=array('code'=>200,'msg'=>'','data'=>$channel,'session'=>$_SESSION);
        }else{
            $return=array('code'=>100,'msg'=>'暂无数据');
        }
        return json($return);
    }
    /*
     * getConsumptionType
     * 获取消费类型
     * brandclass_id
     * staff_id
     * */
    public function getConsumptionType(){
        $param = input();
        $info = controller('crm/Customer','lib')->consumptionType(['brandclass_id'=>$param['brandclass_id']]);
        if(!empty($info)){
            return json(array('code'=>200,'data'=>$info));
        }else{
            return json(array('code'=>100,'msg'=>'暂无数据'));
        }
    }
    /*
     * getIntention
     * 获取客户意向
     * staff_id
     * */
    public function getIntention(){
        $info = controller('crm/Customer','lib')->intention();
        if(!empty($info)){
            return json(array('code'=>200,'data'=>$info));
        }else{
            return json(array('code'=>100,'msg'=>'暂无数据'));
        }
    }
    /*
     * getAccessModel
     * 获取获取方式
     * staff_id
     * */
    public function getAccessModel(){
        $info = controller('crm/Customer','lib')->accessModel();
        if(!empty($info)){
            return json(array('code'=>200,'data'=>$info));
        }else{
            return json(array('code'=>100,'msg'=>'暂无数据)'));
        }
    }
    /*
     * getSource
     * 获取客户来源
     * staff_id
     * */
    public function getSource(){
        $source = controller('crm/Customer','lib')->source();
        // $source = [];
        // foreach ($info as $key => $value) {
        //     if ($value['type_id']==2 || $value['type_id']==3) {
        //         $source[] = $value;
        //     }
        // }
        if(!empty($source)){
            return json(array('code'=>200,'data'=>$source));
        }else{
            return json(array('code'=>100,'msg'=>'暂无数据'));
        }
    }
    //列表 时间，店面，客资状态，（进店，成交），分配状态 通过提报日期,关键词,客资状态筛选,数据返回格式:客资返回列表 分页加载
    /*customerList
     * all_time dj_day:录入时间,
     *           jr_day:接入时间,
     *           create_time:获取时间,
     *           fp_day:分配时间,
     *           next_time:再约时间,
     *           yjd_action_day:预约操作时间,
     *           yjd_day:预约进店时间,
     *           syjd_day:时间进店时间,
     *           order_start_time:订单开始时间,
     *           order_day:成交时间,
     *           c_star_day:追踪开始时间,
     *           last_trackday:最后追踪时间,
     *           yx_day:转有效时间,
     *           sign_time:标记时间
     * start    开始时间
     * end    结束时间
     * staff_id
     * search    查询关键字
     * shop_code    店面
     * customer_channel 渠道
     * dj_staff_id      录入人
     * sales_staff_id   追踪人
     * is_loss       不再追踪 1:是；2：否
     * is_success    成交状态；1：已成交；2未成交；3：已定金;4:本单作废
     * is_valid      客资状态；1：有效；2：待定；3：无效；4：驳回；5：反驳回
     * is_fp         分配状态；1：已分配；2：未分配；3：待接收；4：分配失败；
     * is_intostore  进店状态；1：未进店；2：进店进客；3：进店非进客;4:邀约流失；5：进店流失
     * type_info 类似pc端更多里的条件
     *limit          每页条数
     * page             页数
     * 返回值：
     *  code 200
     *  data
     * */
    public function customerList(){
        $data = input();
        //列表页时间
        $list_date = db_config('list_date');
        if($list_date == 'week'){
            $start_time = date('Y-m-d 00:00:00',strtotime('-1 week'));
            $end_time=date('Y-m-d 23:59:59');
        }elseif($list_date == 'day'){
            $start_time=date('Y-m-d 00:00:00');
            $end_time=date('Y-m-d 23:59:59');
        }else{
            $start_time = date('Y-m-01 00:00:00');
            $end_time = date('Y-m-d 23:59:59');
        }

        $data['start_time'] = $data['start'] ? date('Y-m-d 00:00:00)',strtotime($data['start'])) : $start_time;
        $data['end_time'] = $data['end'] ? date('Y-m-d 23:59:59',strtotime($data['end'])) : $end_time;


        $data['rows'] = $data['limit'] ? intval($data['limit']) : 10;
        $data['page'] = $data['page'] ? intval($data['page']) : 1;
        $data['more_like'] = $data['search'] ? trim($data['search']) : '';
        $data['tab'] = $data['tab'] ? $data['tab'] : 1;
        $data['all_time'] = $data['all_time'] ? $data['all_time'] : 'dj_day';
        $data['sord'] = 'desc';
        if($data['sales_staff_id']){
            $data['type_info'] = 'sales_staff_id='.$data['sales_staff_id'];
            unset($data['sales_staff_id']);
        }
        $ret = controller('crm/Customer','lib')->customerListData($data);
        $info = getCustomerStatus($ret['new_rows']);
        $count = $ret['records'];
        if(!empty($info)){
            $return = array('code'=>200,'data'=>$info,'count'=>$count,'sql'=>$ret['sql'],'session'=>$ret['session'],'cookie'=>$_COOKIE);
        }else{
            $return = array('code'=>100,'msg'=>'暂无数据','sql'=>$ret['sql']);
        }
        return json($return);
    }

    /*
     * 客资详情+追踪记录
     * customerDetail
     * 参数  id
     * 返回值
     * code 200
     * data 客资信息
     * log  追踪记录
     * */
    public function customerDetail(){
        $id = input('param.id');
        /*
         * ->field('id,customer_name,customer_tel,customer_wechat,customer_qq,is_valid,is_success,is_intostore,is_fp,is_loss,c_star_day,last_trackday,dj_day,add_shop_name,shop_name,customer_type,sign_name,consultation_type,consulation_shop,consulation_shop_code,customer_channel,customer_cource,customer_intention,customer_orderaddress,access_model,customer_area,customer_remark,introducer_name,province,city,county,customer_address,sign_name,dj_staff,fp_staff,sales_staff,customer_intention,order_number')
         * */
        $info = db('c_customerinfo')->where('id',$id)->find();
        if($info['is_loss'] == 1){
            $info['status'] = '不再追踪';
        }elseif ($info['is_success'] == 1) {
            $info['status'] = '已订单';
        }elseif ($info['is_success'] == 3) {
            $info['status'] = '已订金';
        }elseif ($info['is_intostore'] == 2) {
            $info['status'] = '进店进客';
        }elseif ($info['is_intostore'] == 3) {
            $info['status'] = '进店非进客';
        }elseif ($info['is_intostore'] == 5) {
            $info['status'] = '进店流失';
        } elseif ($info['yjd_day']) {
            $info['status'] = '预约进店';
        } elseif (!$info['last_trackday']) {
            $info['status'] = '待追踪';
        }elseif ($info['is_fp'] == 2) {
            $info['status'] = '未分配';
        } elseif ($info['is_fp'] == 3) {
            $info['status'] = '待接收';
        } elseif ($info['is_fp'] == 4) {
            $info['status'] = '分配失败';
        }elseif ($info['is_fp'] == 1) {
            if ($info['is_valid'] == 1) {
                $info['status'] = '有效';
            } elseif ($info['is_valid'] == 3) {
                $info['status'] = '无效';
            } elseif ($info['is_valid'] == 2) {
                $info['status'] = '待定';
            } elseif ($info['is_valid'] == 4) {
                $info['status'] = '驳回';
            } elseif ($info['is_valid'] == 5) {
                $info['status'] = '反驳回';
            } else {
                $info['status'] = '待定';
            }
        }
        $pattern = '<img.*?src="(.*?)">';
        preg_match($pattern,$info['customer_remark'],$img);
        // preg_match("/ src=([\"'])([^\\1]*)\\1/", $info['customer_remark'], $img);
        if(!empty($img[1])){
            $info['customer_remark_img'] = $img[1];
        }else{
            $info['customer_remark_img'] = '';
        }
        $info['customer_remark'] = strip_tags($info['customer_remark']);
        // 追踪记录
        /*$trackInfos = controller("crm/Customer","lib")->getCustomerTrackInfos($id);
        foreach($trackInfos as $k=>$v){
            $sales_remark=strip_tags($v['sales_remark']);
            $trackInfos[$k]['sales_remark']=preg_replace("/&nbsp;/si"," ",$sales_remark);
        }*/
        return json(array('code'=>200,'data'=>$info,'session'=>$_SESSION));
    }
    /*
     * getTrackLog
     * 追踪记录
     * id
     * */
    public function getTrackLog(){
        $id = input('param.id');
        if(empty($id)){
            return json(array('code'=>100,'msg'=>'未获取到客资ID'));
        }
        $trackInfos = controller("crm/Customer","lib")->getCustomerTrackInfos($id);
        foreach($trackInfos as $k=>$v){
            $pattern = '<img.*?src="(.*?)">';
            preg_match($pattern,$v['sales_remark'],$img);
            // preg_match("/ src=([\"'])([^\\1]*)\\1/", $v['sales_remark'], $img);
            if($img[1]){
                $trackInfos[$k]['sales_remark_img'] = $img[1];
            }else{
                $trackInfos[$k]['sales_remark_img'] = '';
            }

            $sales_remark=strip_tags($v['sales_remark']);
            $trackInfos[$k]['sales_remark']=preg_replace("/&nbsp;/si"," ",$sales_remark);
        }
        if(!empty($trackInfos)){
            return json(array('code'=>200,'data'=>$trackInfos));
        }else{
            return json(array('code'=>100,'msg'=>'未找到数据'));
        }
    }
    /*
     * getOrderHistory
     * 历史订单
     * id
     * */
    public function getOrderHistory(){
        $id = input('param.id');
        if(empty($id)){
            return json(array('code'=>100,'msg'=>'未获取到客资ID'));
        }
        $historyOrders = controller("crm/Customer","lib")->getCustomerHistoryOrders($id);
        $is_erp = is_install('sx_erp');
        foreach ($historyOrders as $key => $value) {
            if ($is_erp === false) {
                $historyOrders[$key]['erp_status'] = 0;
                $historyOrders[$key]['erp_link'] = '';
            }else{
                $historyOrders[$key]['erp_status'] = 1;
                $historyOrders[$key]['erp_link'] = '/crm/Customer/getAllServiceInfo/order_sn/'.$value['order_sn'];
            }
        }
        if(!empty($historyOrders)){
            return json(array('code'=>200,'data'=>$historyOrders));
        }else{
            return json(array('code'=>100,'msg'=>'未找到数据'));
        }
    }
    /*
     * 追踪，预约，驳回，不再追踪
     * customer_id
     * customer_name    客资姓名
     * customer_tel     客资手机
     * customer_wechat  客资微信
     * customer_sex     客资性别
     * add_friend_time  加好友时间  2019-05-12 12:20:41
     * mate_name        配偶姓名
     * mate_tel         配偶电话
     * mate_wechat      配偶微信
     *  noTrack 1:继续追踪，2：驳回；3：预约；4：不再追踪
     * staff_id
     * shop_code
     * brandclass_id
     * is_valid 客资状态  1：有效；2：待定；3：无效；4：驳回；5：反驳回
     * sign_id sign_name 客资标记
     * customer_intention_id customer_intention 客户意向
     * consultation_type_id consultation_type 消费类型
     * budget 预算
     * marry_day 婚期
     * next_time 再约时间
     * seles_step 追踪阶段id
     * step_name 追踪阶段
     * op_signinfo_id op_signinfo 追踪标记
     *
     * sales_remark 备注
     *
     * reject_reason 驳回原因
     *
     * consulation_shop_code consulation_shop 意向店面
     * reception_id reception_name 接待人
     * yjd_day 预约时间
     *
     * reason 不再追踪原因
     *
     *
     * */
    public function sales(){
        $data = input();
        if(empty($data['customer_id'])){
            return json(array('code'=>'101','msg'=>'未获取到客资ID'));
        }        
        
        if ($data['noTrack'] == 1) {
            //电访必选项配置
            $dfMust = db_config('df_must_'.$data['brandclass_id']);
            $dfMust = trim($dfMust, ',');
            if ($dfMust) {
                $dfMust = explode(',',$dfMust);
                foreach ($dfMust as $key => $value) {
                    if ($value == 'next_time') {
                        if (!$data[$value] || $data[$value] <= date('Y-m-d H:i:s')) {
                            return json(array('code'=>'99','msg'=>'再约时间小于当前时间，请重试'));
                        }
                    }
                }
            }
        }
        unset($data['token'],$data['staff_id'],$data['brandclass_id']);
        if($data['noTrack'] == 2){
            $reject['cid'] = $data['customer_id'];
            if(!$data['reject_reason']){
                return json(array('code'=>'104','msg'=>'未获取到驳回原因'));
            }else{
                $reject[''] = $data['reject_reason'];
            }
            if(!$data['sales_remark']){
                return json(array('code'=>'104','msg'=>'未获取到驳回备注'));
            }else{
                $reject['send_msg'] = $data['sales_remark'];
            }
            $res = controller('crm/Customer','lib')->customerReject($reject);
        }else{
            $cInfo = db('c_customerinfo')->where('id',$data['customer_id'])->find();

            if (!$data['customer_name']) {
                $data['customer_name'] = $cInfo['customer_name'];
            }
            if (!$data['customer_tel']) {
                $data['customer_tel'] = $cInfo['customer_tel'];
            }
            if (!$data['customer_wechat']) {
                $data['customer_wechat'] = $cInfo['customer_wechat'];
            }
            if (!$data['customer_sex']) {
                $data['customer_sex'] = $cInfo['customer_sex'];
            }
            if (!$data['mate_name']) {
                $data['mate_name'] = $cInfo['mate_name'];
            }
            if (!$data['mate_tel']) {
                $data['mate_tel'] = $cInfo['mate_tel'];
            }
            if (!$data['mate_wechat']) {
                $data['mate_wechat'] = $cInfo['mate_wechat'];
            }
            if (!$data['add_friend_time']) {
                $data['add_friend_time'] = $cInfo['add_friend_time'];
            }
            if (!$data['province']) {
                $data['province'] = $cInfo['province'];
            }
            if (!$data['city']) {
                $data['city'] = $cInfo['city'];
            }
            if (!$data['county']) {
                $data['county'] = $cInfo['county'];
            }
            if (!$data['sign_name']) {
                $data['sign_name'] = $cInfo['sign_name'];
            }
            if (!$data['is_valid']) {
                $data['is_valid'] = $cInfo['is_valid'];
            }
            if (!$data['next_time']) {
                $data['next_time'] = $cInfo['next_time'];
            }
            $res = controller('crm/Customer','lib')->editSalesTracking($data);
        }
        $this->data = input();
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    /*
     * 网付订单
     * onlineOrder
     * customer_id
     * consulation_shop_code consulation_shop 意向店面
     * reception_id reception_name 接待人
     * target_time 开单时间
     * order_amount 一销套系
     * order_fact   一销实收
     * two_pin_amount 二销套系
     * two_pin_fact   二销实收
     * photo_shop_code photo_shop_name 拍照店面
     * order_type 订单类型：1：线上，2：线下
     * order_source 订单来源
     * sign_id sign_name 客资标记
     * customer_channel_id customer_channel 渠道
     * consultation_type_id consultation_type 消费类型
     * order_note 订单备注
     * */
    public function onlineOrder(){
        $param = input();
        $res = db('c_customer_order')->where('order_sn', $param['order_sn'])->find();
        if ($res) {
            $return['code']= 300;
            $return['msg'] = '操作失败！订单号已被占用，请重试！';
            $return['order_sn'] = $res['order_sn'];
            return json($return);
        }
        $res = controller("crm/Customer","lib")->zhuanOrder($param);
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    /*
     * 发送短信
     * appSendMsg
     * ids  客资id，多个用 ，隔开
     * send_msg 短信内容
     * receive_name 接收人 多个用 ，隔开
     * model_id  短信模板id
     * */
    public function appSendMsg(){
        $res = controller('crm/Customer','lib')->send_message(input());
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    /*
     * 获取短信模板
     * getMsgModel
     * shop_code
     * staff_id
     * */
    public function getMsgModel(){
        if(empty(input('param.shop_code'))){
            return json(array('code'=>110,'msg'=>'未获取到店面编码'));
        }
        $res = controller('crm/Customer','lib')->getModel(input('post.shop_code'));
        return json($res);
    }
    /*
     * getSetting
     * 获取客资标记，追踪标记，驳回原因,追踪失败原因
     * shop_code
     * staff_id
     * token
     * */
    public function getSetting(){
        $shop_code = input('param.shop_code');
        if(empty($shop_code)){
            return json(array('code'=>110,'msg'=>'未获取到店面编码'));
        }
        // 追踪标记
        $allSet['track'] = controller('crm/Customer','lib')->markSet();
        //客资标记
        $allSet['sign'] = controller('crm/Setting','lib')->gettrackingKmarkerList();
        //驳回原因
        $allSet['reject'] = db('s_reject_reason')->where('shop_code',$shop_code)->select();
        //追踪失败原因
        $allSet['reason'] = db('s_file_reason')->where('shop_code',$shop_code)->select();
        return json(array('code'=>200,'data'=>$allSet));
    }
    /*
     * 我提报的 可通过客资状态 关键词 分配日期 进行筛选 返回:返回数量 和客资列表 分页加载
     * customerDj
     * start    开始时间
     * end    结束时间
     * search    查询关键字
     * staff_id    员工id
     * shop_code    店面
     * is_success    成交状态；1：已成交；2未成交；3：已定金
     * is_valid      客资状态；1：有效；2：待定；3：无效；4：驳回；5：反驳回
     * is_fp         分配状态；1：已分配；2：未分配；3：待接收；4：分配失败；
     * is_intostore  进店状态；1：未进店；2：进店进客；3：进店非进客
     *limit          每页条数
     * page             页数
     * 返回值：
     *  code 200
     *  data: status未客资目前状态
     * */
    public function customerDj(){
        $data = input();
        $data['start_time'] = $data['start'] ? date('Y-m-d',strtotime($data['start'])) : date('Y-m-d');
        $data['end_time'] = $data['end'] ? date('Y-m-d',strtotime($data['end'])) : date('Y-m-d');
        $data['rows'] = $data['limit'] ? intval($data['limit']) : 10;
        $data['page'] = $data['page'] ? intval($data['page']) : 1;
        $data['more_like'] = $data['search'] ? trim($data['search']) : '';
        $data['tab'] = 1;
        $data['all_time'] = 'dj_day';
        $data['sord'] = 'desc';
        $data['dj_staff_id'] = intval($data['staff_id']);

        $ret = controller('crm/Customer','lib')->customerListData($data);
        $info = getCustomerStatus($ret['new_rows']);
        $count = $ret['records'];
        $staff_name = $data['staff_name']?$data['staff_name']:session('staff_name');
        if(!empty($info)){
            action_log($data,[],0,$data['staff_id'],$staff_name);
            $return = array('code'=>200,'data'=>$info,'count'=>$count);
        }else{
            $return = array('code'=>100,'msg'=>'暂无数据');
        }
        return json($return);
    }
    /*
     * 分配给我 可通过客资状态 关键词 分配日期 进行筛选 返回:返回数量 和客资列表 分页加载
     * customerSales
     * start    开始时间
     * end    结束时间
     * shop_code    店面
     * search    查询关键字
     * staff_id    员工id
     * is_success    成交状态；1：已成交；2未成交；3：已定金
     * is_valid      客资状态；1：有效；2：待定；3：无效；4：驳回；5：反驳回
     * is_fp         分配状态；1：已分配；2：未分配；3：待接收；4：分配失败；
     * is_intostore  进店状态；1：未进店；2：进店进客；3：进店非进客
     *limit          每页条数
     * page             页数
     * 返回值：
     *  code 200
     *  data: status未客资目前状态
     * */
    public function customerSales(){
        $data = input();
        $data['start_time'] = $data['start'] ? date('Y-m-d',strtotime($data['start'])) : date('Y-m-d');
        $data['end_time'] = $data['end'] ? date('Y-m-d',strtotime($data['end'])) : date('Y-m-d');
        $data['rows'] = $data['limit'] ? intval($data['limit']) : 10;
        $data['page'] = $data['page'] ? intval($data['page']) : 1;
        $data['more_like'] = $data['search'] ? trim($data['search']) : '';
        $data['tab'] = 1;
        $data['jr_time'] = 'dj_day';
        $data['sord'] = 'desc';
        $data['sales_staff_id'] = intval($data['staff_id']);

        $ret = controller('crm/Customer','lib')->customerListData($data);
        $info = getCustomerStatus($ret['new_rows']);
        $count = $ret['records'];
        $staff_name = $data['staff_name']?$data['staff_name']:session('staff_name');
        if(!empty($info)){
            action_log($data,[],0,$data['staff_id'],$staff_name);
            $return = array('code'=>200,'data'=>$info,'count'=>$count);
        }else{
            $return = array('code'=>100,'msg'=>'暂无数据');
        }
        return json($return);
    }
    /*我的工作情况  毛客资  有效客资 进店 订单 流失客资（不再追踪） 有效率 进店率 成交率 一销套系 一销均价 总实收
     * myWork
     * 参数：start end staff_id shop_code
     * [
            'code'=>200,
            'mkz'=>$mkz,                        //毛客资
            'valid'=>$valid,                    //有效
            'jd'=>$jd,                          //进店
            'order'=>$order,                    //订单
            'loss'=>$loss,                      //不再追踪
            'validRate'=>$validRate,            //有效率
            'jdRate'=>$jdRate,                  //进店率
            'orderRate'=>$orderRate,            //成交率
            'total'=>$total,                    //一销套系
            'avg'=>$avg,                        //一销均价
            'fact'=>$fact,                      //总实收
        ];
     * */
    public function myWork(){
        $data = input();
        $start = $data['start'] ? date('Y-m-d 00:00:00', strtotime($data['start'])) : date('Y-m-d 00:00:00');
        $end   = $data['end'] ? date('Y-m-d 23:59:59', strtotime($data['end'])) : date('Y-m-d 23:59:59');
        $tar = new Target();
        $param = [
            'start_day' => $start,
            'end_day' => $end,
            'staff_id' => intval($data['staff_id']),
            'shop_code' => trim($data['shop_code'])
        ];
        $mkz = $tar->newCustomerNum($param);
        $valid = $tar->validCustomerNumber($param);
        $jd = $tar->actualIntoCustomerNumber($param);
        $order = $tar->orderNumber($param);
        /*$loss = db('CCustomerinfo')
                ->where('dj_staff_id|sales_staff_id|sk_staff_id','in',$data['staff_id'])
                ->where('loss_day','between',[$start,$end])
                ->where('is_loss',1)->where('c_from',1)
                ->where('add_shop_code|shop_code',$data['shop_code'])
                ->count();*/
        $loss = $tar->cLossCustomer($param);
        $validRate = $valid ? sprintf('%.2f',$valid/$mkz*100).'%' : '0%';
        $jdRate = $jd ? sprintf('%.2f',$jd/$valid*100).'%' : '0%';
        $orderRate = $order ? sprintf('%.2f',$order/$jd*100).'%' : '0%';
        //一销套系
       /* $total = db('c_customerinfo')->alias('c')->join('c_customer_order o','o.order_sn=c.order_number','left')
            ->where('c.add_shop_code|c.shop_code',$data['shop_code'])
            ->where('c.is_status', 1)
            ->where('c.c_from', 1)
            ->where('c.order_day','between',[$start,$end])
            ->where('c.dj_staff_id|c.sales_staff_id|c.sk_staff_id', $data['staff_id'])
            ->sum('o.order_amount');*/
        $total = $tar->oneTotalMoney($param);

        //均价
        $avg = sprintf('%.2f',$total/$order);
        $fact = $tar->dealAmount($param);
        $arr = [
            'code'=>200,
            'data'=>[
                'mkz'=>$mkz,
                'valid'=>$valid,
                'jd'=>$jd,
                'order'=>$order,
                'loss'=>$loss,
                'validRate'=>$validRate,
                'jdRate'=>$jdRate,
                'orderRate'=>$orderRate,
                'total'=>$total,
                'avg'=>$avg,
                'fact'=>$fact,
            ]
        ];
        return json($arr);
    }
    /*
     * 转订单 zhuanOrder
     * 参数：  customer_id                   客资id          必填
     *         customer_name                 客资名称          必填
               target_time                   订单时间
               consulation_shop_code         意向店面编码          必填
               consulation_shop              意向店面
               reception_id                  接待人id
               reception_name                接待人
                customer_channel_id          渠道id          必填
                customer_channel             渠道          必填
                order_fact                   一销实收
                order_amount                 一销套系
                two_pin_fact                 二销实收
                two_pin_amount               二销套系
                consultation_type_id         消费类型id          必填
                consultation_type            消费类型          必填
                order_source                 订单来源          必填
                order_note                   转单备注          必填
                order_sn                     单号
                order_type                   订单类型：1：线上；2：线下          必填
     * 返回值：array('code'=>200,'msg'=>'转订单成功')
     * */
    public function zhuanOrder(){
        $param = input('post.');
        $order_sn = trim($param['order_sn']);
        $cid = (int)$param['customer_id'];
        $res = db('c_customer_order')->where('order_sn', $order_sn)->find();
        if ($res) {
            $return['code']= 300;
            $return['msg'] = '操作失败！订单号已被占用，请重试！';
            $return['order_sn'] = $res['order_sn'];
            return json($return);
        }
        $res = controller("crm/Customer","lib")->zhuanOrder($param);
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    /*
       * 预约进店 customerYJD
       * 参数：id  客资id          必填
               consulation_shop_code         意向店面编码          必填
               consulation_shop              意向店面          必填
               reception_id                  接待人id
               reception_name                接待人
               yjd_day                       预约进店时间          必填
               intostore_note                预约备注          必填
       * 返回值：array('code'=>200,'msg'=>'预约进店成功')
       * */
    public function customerYJD(){
        $data = input();
        if(!check_right('menu1519633870')){
            return array('code'=>130,'msg'=>'你无此操作权限');
        }
        $shop_type = $data['shop_type']?$data['shop_type']:session('shop_type');
        if($shop_type == 2){
            $res = controller('crm/Customer','lib')->customerYjd_child($data);
        }else{
            $res = controller('crm/Customer','lib')->customerYjd($data);
        }
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    /*
     * 标记流失（不再追踪） noTrack
     * 参数：id  客资id
     *       loss_cause 不再追踪原因
     * 返回值：array('code'=>200,'msg'=>'标记有效成功')
     * */
    public function noTrack(){
        $data = input();
        $param['id'] = intval($data['id']);
        $param['loss_cause'] = $data['loss_cause'];
        $res = controller('crm/Customer','lib')->notTraking($param);
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    /*
     * 标记有效 signValid
     * 参数：id  客资id
     * 返回值：array('code'=>200,'msg'=>'标记有效成功')
     * */
    public function signValid(){
        $id = input('param.id');
        $res = controller('crm/Customer','lib')->signValid($id);
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    /*
     * 标记无效 signUnValid
     * 参数：id  客资id
             unvalid_id  无效原因id
             unvalid_reason  无效原因
     * 返回值：array('code'=>200,'msg'=>'标记无效成功')
     * */
    public function signUnValid(){
        $data = input();
        $res = controller('crm/Customer','lib')->signUnValid($data);
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    /*
     * 订单来源 orderSource
     * 参数：shop_code  店code
     * 返回值：array('code'=>200,'data'=>'数据')
     * */
    public function orderSource(){
        $shop_code = input('param.shop_code');
        if(empty($shop_code)){
            $ret = array('code'=>101,'msg'=>'未获取到店面编码');
        }else{
            $res = db('s_order_source')->where('shop_code',$shop_code)->where('is_delete',1)->select();
            if(!empty($res)){
                $ret = array('code'=>200,'data'=>$res);
            }else{
                $ret = array('code'=>100,'msg'=>'暂无订单来源');
            }
        }
        return json($ret);
    }
    /*
     * 转介绍--介绍人搜索 introSearch
     * 参数：customer_name  搜索内容：姓名，手机，单号
     * 返回值：array('code'=>200,'data'=>'数据')
     * */
    public function introSearch(){
        $data = input();
        $res = controller("crm/Customer","lib")->customerNameSearch(trim($data['customer_name']));
        if($res['Code'] == 200){
            $ret = array('code'=>200,'msg'=>'','data'=>$res['Data']);
        }else{
            $ret = array('code'=>$res['Code'],'msg'=>$res['Msg'],'data'=>$res['Data']);
        }
        return json($ret);
    }
    /*
     * customerRejectBack
     * 反驳回
     * cid 客资id
     * staff_id
     *fbhReason
     * */
    public function customerRejectBack(){
        $data = input();
        $return = controller('crm/Customer','lib')->customerUnValidUpdate($data);
        if($return['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$return['data']]);
        }
        $this->result_code = $return['code'];
        $this->appApiLog();
        return json($return);
    }
    /*
     * appDelCustomer
     * 删除客资
     * id 客资id，多个用 ，隔开
     * staff_id
     * */
    public function appDelCustomer(){
        $data = input();
        $ids = explode(',',$data['id']);
        $res = controller("crm/Customer","lib")->delCustomer($ids);
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        if($res['code'] == 1){
            return json(array('code'=>200,'msg' =>'删除客资成功！','data'=>$res['data']));
        }else{
            return $res;
        }
    }
    /*
     * getBrandclass
     * 分配时获取事业部 店
     * staff_id
     *
     * */
    public function getBrandclass(){
        $staffinfo = getStaffInfoById(input('param.staff_id'));
        if($staffinfo['is_belong'] > 1){
            $data['brandclass_id'] = $staffinfo['brandclass_id'];
            $p = [
                'staff_id'=> input('param.staff_id'),
                'brandclass_id'=> $staffinfo['brandclass_id'],
                'shop_type' => $staffinfo['shop_type']
            ];
            $shops = getShops($p);//可操作店

        }else{
            $shops = [];
        }
        $res = controller("crm/Customer","lib")->getBrandClass();
        if($res){
            $return = array('code'=>200,'data'=>$res,'shop'=>$shops,'android_shops'=>array_values($shops));
        }else{
            $return = array('code'=>100,'msg'=>'暂无数据');
        }
        return json($return);
    }
    /*
     *appGetDepartment
     * 获取部门 人员
     * shop_code
     * */
    public function appGetDepartment(){
        $data = input();
        if(empty($data['shop_code'])){
            return json(array('code'=>100,'msg'=>'未获取到要店面'));
        }
        $res = controller('crm/Setting','lib')->department_list(['shop_code'=>$data['shop_code']]);
        if(empty($res)){
            return json(array('code'=>100,'msg'=>'未查询到部门信息'));
        }else{
            $staffs = $this->getFpStaffs($data);
            if(empty($staffs)){
                return json(array('code'=>200,'data'=>$res,'staff'=>[]));
            }else{
                return json(array('code'=>200,'data'=>$res,'staff'=>$staffs));
            }
        }
    }
    /*
     *appGetGroupByDepId
     * 获取部门下的小组  人员
     * shop_code
     * department_id
     * */
    public function appGetGroupByDepId(){
        $data = input();
        if(empty($data['shop_code'])){
            return json(array('code'=>100,'msg'=>'未获取到要店面'));
        }
        if(empty($data['department_id'])){
            return json(array('code'=>100,'msg'=>'未获取到部门ID'));
        }
        $res = db('CStaffGroup')->where('department_id',$data['department_id'])->select();
        $staffs = $this->getFpStaffs($data);
        return json(array('code'=>200,'data'=>$res,'staff'=>$staffs));
        
        // if(empty($res)){
        //     return json(array('code'=>100,'msg'=>'未查询到部门下的小组信息'));
        // }else{
        //     $staffs = $this->getFpStaffs($data);
        //     if(empty($staffs)){
        //         return json(array('code'=>200,'data'=>$res,'staff'=>[]));
        //     }else{
                
        //     }
        // }
    }
    /*
     * getGroupStaffs
     * 获取小组下人员
     * shop_code
     * department_id
     * group_id
     * */
    public function getGroupStaffs(){
        $data = input();
        if(empty($data['shop_code'])){
            return json(array('code'=>100,'msg'=>'未获取到店面'));
        }
        if(empty($data['department_id'])){
            return json(array('code'=>100,'msg'=>'未获取到部门ID'));
        }
        if(empty($data['group_id'])){
            return json(array('code'=>100,'msg'=>'未获取到小组ID'));
        }
        $staffs = $this->getFpStaffs($data);
        if(!empty($staffs)){
            return json(array('code'=>200,'data'=>$staffs));
        }else{
            return json(array('code'=>100,'msg'=>'未获取到人员'));
        }
    }
    public function getFpStaffs($data){
        $time_area= $data['time_area'] ? $data['time_area'] : 'today';
        $department_id = $data['department_id'] ? $data['department_id'] : '';
        $group_id      = $data['group_id'] ? $data['group_id'] : '';
        $shop_code     = $data['shop_code'] ? $data['shop_code'] : session('shop_code');
        $method        = $data['method'] ? $data['method'] : '';

        if($department_id) $pram['department_id'] = $department_id;

        if($shop_code){
            $pram['shop_code'] = $shop_code;
            $pram['work_type'] = RECEIVE_WORK_TYPE;
            // $staffs = cache('staffs_'.$shop_code.$department_id.$group_id.$method);
            $staffs = cache('staffs_21'.$shop_code.$department_id.$method);
            if(empty($staffs)){
                // $staffs = controller('crm/Customer','lib')->get_staff_lists($pram);
                // cache('staffs_'.$shop_code.$department_id.$group_id.$method,$staffs);
                $staffs = getShopStaffs($pram);
                cache('staffs_21'.$shop_code.$department_id.$method,$staffs);
            }
        }
        $day = getdateArea($time_area);
        //获取小组下的员工
        if($group_id){
            $groupStaffs = db('c_staff_group_relation')->where('group_id',$group_id)->column('staff_id');
        }

        $a = [];
        $b = [];
        $arrIds = array_column($staffs,'id');
        $ids = implode(',',$arrIds);
        $condition = [
            'staff_id'  => $ids,
            'shop_code' => $shop_code,
            'start_day' => $day[0],
            'end_day'   => $day[1],
        ];
        // 查询所有员工 接收的客资
        $info = controller("crm/Customer","lib")->jrCustomers($condition);
        // 计算每一个员工的业绩
        if($method){
            $targets = controller("crm/Target","lib")->getAllTarget();
            $all_method = array_column($targets,'method');
            if (!in_array($method, $all_method)){
                return $staffs;
            }
            $targInfo = controller("crm/Target","lib")->$method($condition);
        }
        foreach ($staffs as $key => $value) {
            if($group_id){
                if(in_array($value['id'],$groupStaffs)){
                    // 查看员工是否在线
                    $status = controller('crm/Customer','lib')->getStaffOnlineStatus($value['id']);
                    $condition = [
                        'staff_id'  => $value['id'],
                        'start_day' => $day[0],
                        'end_day'   => $day[1],
                    ];
                    if($status){
                        $res1['status'] = 1;
                        $res1['rate'] =  $targInfo[$value['id']] ? $targInfo[$value['id']] : 0;
                        $res1['name'] = $value['staffname'];
                        $res1['id'] = $value['id'];
                        $res1['cNum'] = $info[$value['id']] ? $info[$value['id']] : 0;
                        array_push($a,$res1);
                    }else{
                        $res['status'] = 0;
                        $res['rate'] =  $targInfo[$value['id']] ? $targInfo[$value['id']] : 0;
                        $res['name'] = $value['staffname'];
                        $res['id']   = $value['id'];
                        $res['cNum'] = $info[$value['id']] ? $info[$value['id']] : 0;
                        array_push($b,$res);
                    }
                }
            }else{
                // 查看员工是否在线
                $status = controller('crm/Customer','lib')->getStaffOnlineStatus($value['id']);
                $condition = [
                    'staff_id'  => $value['id'],
                    'start_day' => $day[0],
                    'end_day'   => $day[1],
                ];
                if($status){
                    $res1['status'] = 1;
                    $res1['rate'] =  $targInfo[$value['id']] ? $targInfo[$value['id']] : 0;
                    $res1['name'] = $value['staffname'];
                    $res1['id'] = $value['id'];
                    $res1['cNum'] = $info[$value['id']] ? $info[$value['id']] : 0;
                    array_push($a,$res1);
                }else{
                    $res['status'] = 0;

                    $res['rate'] =  $targInfo[$value['id']] ? $targInfo[$value['id']] : 0;

                    $res['name'] = $value['staffname'];
                    $res['id'] = $value['id'];
                    $res['cNum'] = $info[$value['id']] ? $info[$value['id']] : 0;
                    array_push($b,$res);
                }
            }
        }

        $return = array_merge($a,$b);

        return $return;
    }
    /*
     * appFP
     * 分配
     * cid 多个 ，隔开
     * staff_id
     * shop_code
     * shop_name
     * */
    public function appFP(){
        $param = input();
        $date = date('Y-m-d H:i:s',time());
        $sid  = $param['sales_staff_id'];
        if(empty($sid)){
            return json(array('code'=>100,'msg'=>'未获取到接收人ID'));
        }
        //如果追踪人已经是要分配的人，去掉
        $sales = db('c_customerinfo')->where('id','in',$param['cid'])->field('id,sales_staff_id')->select();
        $cid = '';
        foreach($sales as $kk=>$vv){
            if(count($sales) == 1){
                if($vv['sales_staff_id'] == $sid){
                    return json(array('code'=>101,'msg'=>'已是此追踪人，不能分配'));
                }
                $cid = $vv['id'];
            }else if($vv['sales_staff_id'] != $sid){
                $cid  .= $vv['id'].',';
            }

        }

        $arr['cid'] = $cid;
        $arr['sid'] = (int)$sid;
        $arr['shop_code'] = $param['shop_code'];
        $arr['shop_name'] = $param['shop_name'];

        $return = controller("crm/Customer","lib")->allotSale($arr);
        if ($return['code']!=200) {
            return json($return);
        }else{
            $cids = explode(',', $cid);
            $cNum = count($cids);
            $staffInfo = getStaffInfoById($param['sales_staff_id']);
            // 发送消息用数据
            $remind = getRemind($staffInfo['brandclass_id']);
            // 181212 Eric
            if(in_array('tan',$remind['sd']['send_method']) && in_array('sales',$remind['sd']['send_receive'])){
                $messageD['send_type']      = 1;
                $messageD['send_time']      = $date;
                $messageD['send_title']     = '分配提醒';
                $messageD['send_msg']       = '您分配到'.$cNum.'笔客资，请查收。';
                $messageD['receive_id']     = $sid;
                $messageD['receive_name']   = $staffInfo['staff_name'] ? $staffInfo['staff_name'] : $staffInfo['staffname'];
                $messageD['receive_status'] = 1;
                $messageD['receive_time']   = $date;
                $messageD['operation_type'] = 2;
                $messageD['operation']      = '';
                $timeOut = db_config('fp_timeout_'.$staffInfo['shop_code']);
                $messageD['time_out']       = $timeOut ? $timeOut : 60;

                $resM = sendSystemMessage($messageD);
            }


            // 发送微信模板消息
            if(in_array('tui',$remind['sd']['send_method']) && in_array('sales',$remind['sd']['send_receive'])){
                $content = [
                    'touser'       => $sid,
                    'template_id'  => OPENTM_MFP,
                    'data'         => [
                        'first'=>[
                            'value'=> '系统消息',
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> '您分配到'.$cNum.'笔客资，请查收。',
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $date,
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> '请尽快追踪，谢谢',
                            'color'=> '#173177'
                        ],
                    ],
                ];
                $send_data['content'] = json_encode($content);
                $res = sendMsg($send_data);
            }
            if($return['code'] == 200){
                $this->data = input();
            }else{
                $this->data = array_push(input(),['error'=>$return['data']]);
            }
            $this->result_code = $return['code'];
            $this->appApiLog();
            return json($return);
        }
    }
    /*
     * 渠道花费查询
     * channelCostSearch
     * shop_code
     * belong_shop_code
     * cost_date  花费设定时间
     * staff_id
     * department_id
     * channel_name  模糊搜索渠道名
     * page 页数
     * limit 每页条数
     * */
    public function channelCostSearch(){
        $param = input();
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 20;
        $where = [];


        if($param['channel_name']){
            $where['channel_name'] = ['like','%'.trim($param['channel_name']).'%'];
        }

        if($param['shop_code']){
            $where['shop_code'] = $param['shop_code'];
        }

        $info['data'] =  db('s_channel')->where($where)->page($page)->limit($limit)->field('id,channel_name,order_sort')->order('order_sort')->select();
        $info['count'] = db('s_channel')->where($where)->count();
        if($param['cost_date']){
            $where['cost_date'] = date('Y-m-d',strtotime($param['cost_date']));
        }else{
            return json(array('code'=>99,'msg'=>'请选择花费设定日期'));
        }
        if($param['department_id']){
            $where['department_id'] = $param['department_id'];
        }
        if($param['belong_shop_code']){
            $where['belong_shop_code'] = $param['belong_shop_code'];
        }
        if($param['province_id']){
            $where['province_id'] = $param['province_id'];
        }
        if($param['city_id']){
            $where['city_id'] = $param['city_id'];
        }
        $cost = db('s_channel_cost')->where($where)->column('cost,belong_shop_code','channel_id');
        foreach($info['data'] as $k=>$v){
            $info['data'][$k]['cost'] = $cost[$v['id']]['cost'];
            $info['data'][$k]['belong_shop_code'] = $cost[$v['id']]['belong_shop_code'];
        }
        if(empty($info)){
            return json(array('code'=>100,'msg'=>'未获取到渠道花费'));
        }else{
            $total = array_sum(array_column($info['data'],'cost'));
            $info['total'] = sprintf('%.2f',$total);
            return json(array('code'=>200,'data'=>$info));
        }
    }
    /*
     *channelCostEdit
     * 渠道花费修改
     * staff_id
     * shop_code
     * shop_name
     * channel_id  渠道id
     * cost 花费
     * cost_date 花费设定日期
     * province_id 省id
     * province_name
     * city_id 市id
     * city_name
     * department_id 部门id
     * department_name
     * belong_shop_code 归属店
     * belong_shop_name
     * */
    public function channelCostEdit(){
        $data = input();
        if(empty($data['channel_id'])){
            return json(array('code'=>100,'msg'=>'未获取到渠道ID'));
        }
        if(empty($data['cost'])){
            return json(array('code'=>101,'msg'=>'花费不能为空'));
        }
        if(empty($data['shop_code'])){
            return json(array('code'=>102,'msg'=>'未获取到店面编码'));
        }
        if(empty($data['cost_date'])){
            return json(array('code'=>103,'msg'=>'未获取到花费日期'));
        }
        $res = controller('crm/Customer','lib')->appChannelCostEdit($data);
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    /*
     *getShopStaffs
     * 获取店面下人员（登记人，追踪人，接待人,筛客人）
     * is_belong  登录后返回值有
     * brandclass_id
     * shop_code
     * token
     * flag dj:登记人；sales:追踪人;sk：筛客人；reception:接待人;默认：登记人
     * staff_id
     * */
    public function getShopStaffs(){
        $data = input();
        $staff = [];
        if($data['flag'] == 'sales'){
            if(empty($data['shop_code'])){
                return json(array('code'=>101,'msg'=>'参数有误，未获取到店面编码'));
            }
            $p['work_type'] = 21;
            $p['shop_code'] = $data['shop_code'];
        }elseif($data['flag'] == 'reception'){
            if(empty($data['shop_code'])){
                return json(array('code'=>101,'msg'=>'参数有误，未获取到店面编码'));
            }
            // $p['work_type'] = 1;
            // $p['shop_code'] = $data['shop_code'];
            $staff = controller("crm/Customer","lib")->sklist($data['shop_code'],MS_WORK_TYPE);
            $this->data = input();
            $this->result_code = 200;
            $this->appApiLog();
            return json(array('code'=>200,'data'=>array_values($staff)));
        }elseif($data['flag'] == 'sk'){
            if(empty($data['shop_code'])){
                return json(array('code'=>101,'msg'=>'参数有误，未获取到店面编码'));
            }
            $p['work_type'] = 24;
            $p['shop_code'] = $data['shop_code'];
        }else{
            if($data['is_belong'] == 1){
                unset($p);
            }elseif($data['is_belong'] == 2){
                $p['brandclass_id'] = $data['brandclass_id'] ? $data['brandclass_id'] : session('brandclass_id');
            }else{
                $p['shop_code'] = $data['shop_code'];
            }
        }

        if(check_right('menu1512637269')){ //查看全部客资
            $staff = getShopStaffs($p);
        }elseif(check_right('menu1531471639')){ //查看部门客资
            if($data['department_id']){
                $p['department_id'] = $data['department_id'];
            }else{
                // $cache = cache('staffInfo_'.$data['staff_id']);
                $cache = getStaffInfoById($data['staff_id']);
                if($cache){
                    $p['department_id'] = $cache['department_id'];
                }
            }
            $staff = getShopStaffs($p);
        }elseif(check_right('menu1529653231')){ //查看小组客资
            //查询小组成员，排重，看谁符合
            $group_id = db('c_staff_group_relation')->where('is_admin',1)->where('staff_id',$data['staff_id'])->column('group_id');
            $group_staff = db('c_staff_group_relation')->where('group_id','in',$group_id)->group('staff_id')->column('staff_id');
            $staff = getShopStaffs($p);
            foreach($staff as $k=>$v){
                if(!in_array($v['id'],$group_staff)){
                    unset($staff[$k]);
                }
            }
        }
        $this->data = input();
        $this->result_code = 200;
        $this->appApiLog();
        return json(array('code'=>200,'data'=>array_values($staff)));
    }
    /*
     * getShop
     * 意向店面，拍照店面查询
     * brandclass_id
     * shop_code
     * flag    photo:拍照店；intention：意向店
     * token
     * staff_id
     * */
    public function getShop(){
        $data = input();
        if(empty($data['brandclass_id'])){
            return json(array('code'=>101,'msg'=>'参数有误，未获取到事业部ID'));
        }
        $search['brandclass_id'] = $data['brandclass_id'];
        if($data['flag'] == 'photo'){
            $search['is_photo']   = 1;
        }else{
            //意向店面
            $intention_shop = db_config('intention_shop');
            if($intention_shop == 1){//所有店

            }elseif($intention_shop == 2){//接单店
                $search['is_op2'] = 1;
            }elseif($intention_shop == 3){//本店
                $search['shop_code'] = $data['shop_code'];
            }else{
                $search['is_marketing'] = 2;
            }
        }
        $intentionShop=controller('crm/Customer','lib')->get_shop($search);
        return json(['code'=>200,'data'=>$intentionShop]);
    }
    /*
     * showCost
     * 花费录入界面
     * brandclass_id
     * shop_code
     * staff_id
     * valid_date
     * shop_type
     * belong_shop_code
     * belong_shop_name
     *
     * return 'code'=>200,'flag'=>$flag,'data'=>$info  其中，flag=region，是地域，要显示省市，flag=belong，是归属店
     * */
    public function showCost(){
        $data = input();
        if(empty($data['shop_code'])){
            return json(array('code'=>101,'msg'=>'参数有误，未获取到店面编码'));
        }
        //维度
        $method = db_config('cost_method_'.$data['shop_code']);
        if($method == 'belong' && ($data['valid_date'] == 0)){
            $array = [
                'brandclass_id' => $data['brandclass_id'],
                'staff_id' => $data['staff_id'],
                'shop_type' =>$data['shop_type'],
                'shop_code' =>$data['shop_code'],
                'belong_shop_code' =>$data['belong_shop_code'],
                'belong_shop_name' =>$data['belong_shop_name'],
            ];
            $info = getBelongShop($array);
            $flag = 'belong';
        }else{
            $p = [
                'type'=>1,
                'shop_code'=>$data['shop_code']
            ];
            $info=controller("crm/Customer","lib")->address($p);
            $flag = 'region';
        }
        return json(array('code'=>200,'flag'=>$flag,'data'=>$info,'android'=>array_values($info)));
    }
    /*
     *getCity
     * 根据省份获取市
     * shop_code
     * staff_id
     * pid  省份id
     * */
    public function getCity(){
        $data = input();
        if(empty($data['shop_code'])){
            return json(array('code'=>101,'msg'=>'参数有误，未获取到店面编码'));
        }else{
            $p['shop_code'] = $data['shop_code'];
        }
        if(empty($data['pid'])){
            return json(array('code'=>102,'msg'=>'参数有误，未获取到省份ID'));
        }else{
            $p['pid'] = $data['pid'];
        }
        $p['type']= 2;
        $info=controller("crm/Customer","lib")->address($p);
        return json(array('code'=>200,'data'=>$info));
    }
    /*
     * getMenu
     * 获取用户权限接口
     * staff_id
     * shop_code
     * main_position_code
     * token
     * */
    public function getMenu(){
        $data = input();
        if(empty($data['shop_code'])){
            return json(array('code'=>101,'msg'=>'参数有误，未获取到店面编码'));
        }
        if(empty($data['staff_id'])){
            return json(array('code'=>102,'msg'=>'参数有误，未获取到用户ID'));
        }
        if(empty($data['main_position_code'])){
            return json(array('code'=>102,'msg'=>'参数有误，未获取到用户岗位编号'));
        }
        $staffInfo = getStaffInfoById($data['staff_id']);
        if(in_array(SYSTEM_AUTH_ADMIN,explode(',',$staffInfo['main_work_type'].','.$staffInfo['work_type']))){
            $info = db('s_menu')->field('menu_code,menu_name')->select();
            return json(array('code'=>200,'data'=>$info));
        }
        $menu = db('s_position_menu')->where('position_code',$data['main_position_code'])->value('menu_code');
        $menu = explode(',',$menu);
        $info = db('s_menu')->where('menu_code','in',$menu)->field('menu_code,menu_name')->select();
        return json(array('code'=>200,'data'=>$info));
    }
    /*
     * getIntostoreList
     * 获取进客列表
     * @param search_time    查询时间方式      选填
     * @param content    精确查询内容      选填
     * @param start    end    开始结束时间     选填
     * @param flag          查询标记     选填
     * @param reception_id   接待人id  选填
     * @param customer_intention_id   客户意向  选填
     * @param consulation_shop_code   意向店面  选填   可查询多个  查的归属店
     * @param consultation_type_id   消费类型  选填
     * @param customer_cource_id   客户来源  选填
     * @param dj_staff_id   客户来源  选填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * @param limit 条数
     * @param page 页数
     * */
    public function getIntostoreList(){
        $data = input();
        $info = controller('index/Intostore','api')->customerList($data);
        return json(array('code'=>200,'data'=>$info));
    }
    /*
     * 切换岗位  changePosition
     * @param main_position_code  主岗位code  全局
     * return true/false
     * */
    public function changePosition(){
        $main_position_code = input('main_position_code');
        $info = changeMyPosition($main_position_code);
        $shop_code = input('shop_code')?input('shop_code'):session('shop_code');
        if($info){
            return json(array('code'=>200,'msg'=>'切换岗位成功','session'=>$shop_code,'cookie'=>$_COOKIE,'main_position_code'=>$main_position_code));
        }else{
            return json(array('code'=>100,'msg'=>'切换岗位失败'));
        }
    }
    /*
     * @param file
     * 图片上传接口
     * */
    public function upload_img(){
        $base_path = 'upload';
        $addr = config('app_host');
        $addr = trim(trim($addr), '/');
        // 多文件
        // $files = request()->file("imgs");
        // 单文件
        $files = request()->file();

        $response = [];
        if (!$files) {
            $returnData['code'] = 100;
            $returnData['msg']  = '图片不存在';
            return ($returnData);
        }
        foreach ($files as $key => $value) {
            $info = $value->getInfo();
            $type = explode('/', $info['type']);
            $name = md5($info['name']);
            $size = md5($info['size']);
            // $file = hash_file($info['tmp_name']);
            $filename = md5($name.$size);
            $fDir = substr($filename, 0, 2);
            $sDir = substr($filename, 2, 2);
            // 是否判断同一文件
            $is_have = file_exists(ROOT_PATH.'/public/'.$base_path.DS.$fDir.DS.$sDir.DS.$filename.'.'.$type[1]);
            if ($is_have) {
                // 重新生成新的文件名
                do{
                    $rand = get_rand_string(6);
                    $filename = md5($filename.$rand);
                    $fDir = substr($filename, 0, 2);
                    $sDir = substr($filename, 2, 2);
                    $is_have = file_exists(ROOT_PATH.'/public/'.$base_path.DS.$fDir.DS.$sDir.DS.$filename.'.'.$type[1]);
                }while($is_have);
                $res = $value->move(ROOT_PATH.'/public/'.$base_path.DS.$fDir.DS.$sDir, $filename);
                if ($res === false) {
                    $returnData['code'] = 101;
                    $returnData['msg']  = '图片上传失败，请检查权限。';
                    return json($returnData);
                }
            }else{
                $res = $value->move(ROOT_PATH.'/public/'.$base_path.DS.$fDir.DS.$sDir, $filename);
                if ($res === false) {
                    $returnData['error']= 1;
                    $returnData['code'] = 102;
                    $returnData['msg']  = '文件上传失败，请检查权限。';
                    return json($returnData);
                }
            }

            $response['code'] = 200;
            $response['name'] = $info['name'];
            $response['url']  = $addr.'/'.$base_path.'/'.$fDir.'/'.$sDir.'/'.$res->getsaveName();
            $response['file'] = $res->getsaveName();
            break;
        }
        $this->data = [];
        $this->result_code = $response['code'];
        $this->appApiLog();
        return json($response);
    }
    /*----------------转介绍-------start----------------------*/
    /*
     * 转介绍
     * @param department_id   部门id
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * @param staff  dj_staff或sales_staff 按登记人或追踪人算,默认登记人
     * @param token
     * @param limit     条数，默认10
     * @param page      页数
     * @param start   开始时间
     * @param end     结束时间    默认当天
     * @param main_position_code
     * @param shop_code
     * */
    public function getZJSInfo(){
        $data = input();
        $data['start'] = $data['start'] ? date('Y-m-d H:i:s',strtotime($data['start'])) : date('Y-m-d');
        $data['end'] = $data['end'] ? date('Y-m-d 23:59:59',strtotime($data['end'])) : date('Y-m-d 23:59:59');
        $data['staff'] = $data['staff'] ? trim($data['staff']) : 'dj_staff';
        if(empty($data['shop_code'])){
            return json(array('code'=>100,'msg'=>'查看转介绍客资必须有店面编码参数'));
        }
        if(check_right('menu1574059811')){ //本店权限
            $info = $this->selectShopZJS($data);
            return json(array('code'=>200,'data'=>$info));
        }elseif(check_right('menu1574059829')){  //本人权限
            if(empty($data['staff_id'])){
                return json(array('code'=>100,'msg'=>'查看本人转介绍客资必须有店面编码参数'));
            }
            $info = $this->selectSelfZJS($data);
            return json(array('code'=>200,'data'=>$info));
        }else{
            return json(array('code'=>100,'msg'=>'没有查看转介绍客资的权限'));
        }
    }
    //查看本店转介绍客资
    public function selectShopZJS($data){
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 2;
        if($data['department_id']){
            if($data['staff'] == 'sales_staff'){
                $where['sales_department_id'] = intval($data['department_id']);
            }else{
                $where['dj_department_id'] = intval($data['department_id']);
            }
        }
        $data['staff'] = $data['staff'] ? trim($data['staff']) : 'dj_staff';
        $where['shop_code'] = $data['shop_code'];
        $mkz = db('c_customerinfo')->where($where)->where('dj_day','between',[$data['start'],$data['end']])->count('id');
        $order = db('c_customerinfo')->where($where)->where('is_success',1)->where('order_day','between',[$data['start'],$data['end']])->count('id');
        $rate = sprintf('%.2f',$order/$mkz*100).'%';
        $sql = "sum(dj_day between '".$data['start']."' and '".$data['end']."') as mkz,";
        $sql .= "sum(is_success=1 and order_day between '".$data['start']."' and '".$data['end']."') as `order`";
        // 录入客资量
        $info= db('c_customerinfo')
            ->where($where)
            ->group($data['staff'])
            ->column($sql,$data['staff']);
        $sql = db()->getLastSql();
        $staff= db('c_customerinfo')
            ->where($where)
            ->group($data['staff'])
            ->column($data['staff']);
        // $staff = array_column($info,$data['staff']);

        $list = [];
        foreach($staff as $k=>$v){
            if($v){
                $list[$v]['staff'] = $v;
                $list[$v]['mkz'] = $info[$v]['mkz'] ? $info[$v]['mkz'] : 0;
                $list[$v]['order'] = $info[$v]['order'] ? $info[$v]['order'] : 0;
                $list[$v]['rate'] = $info[$v]['order']/$info[$v]['mkz']>0 ? sprintf('%.2f',$info[$v]['order']/$info[$v]['mkz']*100).'%' : '0%';
            }
        }


        return array(
          'mkz' => $mkz,
          'order' => $order,
          'rate' => $rate,
          'list' => $list,
          'sql'=>$sql,
        );
    }
    /*
    * 转介绍客资列表   zjsList
    * @param department_id   部门id
    * @param staff_id   操作人id
    * @param staff_name 操作人
    * @param staff  dj_staff或sales_staff 按登记人或追踪人算,默认登记人
    * @token
    * @search_staff 查询谁的客资就传谁的名字
    * @start   开始时间
    * @end     结束时间    默认当天
    * @main_position_code
    * @shop_code
    * */
    public function zjsList(){
        $data = input();
        $limit = $data['limit'] ? $data['limit'] : 10;
        $page = $data['page'] ? $data['page'] : 1;
        $data['staff'] = $data['staff'] ? $data['staff'] : 'dj_staff';
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 2;
        $where['shop_code'] = $data['shop_code'];
        if($data['department_id']){
            if($data['staff'] == 'sales_staff'){
                $where['sales_department_id'] = intval($data['department_id']);
            }else{
                $where['dj_department_id'] = intval($data['department_id']);
            }
        }
        $all = db('c_customerinfo')
            ->where($where)
            ->where($data['staff'],$data['search_staff'])
            ->where('dj_day','between',[$data['start'],date('Y-m-d 23:59:59',strtotime($data['end']))])
            ->count('id');
        $mkz = db('c_customerinfo')
            ->where($where)
            ->where($data['staff'],$data['search_staff'])
            ->where('dj_day','between',[$data['start'],date('Y-m-d 23:59:59',strtotime($data['end']))])
            ->limit($limit)->page($page)
            ->select();
        $order = db('c_customerinfo')
            ->where($where)
            ->where('is_success',1)
            ->where($data['staff'],$data['search_staff'])
            ->where('order_day','between',[$data['start'],$data['end']])
            ->count('id');
        $rate = sprintf('%.2f',$order/$all*100).'%';
        if($all){
            return json(array('code'=>200,'mkz'=>$all,'order' => $order,'rate' => $rate,'limit'=>$limit,'page'=>$page,'list'=>getCustomerStatus($mkz)));
        }else{
            return json(array('code'=>100,'msg'=>'暂无数据','data'=>[],'sql'=>db()->getLastSql()));
        }
    }
    //查看本人转介绍客资
    public function selectSelfZJS($data){
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 2;
        $where['shop_code'] = $data['shop_code'];
        $data['staff'] = $data['staff'] ? trim($data['staff']) : 'dj_staff';
        $limit = $data['limit'] ? $data['limit'] : 10;
        $page = $data['page'] ? $data['page'] : 1;
        $all = db('c_customerinfo')
            ->where($where)
            ->where($data['staff'].'_id',$data['staff_id'])
            ->where('dj_day','between',[$data['start'],$data['end']])
            ->count('id');
        $mkz = db('c_customerinfo')
            ->where($where)
            ->where($data['staff'].'_id',$data['staff_id'])
            ->where('dj_day','between',[$data['start'],$data['end']])
            ->limit($limit)->page($page)
            ->select();
        $order = db('c_customerinfo')
            ->where($where)
            ->where('is_success',1)
            ->where($data['staff'].'_id',$data['staff_id'])
            ->where('order_day','between',[$data['start'],$data['end']])
            ->count('id');
        $rate = sprintf('%.2f',$order/$all*100).'%';
        return array(
            'mkz' => $all,
            'order' => $order,
            'rate' => $rate,
            'limit' => $limit,
            'page' => $page,
            'list' => getCustomerStatus($mkz),
        );
    }
    /*----------------转介绍--------end----------------------*/
    /*
     * 查询人员登录状态  show_login_status
     * token
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function show_login_status(){
        $data = input();
        if(empty($data['staff_id'])){
            return json(array('code'=>100,'msg'=>'未获取到员工ID'));
        }
        $info = getStaffInfoById($data['staff_id']);
        return json(array('code'=>200,'msg'=>'status:登录状态；1：在线；2：忙碌；3：隐身','status'=>$info['status'],'data'=>$info));
    }
    /*
     * 人员登录状态列表  staff_status_list
     * token
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * @param shop_code
     * @param department_id
     * @param main_position_code
     * */
    public function staff_status_list(){
        $data = input();
        if(empty($data['staff_id'])){
            return json(array('code'=>100,'msg'=>'未获取到员工ID'));
        }
        $p['shop_code'] = $data['shop_code'];
        if(check_right('menu1512637269')){ //查看所有客资权限

        }else{  //本人权限
            if($data['staff_id']){
                $p['id'] = $data['staff_id'];
            }
        }

        if($data['department_id']){
            $p['department_id'] = $data['department_id'];
        }
        if($data['main_position_code']){
            $p['main_position_code'] = $data['main_position_code'];
        }
        $mc = new \app\common\lib\mcInterface();
        $staff = $mc->getStaffInfo($p);
        $return = [];
        foreach($staff as $k=>$v){
            $staffInfo = getStaffInfoById($v['id']);
            $return[$k]['id'] = $v['id'];
            $return[$k]['staff_name'] = $v['staffname'];
            $return[$k]['main_position_name'] = $v['main_position_name'] ? $v['main_position_name'] : '';
            $return[$k]['department_name'] = $v['department_name'] ? $v['department_name'] : '';
            $return[$k]['status'] = $staffInfo['status'] ? $staffInfo['status'] : 0;
        }
        return json(array('code'=>200,'msg'=>'status:登录状态；1：在线；2：忙碌；3：隐身','data'=>$return));
    }
}