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

namespace app\index\controller;
use think\Controller;
use app\crm\lib\Target;
class App extends Controller
{
    protected $token = '';
    protected $staff_id = 0;
    public function _initialize() {
        $data = input();
        $this->token = $data['token'];
        $this->staff_id = $data['staff_id'];
        $info = checkAppLogin($this->staff_id,$this->token);
        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'];
            }
            // echo microtime(true).'line:'.__LINE__.'<br />';die;
            $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($info['main_position_code']){
                changeMyPosition($info['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('crm_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('crm_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));
    }
    /*
     * 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 = cache("staffInfo_".$param['staff_id']);
        if(empty($info)){
            if(!$info){
                $info = controller('crm/Customer','lib')->get_staff_info(array('staff_id'=>$param['staff_id']));//个人信息
                if(empty($info['data'])){
                    $data['code'] = 101;
                    $data['msg'] = '查看有误，无法获取当前员工信息';
                    return json($data);
                }
            }
        }else{
            $info['data'] = [
                'staff_id' => $info['staff_id'],
                'department_id' => $info['department_id'],
                'staffname' => $info['staffname'],
                'shop_code' => $info['shop_code'],
                'main_position_code' => $info['main_position_code'],
            ];
        }
        */

        $info['data'] = [
            'staff_id' => $param['staff_id'],
            'department_id' => $param['department_id'] ? $param['department_id'] : session('department_id'),
            'staffname' => $param['staff_name'] ? $param['staff_name'] : session('staff_name'),
            'shop_code' => $param['shop_code'] ? $param['shop_code'] : session('shop_code'),
            'main_position_code' => $param['main_position_code'] ? $param['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('crm_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 == '毛客资成本'){
                $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);
            }
        }
        return json(array('code'=>200,'data'=>$return));
    }
    /*
     * 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 = cache("staffInfo_".$param['staff_id']);
        if(empty($info)){
            if(!$info){
                $info = controller('crm/Customer','lib')->get_staff_info(array('staff_id'=>$param['staff_id']));//个人信息
                if(empty($info['data'])){
                    $data['code'] = 101;
                    $data['msg'] = '查看有误，无法获取当前员工信息';
                    return json($data);
                }
            }
        }else{
            $info['data'] = [
                'staff_id' => $info['staff_id'],
                'department_id' => $info['department_id'],
                'staffname' => $info['staffname'],
                'shop_code' => $info['shop_code'],
                'main_position_code' => $info['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('crm_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[$v] = $validDJ;
                }
                if($v == '有效新单'){
                    $validOrder = $tar->orderNumber($arr);
                    $return[$vv][$v] = $validOrder;
                }
                if($v == '总订单(订单开始时间)'){
                    $order = $tar->orderNumberStart($arr);
                    $return[$v] = $order;
                }
                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']);

        $staff_id = intval($param['staff_id']);

        $res = sx_call('5a01766b4a3dd', ['id'=>$staff_id]);
        if ($res['code'] == 200) {
            $shop_code = $res['data'][0]['shop_code'];
        }

        //录入必选项配置
        $lrMust = db_config('lr_must_'.$bid);
        $lrMust = trim($lrMust,',');
        $lrMust = $lrMust ? explode(',',$lrMust) : [];
        array_push($lrMust, 'customer_channel');
        if($param['customer_type'] ==2 && in_array('customer_channel',$lrMust)){
            foreach($lrMust as  $k=>$v){
                if($v == 'customer_channel'){
                    unset($lrMust[$k]);
                }
            }
        }
        // babypastel 定制 录入转介绍客资时 不使用 部门，使用设定的渠道
        $babypastel = customize('babypastel');
        $zjs_channel= 0;
        if ($babypastel) {
            $zjs_channel = 1;
        }

        //成都网销中心录入客资 ‘获取方式’为必填项
        if($shop_code == 'TSYX13' && !in_array('access_model',$lrMust)){
            $lrMust[] = 'access_model';
        }

        return json(array('code'=>200,'data'=>$lrMust,'zjs_channel'=>$zjs_channel));
    }
    /*
     * 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
     *       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:员工亲友转介绍
     *
     * */
    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'] = $info['shop_code'];
        $data['add_shop_name'] = $info['shop_name'];
        $data['shop_code'] = $param['shop_code'] ? $param['shop_code'] : ($info['belong_shop_code'] ? $info['belong_shop_code'] : $info['shop_code']);
        $data['shop_name'] = $param['shop_name'] ? $param['shop_name'] : ($info['belong_shop_name'] ? $info['belong_shop_name'] : $info['shop_name']);
        if(empty($data['shop_code'])){
            $returnData = array('code' => 100, 'msg' => '未获取到店面，不能提报');
            return json($returnData);
        }

        $data['brandclass_id'] = $param['brandclass_id'];
        $data['brandclass'] = $param['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_cource_id'] = intval($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['customer_channel_id'] = intval($param['customer_channel_id']);
        $data['customer_channel'] = trim($param['customer_channel']);
        if($data['customer_type'] == 2){
            $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']);
            // $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($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);
            }
            if(!is_array($param['baby_stature'])){
                $param['baby_stature'] = json_decode($param['baby_stature'],true);
            }
            if(!is_array($param['baby_weight'])){
                $param['baby_weight'] = json_decode($param['baby_weight'],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']);
        if(empty($data['customer_cource_id'])){
            $cusTypeId = $data['customer_type'] == 2?2:3;
            $source=controller("crm/Customer","lib")->source();
            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;
                        }
                    }
                }
            }
        }

        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['customer_wechat'] = $param['customer_wechat'][$i];
            $data['customer_qq'] = $param['customer_qq'][$i];
            $data['customer_remark'] = $param['customer_remark'][$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];
                $data['baby_stature'] = $param['baby_stature'][$i];
                $data['baby_weight'] = $param['baby_weight'][$i];
            // }else{
                $data['marry_day'] = $param['marry_day'][$i] ? $param['marry_day'][$i] : NULL;
            // }
            $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($data['shop_code']) || $data['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('crm_c_customerinfo',$value).'不能为空！'));
                }
            }
            $res = controller("crm/Customer", "lib")->addCustomer_child($data);
            /*
            if($info['shop_type'] == 2){
                $res = controller("crm/Customer", "lib")->addCustomer_child($data);
            }else{
                $res = controller("crm/Customer", "lib")->addCustomer($data);
            }
            */
            if($res['code'] == 201){
                $returnData = array('code' => 300, 'msg' => $res['msg']);
                return json($returnData);
            }
            if ($res['code'] == 200) {
                $customerInfo = db('crm_c_customerinfo')->where('id', $res['cutomer_id'])->find();
                $record['gtType'] = 4;
                $record['customer_id'] = $res['cutomer_id'];
                $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']);

                $record['sales_day'] = date('Y-m-d H:i:s', time());
                db()->startTrans();
                try {
                    db('crm_c_salestrackinginfo')->insert($record);
                    cache('getCustomerTrackInfos' . $res['cutomer_id'], null);
                    getSalesTracking($res['cutomer_id']);
                    //日志
                    // action_log($data,'', $res, $data['dj_staff_id'], $data['dj_staff']);
                    db()->commit();
                } catch (\Exception $e) {
                    db()->rollback();
                }
            } else {
                return json(array('msg' =>'客资 '.trim($data['customer_name']). ' 提报失败', 'code' => 100));
            }
        }
        return json(array('msg' => '提报成功', 'code' => 200,'customer_id'=>$res['cutomer_id']));
    }

    /*获取渠道
     *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(){
        $info = controller('crm/Customer','lib')->source();
        if(!empty($info)){
            return json(array('code'=>200,'data'=>$info));
        }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：进店流失
     *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',strtotime('-1 week'));
            $end_time=date('Y-m-d');
        }elseif($list_date == 'day'){
            $start_time=date('Y-m-d');
            $end_time=date('Y-m-d');
        }else{
            $start_time = date('Y-m-01');
            $end_time = date('Y-m-d');
        }

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

        $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'] = $data['all_time'] ? $data['all_time'] : 'dj_day';
        $data['sord'] = 'desc';
        
        $ret = controller('crm/Customer','lib')->customerListData($data);
        $info = getCustomerStatus($ret['new_rows']);
        foreach ($info as $key => $value) {
            $info[$key]['customer_tel'] = strip_tags($value['customer_tel']);
        }
        
        $count = $ret['records'];
        if(!empty($info)){
            $return = array('code'=>200,'data'=>$info,'count'=>$count);
        }else{
            $return = array('code'=>100,'msg'=>'暂无数据');
        }
        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('crm_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'] = '待定';
            }
        }
        // 追踪记录
        /*$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){
            $sales_remark=strip_tags($v['sales_remark']);
            $trackInfos[$k]['sales_remark']=preg_replace("/&nbsp;/si"," ",$sales_remark);
        }
        if(!empty($trackInfos)){
            $return = [];
            foreach ($trackInfos as $key => $value) {
                foreach ($value['track'] as $k => $v) {
                    array_push($return, $v);
                }
            }
            return json(array('code'=>200,'data'=>$return));
        }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
     *  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{
            $res = controller('crm/Customer','lib')->editSalesTracking($data);
        }
        // 清除追踪记录的缓存
        $unique = db('crm_c_customerinfo')->where('id',$data['customer_id'])->value('c_unique');
        cache('track_log_'.$unique,null);
        return json($res);
    }
    /*
   *网付订单页面  onlineOrderShow
   * id   客资id
   * staff_sn  人员编码
   * shop_code
   * shop_name
   * staff_id
   * staff_name
   * brandclass_id
   **/
    public function onlineOrderShow(){
        $param = input('post.');
        $id = $param['id'] ? (int)$param['id'] :0;
        if(empty($id)){
            return json(array('code'=>100,'msg'=>'未获取到客资id'));
        }
        $baby_sex = config('baby_sex');
        if(empty($baby_sex)){
            $baby_sex = [
                ['sex'=>'男',],
                ['sex'=>'女',],
            ];
        }
        $cusInfo = controller('crm/Customer', 'lib')->getCustomerInfo($id);
        $cusInfo['shop_code'] = $param['shop_code'];
        $cusInfo['shop_name'] = $param['shop_name'];
        $cusInfo['consulation_shop_code'] = $param['shop_code'];
        $cusInfo['sales_staff_id']= $param['staff_id'];
        $cusInfo['sales_staff']  = $param['staff_name'];
        $cusInfo['baby_birthday']= $cusInfo['baby_birthday'] ? date('Y-m-d', strtotime($cusInfo['baby_birthday'])) : '';
        $cusInfo['ready_baby_day']= $cusInfo['ready_baby_day'] ? date('Y-m-d', strtotime($cusInfo['ready_baby_day'])) : '';
        $cusInfo['marry_day']= $cusInfo['marry_day'] ? date('Y-m-d', strtotime($cusInfo['marry_day'])) : '';
        $sInfo = getStaffInfoById($param['staff_id']);
        //省
        $province = controller('crm/Customer','lib')->address(['type'=>1]);
        //拍照店
        $shop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>$param['brandclass_id'],'is_photo'=>1]);
        $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>2]);

        $shopInfo = getShopInfo();
        $param['ShopSn'] = $shopInfo[$param['shop_code']]['sn'];
        $param['StaffSN'] =  $param['staff_sn'];
        // var_dump(session('staff_sn'));
        // exit;
        $order_sn = $erpInterface->getOrderSn($param);
        //开单相关信息
        $orderInfo = $erpInterface->getCreateOrderInfo(['shop_code'=>$cusInfo['consulation_shop_code']]);
        // var_dump($orderInfo);
        // exit;
        $orderInfo['dt_s_packageset'] = my_sort($orderInfo['dt_s_packageset'],'package_price','SORT_ASC');
        foreach($orderInfo['dt_s_consumptiontype'] as $k=>$v){
            $orderInfo['dt_s_consumptiontype'][$k]['mustfill'] = trim($v['mustfill'],';');
        }
        //渠道
        $channel = controller('crm/Customer','lib')->getChannel();
        $this->assign('channel',$channel);
        //门市
        $rec = getShopStaffs(['shop_code'=>$cusInfo['consulation_shop_code'],'work_type'=>1]);
        //摄影师
        $cameraman = getShopStaffs(['shop_code'=>$cusInfo['consulation_shop_code'],'work_type'=>3]);
        //化妆师
        $dresser = getShopStaffs(['shop_code'=>$cusInfo['consulation_shop_code'],'work_type'=>7]);
        //引导师
        $mentor = getShopStaffs(['shop_code'=>$cusInfo['consulation_shop_code'],'work_type'=>25]);
        $data = [
            'baby_sex' => $baby_sex,
            'cusInfo' => $cusInfo,
            'staff_info' => $sInfo,
            'today' => date('Ymd'),
            'province' => $province,
            'shop' => $shop,
            'order_sn' => $order_sn,
            'orderInfo' => $orderInfo,
            'channel' => $channel,
            'rec' => $rec,
            'cameraman' => $cameraman,
            'dresser' => $dresser,
            'mentor' => $mentor,
            'dipian' => [
                [
                    'value' =>3,
                    'name' =>'赠送3张底片'
                ],
            ],
        ];
        return json(array('code'=>200,'data'=>$data));
    }
    /*
     * 网付订单
     * onlineOrder
     * customer_id  客资id
     * staff_id
     * staff_name
     * staff_number
     * staff_sn
     * shop_code
     * shop_name
     * setkey
     * brandclass_id
     * brandclass
     * 以上为登录时返回的
     *
     * target_time 开单时间
     * order_sn 单号
     * photo_shop_code
     * photo_shop_name   服务店面
     * consulation_shop_code
     * consulation_shop  订单店面
     * customer_name 妈妈姓名
     * customer_tel   妈妈手机
     * customer_wechat 妈妈微信
     * mate_name    爸爸姓名
     * mate_tel     爸爸手机
     * mate_wechat  爸爸微信
     * baby_name  宝宝姓名
     * baby_sex  宝宝性别
     * baby_birthday  宝宝生日
     * reception_id  门市id
     * reception_name  门市
     * sales_staff_id  追踪人id
     * sales_staff  追踪人
     * customer_area_id  分区
     * customer_cource_id  来源
     * customer_channel_id  渠道id
     * customer_channel  渠道名称
     * customer_orderaddress_id  接单点id
     * customer_orderaddress  接单点
     * mate_birthday  爸爸生日
     * customer_birthday  妈妈生日
     * package_name  套系名称
     * order_amount  套系金额
     * marry_day  结婚日期
     * ready_baby_day  预产期
     * babyhospital  出生医院
     * province_id
     * province  省
     * city_id
     * city  市
     * county_id
     * county  县区
     * customer_address 详细地址
     * consultation_type_id
     * consultation_type  消费类型
     * email  邮箱
     * order_note  订单备注
     * cameraman_id
     * cameraman  摄影师
     * Paymentmoney   实收金额
     * Paytype   付款方式
     * Duikuanma  付款编号
     * give_photo_num   赠送底片数量
     * */
    public function onlineOrder(){
        $param = input();
        
        $res = db('crm_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);
        }
        // var_dump(customize('whxaf'));die;
        if (customize('whxaf')) {
            $res = controller("erp/Erp")->zhuanOrderXaf($param);
        }else{
            $res = controller("erp/Erp")->zhuanOrder($param);
        }
        
        return json($res);
    }
    /*
     * 发送短信
     * appSendMsg
     * ids  客资id，多个用 ，隔开
     * send_msg 短信内容
     * receive_name 接收人 多个用 ，隔开
     * model_id  短信模板id
     * */
    public function appSendMsg(){
        $res = controller('crm/Customer','lib')->send_message(input());
        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('crm_s_reject_reason')->where('shop_code',$shop_code)->select();
        //追踪失败原因
        $allSet['reason'] = db('crm_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('crm_c_customerinfo')
                ->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('crm_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('crm_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);
        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);
        }
        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);
        return json($res);
    }
    /*
     * 标记有效 signValid
     * 参数：id  客资id
     * 返回值：array('code'=>200,'msg'=>'标记有效成功')
     * */
    public function signValid(){
        $id = input('param.id');
        $res = controller('crm/Customer','lib')->signValid($id);
        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);
        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('crm_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);
        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'] == 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
     * 获取部门下的小组  人员   调mc接口  0609
     * 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();
        if(empty($res)){
            $res = [];
        }
        $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));
        }
    }
    /*
     * 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;
            $staffs = cache('staffs_'.$shop_code.$department_id.$group_id.$method);
            if(empty($staffs)){
                $staffs = controller('crm/Customer','lib')->get_staff_lists($pram);
                cache('staffs_'.$shop_code.$department_id.$group_id.$method,$staffs);
            }
        }
        $day = getdateArea($time_area);
        //获取小组下的员工
        if($group_id){
            // 0606 
            $mc = new \app\common\lib\mcInterface();
            $groupStaffs = $mc->getStaffInfoByGid(array('group_id' => $group_id));
            unset($mc);
            // $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('crm_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);
            }
            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('crm_s_channel')->where($where)->page($page)->limit($limit)->field('id,channel_name,order_sort')->order('order_sort')->select();
        $info['count'] = db('crm_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('crm_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);
        return json($res);
    }
    /*
     *getShopStaffs
     * 获取店面下人员（登记人，追踪人，接待人,筛客人）
     * is_belong  登录后返回值有
     * brandclass_id
     * shop_code
     * token
     * flag dj:登记人；sales:追踪人;sk：筛客人；reception:接待人;camera:摄影师，huazhuang:化妆师，yindao:引导师，默认：登记人
     * 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'];
            $staff = getShopStaffs($p);
        }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 = getShopStaffs($p);
        }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'];
            $staff = getShopStaffs($p);
        }elseif($data['flag'] == 'camera'){
            $p['work_type'] = 3;
            $p['shop_code'] = $data['shop_code'];
            $staff = getShopStaffs($p);
        }elseif($data['flag'] == 'huazhuang'){
            $p['work_type'] = 7;
            $p['shop_code'] = $data['shop_code'];
            $staff = getShopStaffs($p);
        }elseif($data['flag'] == 'yindao'){
            $p['work_type'] = 25;
            $p['shop_code'] = $data['shop_code'];
            $staff = getShopStaffs($p);
        }else{
            if($data['is_belong'] == 1){
                $staff = controller("crm/Customer","lib")->get_staff_lists();
            }elseif($data['is_belong'] == 2){
                $staff = controller("crm/Customer","lib")->get_staff_lists(array('brandclass_id'=>$data['shop_code']));
            }else{
                $staff = controller("crm/Customer","lib")->get_staff_lists(array('shop_code'=>$data['shop_code']));
            }
        }
        return json(array('code'=>200,'data'=>$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
     * type 2:市，3：区县
     * */
    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']= $data['type'] ? $data['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('crm_s_menu')->field('menu_code,menu_name')->select();
            return json(array('code'=>200,'data'=>$info));
        }
        $menu = db('crm_s_position_menu')->where('position_code',$data['main_position_code'])->value('menu_code');
        $menu = explode(',',$menu);
        $info = db('crm_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 = cache('staffInfo_'.$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));
    }
    /*-------------------- 报表 --------------------*/
    /*
     *报表入口
     */
    public function report(){
        // 报表ID即报表类名（lib/report/$id）
        // var $id = input('get.id');
        $id = strtolower(input('param.id'));

        // 通过反射类，判断该类是否存在
        if(!class_exists('app\\crm\\lib\\report\\'.ucwords($id) ) ) {
            echo '没有发现这个类：'.$id."\r\n";
            exit();
        }
        $instance = new \ReflectionClass('app\\crm\\lib\\report\\'.ucwords($id));
        $method = 'show';
        if (!$instance->hasMethod($method)) {
            echo '没有发现这个方法：'.$method."\r\n";
            exit();
        }

        $objMethod = $instance->getMethod($method);

        $handle = $instance->newInstance();
        
        $display = $objMethod->invokeArgs($handle,array());
        return $display;
    }
    // 报表数据
    public function data(){
        $data = input();
        $id = strtolower($data['id']);
        // 通过反射类，判断该类是否存在
        if(!class_exists('app\\crm\\lib\\report\\'.ucwords($id))){
            echo '没有发现这个类：'.ucwords($data['id'])."\r\n";
            exit();
        }
        $instance = new \ReflectionClass('app\\crm\\lib\\report\\'.ucwords($id));
        $method = 'data';
        if (!$instance->hasMethod($method)) {
            echo '没有发现这个方法：'.$method."\r\n";
            exit();
        }

        $objMethod = $instance->getMethod($method);

        $handle = $instance->newInstance();

        $display = $objMethod->invokeArgs($handle,$data);
        return $display;
    }
}