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

    }

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

        try{
            db('api_logs','db_logs')->insert($log);
        }catch (\Exception $e){
            \think\Log::error('接口日志保存错误:module:'.$this->module.';controller:'.$this->controller.';action:'.$this->action.';data:'.json_encode($this->data).";error:".$e->getMessage());
        }
    }


    //二级渠道
    public function getErChannel($shop_code=''){
        $shop_code = $shop_code ?: session('shop_code');

        $res = controller("crm/Customer","lib")->getErChannel($shop_code);
        if (count($res) > 0) {
            foreach ($res as $key => $value) {
                $res[$key]['id'] = $value['channel_info_id'];
                $res[$key]['name'] = $value['channel_info_name'];
            }
        }
        return $res;
    }
        
    /*获取渠道
     *getChannel
     * 参数：shop_code 
     * */
    public function getChannel($shop_code='',$staff_id='',$channel_info_id=''){
        $shop_code = $shop_code ?: session('shop_code');

        $res =  controller('crm/Customer','lib')->getChannel($shop_code,$staff_id,$channel_info_id);
        if (count($res) > 0) {
            foreach ($res as $key => $value) {
                $res[$key]['name'] = $value['channel_name'];
            }
        }
        return $res;
    }
    /*
     * getAccessModel
     * 获取获取方式
     * */
    public function getAccessModel(){
        $res = controller('crm/Customer','lib')->accessModel();
        if (count($res) > 0) {
            foreach ($res as $key => $value) {
                $res[$key]['name'] = $value['accessmodel'];
            }
        }
        return $res;
    }
    /*
     * getConsumptionType
     * 获取消费类型
     * brandclass_id
     * */
    public function getConsumptionType($brandclass_id=''){
        $brandclass_id = $brandclass_id ?: session('brandclass_id');
        $res = controller('crm/Customer','lib')->consumptionType(['brandclass_id'=>$brandclass_id]);
        if (count($res) > 0) {
            foreach ($res as $key => $value) {
                $res[$key]['name'] = $value['consumption_name'];
            }
        }
        return $res;
    }
    /*
     * getSource
     * 获取客户来源
     * */
    public function getSource(){
        $res = controller('crm/Customer','lib')->source();
        if (count($res) > 0) {
            foreach ($res as $key => $value) {
                $res[$key]['name'] = $value['cus_name'];
            }
        }
        return $res;
    }
    /*
     * getIntention
     * 获取客户意向
     * */
    public function getIntention(){
        return controller('crm/Customer','lib')->intention();
    }
    //当前人可操作店
    public function getOperateShop()
    {
        $shops = [];
        $p = [
            'staff_id'=> session('staff_id'),
            'brandclass_id'=> session('brandclass_id'),
            'shop_type' => 1 //婚纱
        ];
        return getShops($p);//可操作店
    }
    //客资标记
    public function getTracksign()
    {
        $res = controller("crm/Setting","lib")->gettrackingKmarkerList();
        if (count($res) > 0) {
            foreach ($res as $key => $value) {
                $res[$key]['name'] = $value['tracksign'];
            }
        }
        return $res;
    }

    //进客标记
    public function getincomingSign($shop_code='')
    {
        $erp = config('ext.app_config');  //读取erp配置文件
        $addr = $erp['sx_erp']['addr'];   //调用url
        $api_json['Token'] = $this->token_appwxerp;
        $api_json['Code'] = $shop_code?:session('shop_code');

        //客户分区
        $url_area =trim($addr,'/').'/APP_ERPChildApi/APP_JinKeBiaoJiSet'; //定义拼接url
        $incoming = requestWXERP($url_area,$api_json);
        $incomings = $incoming['Data']?:[];
        return $incomings;
    }

    //宝宝性别
    public function getBabySex()
    {
        // 宝宝性别
        $baby_sex = config('baby_sex');
        if(empty($baby_sex)){
            $baby_sex = [
                ['sex'=>'男',],['sex'=>'女',],
            ];
        }
        foreach ($baby_sex as $key => $value) {
            $baby_sexs[$key]['id'] = $key;
            $baby_sexs[$key]['name'] = $value['sex'];
        }
        return $baby_sexs;
    }








    /*
     * customerAdd
     * 客资提报界面
     * staff_id
     * brandclass_id
     * customer_type 1:新客资;2:转介绍
     * token
     * */
    public function customerAdd(){
        $param = input();
        $bid = $param['brandclass_id'] ? intval($param['brandclass_id']) : session('brandclass_id');
        //录入必选项配置
        $lrMust = db_config('lr_must_'.$bid);
        $lrMust = trim($lrMust,',');
        $lrMust = explode(',',$lrMust);
        if($param['customer_type'] ==2 && in_array('customer_channel',$lrMust)){
            foreach($lrMust as  $k=>$v){
                if($v == 'customer_channel'){
                    unset($lrMust[$k]);
                }
            }
        }

        // $channel = $this->getChannel(session('shop_code'));
        $erchannel = $this->getErChannel(session('shop_code'));
        $accessModel = $this->getAccessModel();
        $consumptionType = $this->getConsumptionType($bid);
        $source = $this->getSource();

        // 宝宝性别
        $baby_sex = $this->getBabySex();

        $hidden = db_config('lr_hidden_'.session('brandclass_id'));
        $hidden = trim($hidden,',');
        $hidden = explode(',',$hidden);

        // 客资标记 是否隐藏
        if ( !in_array('tracksign',$hidden) ) {
            $tracksign= $this->getTracksign();
        }

        return json(array(
            'lrMust'=>$lrMust,
            'erchannel'=>$erchannel,
            'accessModel'=>$accessModel,
            'consumptionType'=>$consumptionType,
            'source'=>$source,
            'baby_sex'=>$baby_sex,
            'tracksign'=>$tracksign
        ));
    }
    //获取三级渠道
    public function getChannels()
    {
        $param = input();
        $channel = $this->getChannel($param['shop_code'],$param['staff_id'],$param['channel_info_id']);
        return json($channel);
    }

    /*
     * 转介绍--介绍人搜索 introSearch
     * 参数：customer_name  搜索内容：手机
     * 返回值：array('code'=>200,'data'=>'数据')
     * */
    public function introSearch(){
        $data = input();
        $res = controller("crm/Customer","lib")->customerNameSearchAppwx(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);
    }


    /*客资提报
     * 参数：staff_id 员工id  必填
     *       customer_name[]  客户姓名
     *       customer_sex[]  客户性别
     *       customer_tel[]  客户手机
     *       customer_wechat[]  客户微信
     *       customer_qq  客户qq
     *       add_shop_code 提报店code
     *       add_shop_name 提报店name
     *       shop_code 归属店code 选填：转介绍必填
     *       shop_name 归属店name 选填：转介绍必填
     *       customer_remark 客户备注 选填
     *       customer_type 1:新客资;2:转介绍
     *       introducer_name 介绍人姓名 选填  老顾客转介绍必填
     *       introducer_tel  介绍人手机 选填 老顾客转介绍必填
     *       introducer_ordernum 介绍人单号 选填  老顾客转介绍必填
     *       introducer_number   介绍人编号 选填  老顾客转介绍必填
     *       baby_birthday       宝宝生日
     *       baby_address        出生医院
     *       marray_day          结婚日期
     *       customer_channel_id 渠道id 必填    转介绍时不用展示，默认当前部门
     *       customer_channel 渠道id    必填    转介绍时不用展示，默认当前部门
     *       consultation_type_id   消费类型id
     *       consultation_type      消费类型
     *       customer_cource_id
     *       customer_cource        来源
     *       access_model_id        获取方式id
     *       access_model           获取方式
     *       zjs_from          转介绍类型 :   1:老顾客转介绍;2:员工亲友转介绍
     *       sales_staff_id    追踪人id
     *       sales_staff    追踪人
     *
     * */
    public function addNewCustomer(){
        $param = input('param.');
        //删除二级渠道
        unset($data['channel_info_id']);

        if(empty($param['staff_id'])){
            $returnData = array('code' => 101, 'msg' => '未获取到操作人ID');
            return json($returnData);
        }

        foreach ($param as $key => $value) {
            $param[$key] = $value == "请选择" ? '' : $value;
        }

        $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' => 102, 'msg' => '未获取到店面，不能提报');
            return json($returnData);
        }

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

        //意向店面
        $data['consulation_shop_code'] = trim($param['consulation_shop_code']);
        $data['consulation_shop'] = trim($param['consulation_shop']);
        //渠道
        $data['customer_channel_id'] = intval($param['customer_channel_id']);
        $data['customer_channel'] = trim($param['customer_channel']);
        //来源
        $data['customer_cource_id'] = trim($param['customer_cource_id']);
        $data['customer_cource'] = trim($param['customer_cource']);
        //客户意向
        // $data['customer_intention_id'] = intval($param['customer_intention_id']);
        // $data['customer_intention'] = trim($param['customer_intention']);
        //消费类型
        $data['consultation_type_id'] = intval($param['consultation_type_id']);
        $data['consultation_type'] = trim($param['consultation_type']);
        //获取方式
        $data['access_model_id'] = intval($param['access_model_id']);
        $data['access_model'] = trim($param['access_model']);
        //1:新客资;2:转介绍
        $data['customer_type'] = intval($param['customer_type'])?:1;
        $customer_type_name = intval($param['customer_type'])==2?'转介绍':'新客资';

        $data['sales_staff_id'] = $param['sales_staff_id'] ? intval($param['sales_staff_id']) : NULL;
        $data['sales_staff'] = $param['sales_staff'] ? $param['sales_staff'] : NULL;

        //转介绍客资 渠道是部门
        if($data['customer_type'] == 2 && !trim($param['customer_channel'])){
            $data['introducer_name'] = trim($param['introducer_name']);
            $data['introducer_tel'] = trim($param['introducer_tel']);
            $data['introducer_ordernum'] = trim($param['introducer_ordernum']);
            // $data['customer_channel_id'] = intval($param['department_id']);
            // $data['customer_channel'] = trim($param['department_name']);
        }

        if($param['customer_type'] == 2){
            if(!$param['zjs_from']){
                return json(array('code'=>103,'msg'=>'转介绍时必须选择类型'));
            }
            //转介绍类型 :   1:老顾客转介绍;2:员工亲友转介绍
            $data['zjs_from'] = $param['zjs_from'];
        }

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

        $param['customer_name'] = explode("<,>",trim($param['customer_name'],"<,>"));
        $param['customer_tel'] = explode("<,>",trim($param['customer_tel'],"<,>"));
        $param['customer_wechat'] = explode("<,>",trim($param['customer_wechat'],"<,>"));
        // $param['marry_day'] = $param['wedding_date'];//explode("<,>",trim($param['marry_day'],"<,>"));
        $param['baby_name'] = explode("<,>",trim($param['baby_name'],"<,>"));
        $param['baby_birthday'] = explode("<,>",trim($param['baby_birthday'],"<,>"));
        $param['ready_baby_day'] = explode("<,>",trim($param['ready_baby_day'],"<,>"));
        $param['baby_sex'] = explode("<,>",trim($param['baby_sex'],"<,>"));
        $param['customer_remark'] = explode("<,>",trim($param['customer_remark'],"<,>"));

        $count = count($param['customer_name']);//提报客资数量

        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'])){
                return json(['code' => 301, 'msg' => $customer_type_name.($i+1).'的妈妈姓名不能为空']);
            }
            $data['customer_tel'] = $param['customer_tel'][$i];
            if(empty($data['customer_tel']) && empty($param['customer_wechat'][$i])){
                return json(['code' => 302, 'msg' => $customer_type_name.($i+1).'的妈妈手机号微信号至少填定一个']);
            }
            if($data['customer_tel'] && !preg_match("/^1[3|4|5|6|7|8|9][0-9]{9}$/", $data['customer_tel'])){
                return json(['code' => 303, 'msg' => $customer_type_name.($i+1).'的【'.$data['customer_tel'].'】手机号格式错误']);
            }

            $data['customer_wechat'] = $param['customer_wechat'][$i];
            $data['customer_qq'] = $param['customer_qq'][$i];
            
            $data['baby_birthday'] = $param['baby_birthday'][$i];
            $data['ready_baby_day'] = $param['ready_baby_day'][$i];
            $data['customer_remark'] = $param['customer_remark'][$i];
            // $data['customer_remark'] = $param['customer_remark'][$i].($param['img'][$i] ? '<img src="'.$param['img'][$i].'">' : '');
            //推广编号
            // $data['channel_plan_number'] = $param['channel_plan_number'][$i];
            // $data['customer_qq'] = $param['customer_qq'][$i];
            
            $data['baby_name'] = $param['baby_name'][$i];
            $data['baby_sex'] = $param['baby_sex'][$i];

            //录入必选项配置
            $lrMust = db_config('lr_must_'.session('brandclass_id'));
            $lrMust = trim($lrMust,',');
            $lrMust = $lrMust ? explode(',',$lrMust) : [];
            // foreach($lrMust as $key=>$value){
            //     if(empty($data[$value]) || !$data[$value] || $data[$value] == '' || $data[$value] == 'undefined'){
            //         return json( array('code' => 100, 'msg' => translate('c_customerinfo',$value).'不能为空！'));
            //     }
            // }

            /*
            //查询归属地是否筛客
            $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'];
                        }
                    }
                }*
            }*/

            // 省市区
            $data['province'] = $param['province'][$i] ? $param['province'][$i] : null;
            $data['province_id'] = $param['province_id'][$i] ? $param['province_id'][$i] : null;
            $data['city'] = $param['city'][$i] ? $param['city'][$i] : null;
            $data['city_id'] = $param['city_id'][$i] ? $param['city_id'][$i] : null;
            $data['county'] = $param['county'][$i] ? $param['county'][$i] : null;
            $data['county_id'] = $param['county_id'][$i] ? $param['county_id'][$i] : null;

            $res = controller("crm/Customer", "lib")->addCustomer_child($data);
            
            if($res['code'] == 200){
                $this->data = input();
            }else{
                $this->data = array_push(input(),['error'=>$res['data']]);
            }
            $this->result_code = $res['code'];
            $this->appApiLog();

            if($res['code'] == 201){
                $returnData = array('code' => 300, 'msg' => $res['msg']);
                return json($returnData);
            }
            if ($res) {
                $customerInfo = db('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'][$i]);
                // $record['sales_remark'] = '手机APP录入 ' . trim($param['customer_remark'][$i]).'<img src="'.$param['img'][$i].'">';
                // if($param['img'][$i]){
                //     $record['sales_remark'] .= '<img src="'.$param['img'][$i].'">';;
                // }

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

    //列表 时间，店面，客资状态，（进店，成交），分配状态 通过提报日期,关键词,客资状态筛选,数据返回格式:客资返回列表 分页加载
    /*customerList
     * all_time dj_day:录入时间,
     *           jr_day:接入时间,
     *           create_time:获取时间,
     *           fp_day:分配时间,
     *           next_time:再约时间,
     *           yjd_action_day:预约操作时间,
     *           yjd_day:预约进店时间,
     *           syjd_day:时间进店时间,
     *           order_start_time:订单开始时间,
     *           order_day:成交时间,
     *           c_star_day:追踪开始时间,
     *           last_trackday:最后追踪时间,
     *           yx_day:转有效时间,
     *           sign_time:标记时间
     * start    开始时间
     * end    结束时间
     * staff_id
     * search    查询关键字
     * shop_code    店面
     * customer_channel 渠道
     * dj_staff_id      录入人
     * sales_staff_id   追踪人
     * is_loss       不再追踪 1:是；2：否
     * is_success    成交状态；1：已成交；2未成交；3：已定金;4:本单作废
     * is_valid      客资状态；1：有效；2：待定；3：无效；4：驳回；5：反驳回
     * is_fp         分配状态；1：已分配；2：未分配；3：待接收；4：分配失败；
     * is_intostore  进店状态；1：未进店；2：进店进客；3：进店非进客;4:邀约流失；5：进店流失
     * type_info 类似pc端更多里的条件 追踪部门
     * limit          每页条数
     * page             页数
     * 返回值：
     *  code 200
     *  data
     * */
    public function customerList(){
        $data = input();

        $data['rows'] = $data['limit'] ? intval($data['limit']) : 10;
        $data['page'] = $data['page'] ? intval($data['page']) : 1;

        $data['more_like'] = $data['search'] ? trim($data['search']) : '';

        $data['tab'] = $data['tab'] ? $data['tab'] : 1;
        $data['all_time'] = $data['all_time'] ? $data['all_time'] : 'dj_day';
        $data['start_time'] = $data['start_time'] ? date("Y-m-d",strtotime($data['start_time'] )): date("Y-m-d");
        $data['end_time'] = $data['end_time'] ? date("Y-m-d 23:59:59",strtotime($data['end_time'] )): date("Y-m-d 23:59:59");

        $data['is_valid'] = $data['is_valid'] != '' ?$data['is_valid']: '2,1,3,4,5';
        $data['is_loss'] = $data['is_loss'] != '' ?$data['is_loss']: 2;

        $datas = $data;
        $datas['end_time'] = date("Y-m-d",strtotime($datas['end_time'] ));
        unset($datas['api_code'],$datas['api_type'],$datas['api_url'],$datas['configuration'],$datas['page'],$datas['token'],$datas['rows'],$datas['tab']);

        if($data['dj_group_id']){
            $data['type_info'] .= 'dj_group_id='.$data['dj_group_id'].",";
            unset($data['dj_group_id']);
        }
        if($data['shop_code']){
            $data['type_info'] .= 'shop_code='.$data['shop_code'].",";
            unset($data['shop_code']);
        }
        if($data['sales_department_id']){
            $data['type_info'] .= 'sales_department_id='.$data['sales_department_id'].",";
            unset($data['sales_department_id']);
        }
        if($data['sales_group_id']){
            $data['type_info'] .= 'sales_group_id='.$data['sales_group_id'].",";
            unset($data['sales_group_id']);
        }
        if($data['sales_staff_id']){
            $data['type_info'] .= 'sales_staff_id='.$data['sales_staff_id'].",";
            unset($data['sales_staff_id']);
        }
        $data['type_info'] = trim($data['type_info'],",");

        $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']);
        }

        $checkboxData = [];
        foreach ($info as $key => $value) {
            $ch['text'] = '';
            $ch['value'] = $value['id'];
            array_push($checkboxData, [$ch]);
        }

        $count = $ret['records'];
        if(!empty($info)){
            $return = array('code'=>200,'data'=>$info,'count'=>$count,'sql'=>$ret['sql'],'param'=>$datas,'checkboxData'=>$checkboxData,'cookie'=>$_COOKIE);
        }else{
            $return = array('code'=>100,'msg'=>'没有更多数据了','sql'=>$ret['sql'],'param'=>$datas);
        }
        return json($return);
    }
    //客资列表 更多条件
    public function customerConditon(){
        $data = input();

        $mc = new \app\common\lib\mcInterface();

        //日期类型
        $dataType = getCustomerDataType();

        //二级渠道
        $channel_info = $mc->getChannelInfo();
        foreach ($channel_info as $key => $value) {
            $channel_info[$key]['name'] = $value['channel_name'];
        }
        array_unshift($channel_info,['id'=>'','name'=>'全部']);

        //来源渠道
        $channel = $this->getChannel(session('shop_code'));
        array_unshift($channel,['id'=>'','name'=>'全部']);

        //客资类型
        $KZType = getCustomerKZType();
        array_unshift($KZType,['id'=>'','name'=>'全部']);

        // 登记店面 取 当前账号的可操作店
        $djParam = [
            'staff_id'=> session('staff_id'),
            'brandclass_id'=> session('brandclass_id'),
            'shop_type' => 2
        ];
        $shop = getShops($djParam);
        $shops = [];
        if (count($shop) > 0) {
            $i = 0;
            foreach ($shop as $key => $value) {
                $shops[$i]['name'] = $value['shop_name'];
                $shops[$i]['id'] = $value['shop_code'];
                $i++;
            }
        }

        $add_department = $add_group = $add_staff = [];
        if($data['add_shop_code']){
            $add_department = $mc->getDepartment(array('shop_code'=>$data['add_shop_code']));
            foreach ($add_department as $key => $value) {
                $add_department[$key]['name'] = $value['department_name'];
            }
        }
        if($data['add_department']){
            $gParam['department_id'] = $data['add_department'];
            $gParam['staff_id'] = session('staff_id');
            $group = $mc->getGroupInfo($gParam);
            $add_group = [];
            foreach ($group as $key => $value) {
                $temp['id'] = $value['id'];
                $temp['name'] = $value['group_name'];
                array_push($add_group,$temp);
            }

            $mcParam['shop_code'] = $data['add_shop_code'] ?: session('shop_code');
            $mcParam['department_id'] = $data['add_department'];
            $add_staff = $mc->getStaffInfo($mcParam);
            foreach ($add_staff as $key => $value) {
                $add_staff[$key]['name'] = $value['staffname'];
            }
        }
        if($data['add_group']){
            $add_staff = $mc->getStaffByDepartment(['group_id'=>$data['add_group']]);
            foreach ($add_staff as $key => $value) {
                $add_staff[$key]['name'] = $value['staffname'];
            }
        }

        $sales_department = $sales_group = $sales_staff = [];
        if($data['sales_shop_code']){
            $sales_department = $mc->getDepartment(array('shop_code'=>$data['sales_shop_code']));
            foreach ($sales_department as $key => $value) {
                $sales_department[$key]['name'] = $value['department_name'];
            }
        }
        if($data['sales_department']){
            $gParams['department_id'] = $data['sales_department'];
            $gParams['staff_id'] = session('staff_id');
            $groups = $mc->getGroupInfo($gParams);
            $sales_group = [];
            foreach ($groups as $key => $value) {
                $temps['id'] = $value['id'];
                $temps['name'] = $value['group_name'];
                array_push($sales_group,$temps);
            }

            $mcParam['shop_code'] = $data['sales_shop_code'] ?: session('shop_code');
            $mcParam['department_id'] = $data['sales_department'];
            $sales_staff = $mc->getStaffInfo($mcParam);
            foreach ($sales_staff as $key => $value) {
                $sales_staff[$key]['name'] = $value['staffname'];
            }
        }
        if($data['sales_group']){
            $sales_staff = $mc->getStaffByDepartment(['group_id'=>$data['sales_group']]);
            foreach ($sales_staff as $key => $value) {
                $sales_staff[$key]['name'] = $value['staffname'];
            }
        }

        return json([
            'add_department'=>$add_department,
            'add_group'=>$add_group,
            'add_staff'=>$add_staff,
            'sales_department'=>$sales_department,
            'sales_group'=>$sales_group,
            'sales_staff'=>$sales_staff,
            "all_time"=>$dataType,
            "add_shop"=>$shops,
            "sales_shop"=>$shops,
            "channel"=>$channel,
            "KZType"=>$KZType,
            "channel_info"=>$channel_info
        ]);
    }
    public function customerConditons(){
        $input = input('param.');
        $staff = [];

        $mc = new \app\common\lib\mcInterface();
        //选完店后
        if ($input['key'] == 'add_shop' || $input['key'] == 'sales_shop') {
            $res = $mc->getDepartment(array('shop_code'=>$input['text']));
            foreach ($res as $key => $value) {
                $res[$key]['name'] = $value['department_name'];
            }
        }

        //选完部门后
        if ($input['key'] == 'add_department' || $input['key'] == 'sales_department') {
            $gParam['department_id'] = $input['text'];
            $gParam['staff_id'] = session('staff_id');
            $group = $mc->getGroupInfo($gParam);
            $res = [];
            foreach ($group as $key => $value) {
                $temp['id'] = $value['id'];
                $temp['name'] = $value['group_name'];
                array_push($res,$temp);
            }

            $mcParam['shop_code'] = $input['shop'] ?: session('shop_code');
            $mcParam['department_id'] = $input['text'];
            $staff = $mc->getStaffInfo($mcParam);
            foreach ($staff as $key => $value) {
                $staff[$key]['name'] = $value['staffname'];
            }
        }

        //选完小组后
        if ($input['key'] == 'add_group' || $input['key'] == 'sales_group') {
            $res = $mc->getStaffByDepartment(['group_id'=>$input['text']]);
            foreach ($res as $key => $value) {
                $res[$key]['name'] = $value['staffname'];
            }
        }

        //选完二级渠道
        if ($input['key'] == "channel_info"){
            $channel = $this->getChannel(session('shop_code'),'',$input['text']);
            array_unshift($channel,['id'=>'','name'=>'全部']);
        }


        return json(['res'=>$res,'staff'=>$staff,'channel'=>$channel]);
    }




    /*
     * getBrandclass
     * 分配时 页面
     * staff_id
     *
     * */
    public function getBrandclass(){
        $data = input();
        $shops = $this->getOperateShop();
        $res['shop_code'] = $data['shop_code'] ?: session('shop_code');

        $mc = new \app\common\lib\mcInterface();
        $departmentList = $mc->getDepartment($res);
        $departmentList = array_combine(array_column($departmentList,'id'),$departmentList);
        $res['department_id'] = session('department_id');

        $staffs = $this->getFpStaffs($res);

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

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

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

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

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

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

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

        return $return;
    }
    /*
     * appFP
     * 分配
     * cid 多个 ，隔开
     * staff_id
     * shop_code
     * shop_name
     * */
    public function appFP(){
        $param = input();
        $date = date('Y-m-d H:i:s',time());
        $sid  = $param['sales_staff_id'];
        if(empty($sid)){
            return json(array('code'=>100,'msg'=>'未获取到接收人ID'));
        }
        //如果追踪人已经是要分配的人，去掉
        $sales = db('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);
            }
            if($return['code'] == 200){
                $this->data = input();
            }else{
                $this->data = array_push(input(),['error'=>$return['data']]);
            }
            $this->result_code = $return['code'];
            $this->appApiLog();
            return json($return);
        }
    }




    /*
     * 客资详情+追踪记录
     * 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) {
            $info['status'] = getIsValidAttr($info['is_valid']);
        }
        $pattern = '<img.*?src="(.*?)">';
        preg_match($pattern,$info['customer_remark'],$img);
        // preg_match("/ src=([\"'])([^\\1]*)\\1/", $info['customer_remark'], $img);
        if(!empty($img[1])){
            $info['customer_remark_img'] = $img[1];
        }else{
            $info['customer_remark_img'] = '';
        }
        $info['customer_remark'] = strip_tags($info['customer_remark']);
        $info['baby_birthday'] = $info['baby_birthday'] ? substr($info['baby_birthday'], 0,10) : '';
        $info['ready_baby_day'] = $info['ready_baby_day'] ? substr($info['ready_baby_day'], 0,10) : '';

        //驳回原因
        $reject = db('crm_s_reject_reason')->where('shop_code',session('shop_code'))->select();

        $erp = is_install('sx_erp');
        if ($erp) {
            $erps = 1;  // 安装erp
        }else{
            $erps = 2;  // 未安装erp
        }
        // $info['order_number'] 订单单号 判断 是否已转单

        $channel = $this->getChannel(session('shop_code'));
        $accessModel = $this->getAccessModel();
        $consumptionType = $this->getConsumptionType(session('brandclass_id'));
        $source = $this->getSource(); //获取客户来源

        // 宝宝性别
        $baby_sex = $this->getBabySex();

        return json(array(
            'code'=>200,
            'data'=>$info,
            'reject'=>$reject,
            'erp'=>$erps,
            'channel'=>$channel,
            'accessModel'=>$accessModel,
            'consumptionType'=>$consumptionType,
            'source'=>$source,
            'baby_sex'=>$baby_sex
        ));
    }
    /*
     * getTrackLog
     * 追踪记录
     * id
     * */
    public function getTrackLog(){
        $id = input('param.id');
        if(empty($id)){
            return json(array('code'=>100,'msg'=>'未获取到客资ID'));
        }
        $trackInfos = controller("crm/Customer","lib")->getCustomerTrackInfos($id);
        foreach($trackInfos as $k=>$v){
            $pattern = '<img.*?src="(.*?)">';
            preg_match($pattern,$v['sales_remark'],$img);
            // preg_match("/ src=([\"'])([^\\1]*)\\1/", $v['sales_remark'], $img);
            if($img[1]){
                $trackInfos[$k]['sales_remark_img'] = $img[1];
            }else{
                $trackInfos[$k]['sales_remark_img'] = '';
            }

            $sales_remark=strip_tags($v['sales_remark']);
            $trackInfos[$k]['sales_remark']=preg_replace("/&nbsp;/si"," ",$sales_remark);

            if($k == $id){
                foreach ($v['track'] as $kk => $vv) {
                    $trackInfos[$k]['track'][$kk]['sales_remark'] = strip_tags($vv['sales_remark']);
                }
            }
        }
        if(!empty($trackInfos)){
            return json(array('code'=>200,'data'=>$trackInfos[$id]));
        }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'=>'未找到数据'));
        }
    }

    /*
     * 标记有效 signValid
     * 参数：id  客资id
     * 返回值：array('code'=>200,'msg'=>'标记有效成功')
     * */
    public function signValid(){
        $id = input('param.id');
        $res = controller('crm/Customer','lib')->signValid($id);
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    /*
     * 标记无效 signUnValid
     * 参数：id  客资id
             unvalid_id  无效原因id
             unvalid_reason  无效原因
     * 返回值：array('code'=>200,'msg'=>'标记无效成功')
     * */
    public function signUnValid(){
        $data = input();
        $res = controller('crm/Customer','lib')->signUnValid($data);
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    //客资修改
    public function customerInfo(){
        $data = input();

        if (!$data['id']) {
            $returnData = array('code' => 100,'msg' =>'用户ID数据为空，请重试');
            return json($returnData);
        }
        unset($data['api_url'],$data['api_type'],$data['configuration'],$data['token'],$data['api_code'],$data['staff_name'],$data['staff_id']);

        $res = controller("crm/Customer","lib")->getCustomerInfoEdit($data);

        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }

    /*
     * getSalesMust
     * 追踪页面 获取追踪必选项配置
     * staff_id
     * */
    public function getSalesMust(){
        $param = input();

        $info = db('c_customerinfo')->where('id',$param['id'])->find();
        $info['customer_remark'] = strip_tags($info['customer_remark']);
        $info['yp_day'] = $info['yp_day'] ? substr($info['yp_day'],0,10) : '';
        $info['next_time'] = $info['next_time'] ? substr($info['next_time'],0,10) : '';
        $info['is_valid'] = getIsValidAttr($info['is_valid']);
        $info['sales_remark'] = '';
        $info['id'] = $param['id'];

        $bid = $param['brandclass_id'] ? intval($param['brandclass_id']) : session('brandclass_id');
        //追踪必选项配置
        $dfMust = db_config('df_must_'.$bid);
        $dfMust = explode(',',$dfMust);
        //追踪选项隐藏配置
        $dfHidden = db_config('df_hidden_'.$bid);
        $dfHidden = explode(',',$dfHidden);

        // 客资标记 是否隐藏
        $tracksign = [];
        if ( !in_array('sign_id',$dfHidden) ) {
            $tracksign = $this->getTracksign();
            foreach ($tracksign as $key => $value) {
                $tracksign[$key]['name'] = $value['tracksign'];
            }
        }

        // 客资状态 有效无效等
        $validArr = [];
        if(check_right('menu1546854995')){
            $temp['id']  = 1;
            $temp['name']= '有效';
            $validArr[] = $temp;
        }
        // 标记待定
        $temp['id']  = 2;
        $temp['name']= '待定';
        $validArr[] = $temp;
        // 标记无效
        if(check_right('menu1517129331')){
            $temp['id']  = 3;
            $temp['name']= '无效';
            $validArr[] = $temp;
        }

        // 无效原因 20210225
        $unValidReason = controller('crm/Customer','lib')->getUnValidReason();
        foreach ($unValidReason as $key => $value) {
            $unValidReason[$key]['name'] = $value['reason'];
        }
        
        // 追踪标记 op_signinfo
        $mark = controller("crm/Customer","lib")->markSet(array('shop_code'=>session('shop_code')));
        foreach ($mark as $key => $value) {
            $mark[$key]['name'] = $value['mark_name'];
        }

        // 追踪阶段 seles_step
        // $selesStep = in_array('seles_step',$dfHidden) ? controller('crm/Customer','lib')->get_seles_step() : [];

        //消费能力
        $customer_capacity=controller("crm/Customer","lib")->capacity(array('shop_code'=>session('shop_code')));
        foreach ($customer_capacity as $key => $value) {
            $customer_capacity[$key]['name'] = $value['capacity'];
        }

        return json(array(
            'code'=>200,
            'info'=>$info,
            'must'=>$dfMust,
            'hidden'=>$dfHidden,
            'sign_name'=>$tracksign,
            'is_valid'=>json_decode(json_encode($validArr),true),
            'unValidReason'=>$unValidReason,
            'op_signinfo'=>$mark,
            'customer_capacity'=>$customer_capacity,
            // 'selesStep'=>$selesStep,
        ));
    }
    //无效原因
    public function getValidReason(){
        $unValidReason = controller('crm/Customer','lib')->getUnValidReason();
        foreach ($unValidReason as $key => $value) {
            $unValidReason[$key]['name'] = $value['reason'];
        }
        return json(array(
            'code'=>200,
            'reject_reason'=>$unValidReason
        ));
    }


    /*
     * 追踪，预约，驳回，不再追踪
     * customer_id
     * customer_name    客资姓名
     * customer_tel     客资手机
     * customer_wechat  客资微信
     * customer_sex     客资性别
     * add_friend_time  加好友时间  2019-05-12 12:20:41
     * mate_name        配偶姓名
     * mate_tel         配偶电话
     * mate_wechat      配偶微信
     *  noTrack 1:继续追踪，2：驳回；3：预约；4：不再追踪
     * staff_id
     * shop_code
     * brandclass_id
     * is_valid 客资状态  1：有效；2：待定；3：无效；4：驳回；5：反驳回
     * sign_id sign_name 客资标记
     * customer_intention_id customer_intention 客户意向
     * consultation_type_id consultation_type 消费类型
     * budget 预算
     * marry_day 婚期
     * next_time 再约时间
     * seles_step 追踪阶段id
     * step_name 追踪阶段
     * op_signinfo_id op_signinfo 追踪标记
     *
     * sales_remark 备注
     *
     * reject_reason 驳回原因
     *
     * consulation_shop_code consulation_shop 意向店面
     * reception_id reception_name 接待人
     * yjd_day 预约时间
     *
     * reason 不再追踪原因
     *
     *
     * */
    public function sales(){
        $data = input();
        if(empty($data['customer_id'])){
            return json(array('code'=>'101','msg'=>'未获取到客资ID'));
        }        
        
        if ($data['noTrack'] == 1) {
            //电访必选项配置
            $dfMust = db_config('df_must_'.$data['brandclass_id']);
            $dfMust = trim($dfMust, ',');
            if ($dfMust) {
                $dfMust = explode(',',$dfMust);
                foreach ($dfMust as $key => $value) {
                    if ($value == 'next_time') {
                        if (!$data[$value] || $data[$value] <= date('Y-m-d H:i:s')) {
                            return json(array('code'=>'99','msg'=>'再约时间小于当前时间，请重试'));
                        }
                    }
                }
            }
        }

        unset($data['api_url'],$data['api_type'],$data['configuration'],$data['token'],$data['api_code'],$data['staff_name'],$data['staff_id']);

        if($data['noTrack'] == 2){
            $reject['cid'] = $data['customer_id'];
            if(!$data['reject_reason']){
                return json(array('code'=>'104','msg'=>'未获取到驳回原因'));
            }else{
                $reject[''] = $data['reject_reason'];
            }
            if(!$data['sales_remark']){
                return json(array('code'=>'104','msg'=>'未获取到驳回备注'));
            }else{
                $reject['send_msg'] = $data['sales_remark'];
            }
            $res = controller('crm/Customer','lib')->customerReject($reject);
        }else{
            $cInfo = db('c_customerinfo')->where('id',$data['customer_id'])->find();

            if (!$data['customer_name']) {
                $data['customer_name'] = $cInfo['customer_name'];
            }
            if (!$data['customer_tel']) {
                $data['customer_tel'] = $cInfo['customer_tel'];
            }
            if (!$data['customer_wechat']) {
                $data['customer_wechat'] = $cInfo['customer_wechat'];
            }
            if (!$data['customer_sex']) {
                $data['customer_sex'] = $cInfo['customer_sex'];
            }
            if (!$data['mate_name']) {
                $data['mate_name'] = $cInfo['mate_name'];
            }
            if (!$data['mate_tel']) {
                $data['mate_tel'] = $cInfo['mate_tel'];
            }
            if (!$data['mate_wechat']) {
                $data['mate_wechat'] = $cInfo['mate_wechat'];
            }
            if (!$data['add_friend_time']) {
                $data['add_friend_time'] = $cInfo['add_friend_time'];
            }
            if (!$data['province']) {
                $data['province'] = $cInfo['province'];
            }
            if (!$data['city']) {
                $data['city'] = $cInfo['city'];
            }
            if (!$data['county']) {
                $data['county'] = $cInfo['county'];
            }
            if (!$data['sign_name']) {
                $data['sign_name'] = $cInfo['sign_name'];
            }
            if (!$data['is_valid']) {
                $data['is_valid'] = $cInfo['is_valid'];
            }
            if (!$data['next_time']) {
                $data['next_time'] = $cInfo['next_time'];
            }
            $res = controller('crm/Customer','lib')->editSalesTracking($data);
        }
        $this->data = input();
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }

    /*
     * 反驳回
     * cid 客资id
     * */
    public function customerRejectBack(){
        $data = input();
        $return = controller('crm/Customer','lib')->customerUnValidUpdate($data);
        if($return['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$return['data']]);
        }
        $this->result_code = $return['code'];
        $this->appApiLog();
        return json($return);
    }
    /*
     * 删除客资
     * id 客资id，多个用 ，隔开
     * */
    public function appDelCustomer(){
        $data = input();
        $ids = explode(',',$data['id']);
        $res = controller("crm/Customer","lib")->delCustomer($ids);
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        if($res['code'] == 1){
            return json(array('code'=>200,'msg' =>'删除客资成功！','data'=>$res['data']));
        }else{
            return $res;
        }
    }

    /*
     * 标记流失（不再追踪） noTrack
     * 参数：id  客资id
     *       loss_cause 不再追踪原因
     * 返回值：array('code'=>200,'msg'=>'标记有效成功')
     * */
    public function noTrack(){
        $data = input();
        $param['id'] = intval($data['id']);
        $param['loss_cause'] = $data['loss_cause'];
        $res = controller('crm/Customer','lib')->notTraking($param);
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }

    /*
       * 预约进店 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 = 2; //儿童

        $res = controller('crm/Customer','lib')->customerYjd_child($data);

        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    /*
     * getShop
     * 意向店面，拍照店面查询  预约进店 页面
     * brandclass_id
     * shop_code
     * flag    photo:拍照店；intention：意向店
     * token
     * staff_id
     * */
    public function getShop(){
        $data = input();
        $search['brandclass_id'] = $data['brandclass_id'] ?: session('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'];
            }
        }
        $intentionShop=controller('crm/Customer','lib')->get_shop($search);
        foreach ($intentionShop as $key => $value) {
            $intentionShop[$key]['id'] = $value['shop_code'];
            $intentionShop[$key]['name'] = $value['shop_name'];
        }
        return json(['code'=>200,'data'=>$intentionShop]);
    }
    /*
     *getShopStaffs
     * 获取店面下人员（登记人，追踪人，接待人,筛客人）
     * is_belong  登录后返回值有
     * brandclass_id
     * shop_code
     * token
     * flag dj:登记人；sales:追踪人;sk：筛客人；reception:接待人;默认：登记人
     * staff_id
     * */
    public function getShopStaffs(){
        $data = input();
        $staff = [];
        if($data['flag'] == 'sales'){
            if(empty($data['shop_code'])){
                return json(array('code'=>101,'msg'=>'参数有误，未获取到店面编码'));
            }
            $p['work_type'] = 21;
            $p['shop_code'] = $data['shop_code'];
            $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'=>session('brandclass_id')));
            }else{
                $staff = controller("crm/Customer","lib")->get_staff_lists(array('shop_code'=>$data['shop_code']));
            }
        }
        foreach ($staff as $key => $value) {
            $staff[$key]['name'] = $value['staffname'];
        }
        $this->data = input();
        $this->result_code = 200;
        $this->appApiLog();
        return json(array('code'=>200,'data'=>array_values($staff)));
    }


    // 检查客资是否转过订单
    public function checkCustomerOrder(){
        // 权限
        $auth = check_right('menu1519633923');
        if (!$auth) {
            return json(['code' => 102,'error'=>'1','msg'=>'您没有操作转订单的权限，请先设置权限']);
        }
        $erp = is_install('sx_erp');
        if (!$erp) {
            return json(['code' => 103, 'error'=>'1','msg'=>'您没有安装ERP，请先安装ERP！']);
        }
        $return = [];
        $id = (int)input('post.id');
        $info = db('crm_c_customerinfo')->where('id',$id)->field('order_number')->find();
        $one_order = db_config('one_customer_more_order');//同一客资允许多次订单,有过成交，就一直成交

        if ($info['order_number']) {
            if($one_order == 2){
                $return['error'] = 1;
                $return['code'] = 104;
                $return['msg']  = '已设置为不允许同一客资多次订单，请打开设置或重新创建客资转订单';
            }else{
                $return['code'] = 100;
                $return['msg']  = '已订单';
            }
        }else{
            $return['code'] = 200;
            $return['msg']  = '未订单';
        }

        return json($return);
    }

    // 网付订单 页面
    public function orderManager(){
        // 权限
        $auth = check_right('menu1519633923');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有操作转订单的权限，请先设置权限');
            return json($return);
        }

        //是否安装ERP
        $erp = is_install('sx_erp');
        if (!$erp) {
            $return = array('error'=>'1','msg'=>'您没有安装ERP，请先安装ERP！');
            return json($return);
        }

        $id = (int)input('param.id');

        $cusInfo = controller('crm/Customer', 'lib')->getCustomerInfo($id);
        $cusInfo['consultation_type'] = strip_tags($cusInfo['consultation_type']);
        $cusInfo['baby_birthday'] = substr($cusInfo['baby_birthday'],0,10);

        //来源渠道
        // $channel=controller("Customer","lib")->channel(array('shop_code'=>session('shop_code')));
        $channel=controller("crm/Customer","lib")->getChannel();
        if($cusInfo['shop_code'] != $cusInfo['add_shop_code']){//如果提报店和归属店不一样，把提报店的渠道追加到归属店的渠道里面
            $channel = array_merge($channel,array(array('id'=>$cusInfo['customer_channel_id'],'channel_name'=>$cusInfo['customer_channel'])));
        }

        $baby_sex = $this->getBabySex();;
        // 客户来源
        // $customerCource=controller("crm/Customer","lib")->source();

        //拍照店
        $shop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>$param['brandclass_id'],'is_photo'=>1]);
        foreach ($shop as $key => $value) {
            $shop[$key]['id'] = $value['shop_code'];
            $shop[$key]['name'] = $value['shop_name'];
        }

        $shopInfo = getShopInfo();
        $shop_code = session('shop_code');
        $sn = $shopInfo[$shop_code]['sn'];

        // 销售门市列表
        $reception = getShopStaffs(['shop_code'=>$cusInfo['consulation_shop_code'],'work_type'=>1]);
        // $where_staff['shop_code'] = $shop_code;
        // $where_staff['work_type'] = MS_WORK_TYPE;
        // $reception = getShopStaffs($where_staff);
        foreach ($reception as $key => $value) {
            $reception[$key]['name'] = $value['staffname'];
        }

        // $source = $this->getSource(); //获取客户来源

        //客资标记
        // $sign = $this->getTracksign();
        // $this->assign('sign',$sign);

        //摄影师
        $cameraman = getShopStaffs(['shop_code'=>$cusInfo['consulation_shop_code'],'work_type'=>3]);
        foreach ($cameraman as $key => $value) {
            $cameraman[$key]['name'] = $value['staffname'];
        }
        $this->assign('cameraman',$cameraman);

        $erp = config('ext.app_config');  //读取erp配置文件
        $addr = $erp['sx_erp']['addr'];   //调用url
        $api_json['Token'] = $this->token_appwxerp;
        $api_json['Code'] = $shop_code;

        //消费类型
        $url_consultation =trim($addr,'/').'/APP_ERPChildApi/APP_ConsumptionKindSet'; //定义拼接url
        $consultation_types = requestWXERP($url_consultation,$api_json);
        $consultation_type = $consultation_types['Data']?:[];
        foreach ($consultation_type as $key => $value) {
            $consultation_type[$key]['name'] = $value['consumption_name'];
        }

        //客户分区
        $url_area =trim($addr,'/').'/APP_ERPChildApi/APP_A0AreaSet'; //定义拼接url
        $customerarea = requestWXERP($url_area,$api_json);
        $customer_area = $customerarea['Data']?:[];
        foreach ($customer_area as $key => $value) {
            $customer_area[$key]['name'] = $value['area_name'];
        }

        //套系
        $url_PackageSet =trim($addr,'/').'/APP_ERPChildApi/APP_PackageSet'; //定义拼接url
        $paytypedict = requestWXERP($url_PackageSet,$api_json);//print_r($paytypedict);exit;
        $pay_type_dict = $paytypedict['Data']?:[];
        foreach ($pay_type_dict as $key => $value) {
            $pay_type_dict[$key]['id'] = $value['package_price'];
            $pay_type_dict[$key]['name'] = $value['package_name'];
        }

        //支付款项
        $url_Fand =trim($addr,'/').'/APP_ERPChildApi/APP_FundnameItmsSet'; //定义拼接url
        $fan = requestWXERP($url_Fand,$api_json);
        $fand = $fan['Data']?:[];
        foreach ($fand as $key => $value) {
            $fand[$key]['id'] = $value['collectitem_belongs'];
            $fand[$key]['name'] = $value['collectitem_name'];
        }

        //支付方式
        $url_PayType =trim($addr,'/').'/APP_ERPChildApi/APP_PayTypeItmsSet'; //定义拼接url
        $payt = requestWXERP($url_PayType,$api_json);
        $paytype = $payt['Data']?:[];
        // foreach ($paytype as $key => $value) {
        //     $paytype[$key]['name'] = $value['typename'];
        // }

        //订单编号
        $s = getStaffInfoById(session('staff_id'));
        $api_json['productid'] = session('mc_productid');
        $api_json['sn'] = $sn;
        $api_json['staff_sn'] = $s['staff_sn']?$s['staff_sn']:1;
        $url_OrderNum =trim($addr,'/').'/APP_ERPChildApi/APP_GetOrderNum'; //定义拼接url
        $orderNum = requestWXERP($url_OrderNum,$api_json);

        return json(array(
            'code'=>200,
            'cusInfo'=>$cusInfo,
            'channel'=>$channel,
            'consultation_type'=>$consultation_type,
            'shop'=>$shop,
            'reception'=>$reception,
            'sign'=>$sign,
            'customer_area'=>$customer_area,
            'package_name'=>$pay_type_dict,
            'collectitem_name'=>$fand,
            'paytype'=>$paytype,
            'orderNum'=>$orderNum,
            'customer_cource'=>$source,
            'baby_sex'=>$baby_sex,
            'cameraman'=>$cameraman,
            'api_json'=>$api_json,
            'target_time'=>date("Y-m-d"),
        ));
    }

    //网付订单 写入
    public function zhuanOrder(){
        $param = input('');

        $order_sn = trim($param['order_sn']);
        $ros = db('c_customerorder')->where('orderId', $order_sn)->find();
        if ($ros) {
            // 重新获取订单号
            $intentionShop=controller('crm/Customer','lib')->get_shop(['shop_code' => session('shop_code')]);
            $sn = isset($intentionShop[0]) ? $intentionShop[0]['sn'] : '';
            if ($sn == ''){
                $return['code']= 300;
                $return['msg'] = '操作失败！订单号已被占用，请重试！';
                $return['data'] = $ros['order_sn'];
                return json($return);
            }else{
                $erp = config('ext.app_config');  //读取erp配置文件
                $addr = $erp['sx_erp']['addr'];   //调用url
                $api_json['Token'] = $this->token_appwxerp;
                $api_json['Code'] = $shop_code;
                $s = getStaffInfoById(session('staff_id'));
                $api_json['productid'] = session('mc_productid');
                $api_json['sn'] = $sn;
                $api_json['staff_sn'] = $s['staff_sn']?$s['staff_sn']:session('staff_id');
                $url_OrderNum =trim($addr,'/').'/APP_ERPChildApi/APP_GetOrderNum'; //定义拼接url
                $orderNum = requestWXERP($url_OrderNum,$api_json);
                $return['code']= 210;
                $return['msg'] = '订单号已被占用，生成新单号，请再次确认开单！';
                $return['data'] = $orderNum;
                return json($return);
            }
        }
        $param['entrance_type'] = 'appwxerp';
        //appwxerp 转单  是否进客转单1为转单2为客资转单
        $param['is_zhuandan'] = $param['is_zhuandan']?:2;
        // $res = controller("crm/Customer","lib")->zhuanOrder($param);
        if($param['is_zhuandan'] == 1){

        }else{
            $listTime = microtime(true).'==>Line'.__LINE__.';';
            if(db_config('set_order_money_'.session('brandclass_id')) == 2){
                $param['paytype'] = null;    //收款方式
                $param['paymentmoney'] = null; //实收金额：
                $param['order_amount'] = null;
                $param['duikuanma'] = null;
            }
            // var_dump($param);
            // exit;
            $time = date('Y-m-d H:i:s',time());
            $target_time = trim($param['target_time']);
            $order_method = $param['order_method'] ? $param['order_method'] : null;
            /*if($param['target_time'] && $target_time > $time){
                $arr = array('code'=>600,'msg'=>'开单时间不能大于当前时间','data'=>$param['target_time']);
                return $arr;
            }*/
            // $order_sn = $param['order_sn'];
            // $orderid = db('c_customerorder')->where('orderId', $param['order_sn'])->value('id');
            // if($orderid){
            //     $arr = array('code'=>100,'msg'=>'开单失败，订单号重复','data'=>$param['order_sn']);
            //     return $arr;
            // }

            $isParam['package_name'] = $param['package_name'];
            $isParam['wphone'] = $param['customer_tel'];
            $isAddPackage = controller('erp/Erp','lib')->isAddPackage($isParam);
            if ($isAddPackage['code'] != 200) {
                return json($isAddPackage);
            }
            
            $customerInfo = db('crm_c_customerinfo')->where('id', $param['customer_id'])->find();

            $data['shop_code'] = session('shop_code');
            $data['shop_name'] = session('shop_name');
            $data['photo_shop_code'] = $param['photo_shop_code'];
            $data['photo_shop_name'] = $param['photo_shop_name'];
            $data['setkey'] = session('setkey');
            $data['target_time'] = $param['target_time'] ? date('Y-m-d H:i:s',strtotime($param['target_time'])) : $time;

            $data['create_time'] = $time;
            $data['customer_id'] = (int)$customerInfo['id'];
            $data['customer_name'] = $param['customer_name'];

            $cData['customer_name'] = $param['customer_name'];
            $cData['customer_tel'] = $param['customer_tel'];
            // $cData['customer_wechat'] = $param['customer_wechat'];
            // $cData['mate_name'] = $param['mate_name'];
            // $cData['mate_tel'] = $param['mate_tel'];
            // $cData['mate_wechat'] = $param['mate_wechat'];
            $cData['baby_name'] = $param['baby_name'];
            $cData['baby_sex'] = $param['baby_sex'];
            $cData['baby_birthday'] = $param['baby_birthday'] ? date('Y-m-d', strtotime($param['baby_birthday'])) : NULL;
            $cData['reception_id'] = $param['reception_id'];
            $cData['reception_name'] = $param['reception_name'];

            $cData['customer_area_id'] = intval($param['customer_area_id']);
            $cData['customer_area'] = $param['customer_area'];
            // $cData['customer_cource_id'] = intval($param['customer_cource_id']);
            $cData['customer_cource'] = $param['customer_cource_id'];
            // $cData['customer_channel_id']=$data['customer_channel_id'] = intval($param['customer_channel_id']);
            
            // $cData['customer_orderaddress_id'] = intval($param['customer_orderaddress_id']);
            // $cData['customer_orderaddress']=$data['customer_orderaddress'] = $param['customer_orderaddress'];
            // $cData['mate_birthday'] = $param['mate_birthday'] ? date('Y-m-d', strtotime($param['mate_birthday'])) : NULL;
            // $cData['customer_birthday'] = $param['customer_birthday'] ? date('Y-m-d', strtotime($param['customer_birthday'])) : NULL;
            $cData['totalpay_money'] = $param['order_amount'];
            $cData['marry_day'] = $param['marry_day'] ? $param['marry_day'] : null;
            $cData['ready_baby_day'] = $param['ready_baby_day'] ? $param['ready_baby_day'] : null;
            $cData['baby_address'] = $mData['babyhospital'] = $param['o_baby_address'] ? $param['o_baby_address'] : null;
            $cData['province_id'] = $param['province_id'] ? $param['province_id'] : null;
            $cData['province'] = $param['province'] ? $param['province'] : null;
            $cData['city_id'] = $param['city_id'] ? $param['city_id'] : null;
            $cData['city'] = $param['city'] ? $param['city'] : null;
            $cData['county_id'] = $param['county_id'] ? $param['county_id'] : null;
            $cData['county'] = $param['county'] ? $param['county'] : null;
            $cData['customer_address'] = $param['customer_address'] ? $param['customer_address'] : null;
            $cData['is_success'] = 3;

            $data['consultation_type'] = $param['consultation_type'];
            $data['order_fact'] = $param['paymentmoney'] ? $param['paymentmoney'] : 0;
            $data['order_amount'] = $param['order_amount'] ? $param['order_amount'] : 0;
            $data['order_note'] = $param['order_note'];
            $data['order_sn'] = $order_sn;
            $data['order_type'] = 1;
            $data['brandclass_id'] = session('brandclass_id');
            $data['brandclass'] = session('brandclass');
            // 订单有效标准 线下 （order_rule） 1：实收款；2：占比
            $ordervalid = getPercent($data['order_fact'],$data['order_amount'],$data['brandclass_id'],'order');

            if($ordervalid){
                $cData['is_success'] = 1;
                $cData['order_start_time'] = $data['target_time'];
                $cData['order_day']  = $data['target_time'];

                $data['order_valid'] = 2;
                $data['earnest_money'] = 0;
            }else{
                $cData['is_success'] = 3;
                $data['order_valid'] = 1;
                $data['earnest_money'] = 0;
                $cData['order_start_time'] = $data['target_time'];
            }
            // $cData['consultation_type_id']= (int)$param['consultation_type_id'];
            $cData['consultation_type']   = $param['consultation_type'];
            $consultation = controller('crm/Customer','lib')->consumptionType(['shop_code'=>$data['shop_code']]);
            $consultation = array_column($consultation,'id','consumption_name');
            $cData['consultation_type_id']= $consultation[$param['consultation_type']];
            // $mData['email'] = $param['email'];

            $lData['pc_shop_code'] = $param['photo_shop_code'];
            $lData['pc_shop_name'] = $param['photo_shop_name'];
            //摄影师
            $lData['cameraman_id'] = $param['cameraman_id'] ? intval($param['cameraman_id']) : '';
            $lData['cameraman_name'] = $param['cameraman_id'] ? trim($param['cameraman']) : '';
            //引导师
            $lData['tutor_id'] = intval($param['tutor_id']);
            $lData['tutor_name'] = trim($param['tutor_name']);
            $lData['status'] = 2;

            // ----------  ERP接口数据  开始  -------- //
            $dataErp = [];
            $dataErp['ShopSn'] = $param['shop_sn'];
            $dataErp['StaffSN'] = $param['staff_sn'];
            
            $dataErp['OrderId'] = $order_sn ? $order_sn : '';
            // 来源渠道
            // if ($customerInfo['customer_channel_id']) {
            //     $channel_info_name = db('crm_s_channel')->where('id', $customerInfo['customer_channel_id'])->value('channel_info_name');
            //     $dataErp['Customer_channel'] = $channel_info_name;
            // }else{
            //     $dataErp['Customer_channel'] = '';
            // }
            $dataErp['Customer_channel'] = $customerInfo['customer_channel'];
            // 客资编号
            $dataErp['crm_customer_id'] = $customerInfo['id'];
            $dataErp['Customer_from_index'] = $customerInfo['customer_number'];
            $dataErp['crm_c_unique'] = $customerInfo['c_unique'];
            // 联系邮箱
            $dataErp['Email'] = $param['email'] ? $param['email'] : '';
            // 客户来源
            $dataErp['Cssname'] = $param['customer_cource_id'] ? $param['customer_cource_id'] : '';
            // 客户分区
            $dataErp['Area'] = $param['customer_area_id'] ? $param['customer_area_id'] : '';
            // 结婚日期
            $dataErp['Weddingdate']= $param['marry_day'] ? $param['marry_day'] : '';
            $dataErp['Wname']      = $param['customer_name'] ? $param['customer_name'] : '';
            $dataErp['Wphone']     = $param['customer_tel'] ? $param['customer_tel'] : '';
            $dataErp['Wwechat']    = $param['customer_wechat'] ? $param['customer_wechat'] : '';
            $dataErp['Wbirthdate'] = $param['customer_birthday'] ? $param['customer_birthday'] : '';
            $dataErp['Mname']      = $param['mate_name'] ? $param['mate_name'] : '';
            $dataErp['Mphone']     = $param['mate_tel'] ? $param['mate_tel'] : '';
            $dataErp['Mwechat']    = $param['mate_wechat'] ? $param['mate_wechat'] : '';
            $dataErp['Mbirthdate'] = $param['mate_birthday'] ? $param['mate_birthday'] : '';
            // 客户所属店面
            $dataErp['Shop_code']  = $data['shop_code'];
            // 客户所属店面
            $dataErp['Shop_name']  = $data['shop_name'];
            // 客户所属店面
            $dataErp['photo_shop_code']  = $param['photo_shop_code'];
            // 客户所属店面
            $dataErp['photo_shop_name']  = $param['photo_shop_name'];
            // 事业部id
            $dataErp['Brandid']    = session('brandclass_id');
            // 订单备注  data里有
            $dataErp['Ordernote']  = $param['order_note'] ? trim($param['order_note']) : '';
            // 宝宝姓名 目前客资表中没有
            $dataErp['Bbname']     = $param['baby_name'] ? $param['baby_name'] : '';
            // 宝宝生日（阳历）
            $dataErp['Bbithdate']  = $param['baby_birthday'] ? date('Ymd', strtotime($param['baby_birthday'])) : '';
            // 宝宝性别
            $dataErp['Bbsex']      = $param['baby_sex'] ? $param['baby_sex'] : '';
            $dataErp['Bb_hospital']= $param['o_baby_address'] ? $param['o_baby_address'] : '';
            $dataErp['Cameraman']  = $lData['cameraman_name'] ? $lData['cameraman_name'] : '';
            $dataErp['mentor_a']  = $lData['tutor_name'] ? $lData['tutor_name'] : '';
            // 客户订单店面
            $dataErp['Shop_order_code'] = $param['shop_code'];
            $dataErp['Shop_order_name'] = $param['shop_name'];
            // 套餐名称 目前客资表中没有
            $dataErp['order_method'] = $order_method;
            if($order_method == '上门拍订单'){
                $dataErp['Package_name'] = $param['package_name'] ? $param['package_name'] : '';
            }
            if($data['order_valid'] == 2){
                $dataErp['orderyouxiaodate'] = date('Y-m-d H:i:s');
            }
            // 订单日期
            $dataErp['Targetdate']   = date('Ymd',strtotime($target_time));
            // 销售门市
            $dataErp['Storeconsuitant1'] = $param['reception_name'] ? $param['reception_name'] : '';
            // 地址
            $dataErp['Address_sheng'] = $param['province']?$param['province']:'';
            $dataErp['Address_shi'] = $param['city']?$param['city']:'';
            $dataErp['Address_qu'] = $param['county']?$param['county']:'';
            $dataErp['Address'] = $param['customer_address'] ? $param['customer_address'] : '';
            // 网销门市
            $dataErp['Storeconsuitant2'] = $param['sales_staff'] ? $param['sales_staff'] : session('staff_name');
            // 接单点
            $dataErp['Acceptor_address'] = $param['customer_orderaddress'] ? $param['customer_orderaddress'] : '';
            // 预产日期
            $dataErp['Yc_day'] = $param['ready_baby_day'] ? $param['ready_baby_day'] : '';
            // 宝宝出生地
            $dataErp['Bb_hospital'] = $param['o_baby_address'] ? $param['o_baby_address'] : '';
            // 客资系统来源
            $dataErp['Customer_from']    = 'CRM';
            // 操作店
            $dataErp['Opershop']        = session('shop_name');
            $dataErp['Jiandangren']     = session('staff_name');
            // 意向套系
            $dataErp['Yxpackage_name']  = $param['package_name'];
            $dataErp['Yxpackage_price'] = $param['order_amount'];
            //消费类型
            $dataErp['Consumption_type'] = $param['consultation_type'] ? $param['consultation_type'] : '';
            $dataErp['Paymentmoney']= $param['paymentmoney'] ? $param['paymentmoney'] : 0;
            $dataErp['Paytype']     = $param['paytype'];
            $dataErp['Duikuanma']   = $param['duikuanma'] ? $param['duikuanma'] : "";
            $dataErp['topiclist']   = trim($param['topiclist']);
            //开单是否自动写拍照表-----只在上门那里开单才这么操作--sdm
            if($param['autophoto']){
                $dataErp['autophoto'] = 1;
            }
            //开单是否自动写选片表-----只在上门那里开单才这么操作--sdm
            if($param['autosp']){
                $dataErp['autosp'] = 1;
            }
            // if($param['visit_id'] && !$param['cameraman']){
            //     return array('code'=>107,'msg'=>'未分配摄影师，无法转单。');
            // }
            // 赠送底片数量
            // $dataErp['give_photo_num'] = $param['give_photo_num'] ? (int)$param['give_photo_num'] : 0;
            // if ($dataErp['Paymentmoney']>0 ) {
            //     if (!$dataErp['Paytype']) {
            //         return array('code'=>105,'msg'=>'请选择收款方式');
            //     }
            //     if ($order_method != '上门拍订单' && !$dataErp['Duikuanma']) {
            //         return array('code'=>105,'msg'=>'请输入收款编号');
            //     }
            // }
            $dataErp['Duikuanma']   = $param['duikuanma'] ? $param['duikuanma'] : "";
            // $dataErp['crm_visit_id']= $param['visit_id'];
            $dataErp['tuiguangstaff'] = $customerInfo['recommend_staff'] ? $customerInfo['recommend_staff'] : NULL;
            if ($param['wangfutype']) {
                $dataErp['wangfutype'] = $param['wangfutype'];
            }
            // var_dump($dataErp);die;
            //一销锁定
            // var_dump($dataErp);
            // exit;
            // $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>session('shop_type')]);
            // ----------  ERP接口数据  结束  -------- //
            // $listTime .= microtime(true).'==>Line'.__LINE__.';';
            // 开启事务
            db()->startTrans();
            try {
                $data['order_sn'] = $order_sn;

                $oid = db('crm_c_customer_order')->insertGetId($data);

                // 写入客资表
                $cData['order_number'] = $order_sn;

                //修改客资为有效
                if($customerInfo['is_valid'] != 1){
                    $cData['is_valid']= 1;
                    $cData['yx_day']  = $time;
                }
                $cData['update_time'] = $time;
                // 修改追踪时间
                if(empty($customerInfo['c_star_day'])){
                    $cData['c_star_day'] = $time;
                    $cData['c_end_day'] = $time;
                    $cData['last_trackday'] = $time;
                }else{
                    $cData['c_end_day'] = $time;
                    $cData['last_trackday'] = $time;
                }

                //2021-05-07 过滤 重复及空项
                foreach ($cData as $key => $value) {
                    if ($value == $customerInfo[$key] || empty($value)) {
                        unset($cData[$key]);
                    }
                }

                db('crm_c_customerinfo')->where('id', $data['customer_id'])->update($cData);
                // 20200525
                history_log($cData, $customerInfo, $customerInfo['id'], session('staff_id'), session('staff_name'));

                //追踪记录
                $params['customer_id'] = $data['customer_id'];
                $params['c_unique'] = $customerInfo['c_unique'];
                $params['customer_name'] = $customerInfo['customer_name'];
                $params['customer_number'] = $customerInfo['customer_number'];
                if($order_method == '上门拍订单'){
                    $params['sales_remark'] = '上门拍订单';
                }else{
                    $params['sales_remark'] = 'CRM转单';
                }
                $params['sales_day'] = date('Y-m-d H:i:s',time());
                $params['sales_staff'] = session('staff_name');
                $params['sales_staff_id'] = session('staff_id');
                $params['sales_staff_number'] = session('staff_number');
                $params['shop_name'] = $customerInfo['shop_name'];
                $params['shop_code'] = $customerInfo['shop_code'];
                db('crm_c_salestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$data['customer_id'],null);

                getSalesTracking($data['customer_id']);

                //更新主表
                dealMain($customerInfo['c_unique'],$cData);
                // 调 erp 接口
                // var_dump(json_encode($dataErp));
                // $response = $erpInterface->createOrder(json_encode($dataErp));
                // $listTime .= microtime(true).'==>Line'.__LINE__.';';
                if ($param['visit_id'] && $param['autophoto']) {
                    $pclogInfo = db('crm_l_pc_log')->where('id',$param['visit_id'])->find();
                    $tohomeDisableDoubleOrder = db_config('tohome_disable_double_order');
                    if($tohomeDisableDoubleOrder && $pclogInfo['visit_order']){
                        db()->rollback();
                        return array('code'=>106,'msg'=>'当前进客已绑定订单，且不允许再次开单。');
                    }
                    $dataErp['pc_opt_shop_code'] = $pclogInfo['shop_code'];
                    $dataErp['pc_opt_shop_name'] = $pclogInfo['shop_name'];
                    $dataErp['pc_opt_staff_id'] = $pclogInfo['sale_id'];
                    $dataErp['pc_opt_staff_name'] = $pclogInfo['sale_name'];
                    $dataErp['pc_opt_time'] = $pclogInfo['create_time'];
                        
                }

                $response = controller('erp/Erp','lib')->createOrder($dataErp);
                $listTime .= microtime(true).'==>Line'.__LINE__.';';
                // var_dump($response);
                if ($response['code'] != '200') {
                    db()->rollback();
                    $arr = array('code'=>$response['code'],'msg'=>$response['msg'],'error'=>json_encode($response));
                }else{
                    if($param['visit_id']){
                        db('crm_l_pc_log')->where('id',$param['visit_id'])->update($lData);                        
                    }
                    $listTime .= microtime(true).'==>Line'.__LINE__.';';
                    // 如果返回单号不一样，更改单号
                    // if($response['Data'] != $order_sn){ 
                    //     $order_sn = $response['Data'];
                    //     db('crm_c_customerinfo')->where('id',$data['customer_id'])->update(['order_number'=>$order_sn]);
                    //     db('crm_c_customer_order')->where('id',$oid)->update(['order_sn'=>$order_sn]);
                    // }
                    // crm记录日志
                    if($order_method == '上门拍订单'){
                        $crmLog = '上门拍订单';
                    }else{
                        $crmLog = 'CRM转单';
                    }
                    $crmLog .= '，订单单号：'.$dataErp['OrderId'].'；意向套系：'.$param['package_name'].'；';
                    if ($dataErp['Paymentmoney']>0 ) {
                        $crmLog .= '收款方式：'.$dataErp['Paytype'].'；收款金额：'.$dataErp['Paymentmoney'].'；收款编号：'.$dataErp['duikuanma'];
                    }
                    history_log($crmLog, $customerInfo, $data['cid'], session('staff_id'), session('staff_name'));
                    $listTime .= microtime(true).'==>Line'.__LINE__.';';
                    // erp记录开单日志
                    $erpLog[0]['module'] = 'erp';
                    if($order_method == '上门拍订单'){
                        $erpLog[0]['controller'] = '上门拍手机端开单';
                    }else{
                        $erpLog[0]['controller'] = 'CRM开单';
                    }
                    $erpLog[0]['action'] = 'add';
                    $erpLog[0]['old_data']='开立订单；订单编号：'.$dataErp['OrderId'].'；';
                    $erpLog[0]['data'] = '';
                    $erpLog[0]['customer_id'] = $dataErp['OrderId'];
                    $erpLog[0]['staff_name'] = session('staff_name');
                    $erpLog[0]['staff_id'] = session('staff_id');
                    $erpLog[0]['ip'] = get_client_ip();
                    $erpLog[0]['create_time'] = $time;
                    
                    if ($dataErp['Paymentmoney']>0 ) {
                        $erpLog[1]['module'] = 'erp';
                        if($order_method == '上门拍订单'){
                            $erpLog[1]['controller'] = '上门拍手机端开单';
                        }else{
                            $erpLog[1]['controller'] = 'CRM开单';
                        }
                        $erpLog[1]['action'] = 'add';
                        $erpLog[1]['old_data'] = '订单编号：'.$dataErp['OrderId'].'；[上门拍手机端开单,款项名称：前期包套；支付方式：'.$dataErp['Paytype'].'；收款日期：'.date('Ymd').'；收款金额：'.$dataErp['Paymentmoney'].'；收款人：'.session('staff_name').'；收款编号：'.$dataErp['duikuanma'].'。]';
                        $erpLog[1]['data'] = '';
                        $erpLog[1]['customer_id'] = $dataErp['OrderId'];
                        $erpLog[1]['staff_name'] = session('staff_name');
                        $erpLog[1]['staff_id'] = session('staff_id');
                        $erpLog[1]['ip'] = get_client_ip();
                        $erpLog[1]['create_time'] = $time;
                    }
                    db('action_log','db_logs')->insertAll($erpLog);
                    $listTime .= microtime(true).'==>Line'.__LINE__.';';
                    // 开完单 调vip接口
                    $vipParam['tel']        = $dataErp['Wphone'];
                    $vipParam['brand_id']   = session('brandclass_id');;
                    $vipParam['order_code'] = $dataErp['OrderId'];
                    $vipParam['one_money']  = 0;
                    $vipParam['two_money']  = 0;
                    $vipParam['one_detail'] = $dataErp['Paymentmoney'];
                    $vipParam['two_detail'] = 0;
                    $vipParam['order_time'] = date('Y-m-d');
                    $vipParam['total_money']= 0;
                    $vipParam['package_nam']= '';
                    $vip = new \app\common\lib\vipInterface();
                    $createRes = $vip->createOrder($vipParam);
                    $listTime .= microtime(true).'==>Line'.__LINE__.';';
                    db()->commit();
                    $res = array('code'=>200,'msg'=>'开单成功','time'=>$listTime);
                }
            } catch (Exception $e) {
                db()->rollback();
                if($order_method == '上门拍订单'){
                    $error['action'] = '上门拍手机端开单';
                }else{
                    $error['action'] = 'CRM开单';
                }
                $error['error_reason'] = '开单报错：客资id为：'.$customerInfo['id'].',单号为：'.$response['Data'];
                $error['create_time'] = date('Y-m-d H:i:s');
                $res = array('code'=>100,'msg'=>'开单失败','data'=>$e->getMessage(),'sql'=>db()->getLastSql(),'line'=>$e->getLine(),'e'=>$e);
                db('crm_l_error_log')->insert($error);
            }

        }
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }

    //转单页面 选意向店 时  同步 套系
    public function getOrderTX(){
        $erp = config('ext.app_config');  //读取erp配置文件
        $addr = $erp['sx_erp']['addr'];   //调用url
        $api_json['Token'] = $this->token_appwxerp;
        $api_json['Code'] = input('post.shop_code')?input('post.shop_code'):session('shop_code');

        $url_PackageSet =trim($addr,'/').'/APP_ERPChildApi/APP_PackageSet'; //定义拼接url
        $paytypedict = requestWXERP($url_PackageSet,$api_json);
        $pay_type_dict = $paytypedict['Data']?:[];
        foreach ($pay_type_dict as $key => $value) {
            $pay_type_dict[$key]['id'] = $value['package_price'];
            $pay_type_dict[$key]['name'] = $value['package_name'];
        }

        return json($pay_type_dict);
    }



    /*
     * 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(){
        $input = input();

        $time = $input['time'] ?: date("Y-m-d");
        $data['start'] = $time.' 00:00:00';
        $data['end'] = $time.' 23:59:59';
        $data['consulation_shop_code'] = session('shop_code');
        $data['content'] = $input['content'];
        $data['entrance_type'] = 'appwxerp';

        $info = controller('index/Intostore','api')->customerList($data);

        $res['yijd'] = 0;
        $res['wjd'] = 0;
        $res['jdcj'] = 0;
        $res['jdls'] = 0;
        foreach ($info as $key => $value) {
            $info[$key]['is_intostores'] = getIsIntostores($value['is_intostore']);
            $info[$key]['is_successs'] = getIsSuccesss($value['is_success']);
            //已进店
            if (in_array($value['is_intostore'], [2,3,5])) {
                $res['yijd'] += 1;
            }
            //未进店
            if ($value['is_intostore']==1) {
                $res['wjd'] += 1;
            }
            //进店成交
            if ($value['is_success']=='已成交') {
                $res['jdcj'] += 1;
            }
            //进店流失
            if ($value['is_intostore']==5) {
                $res['jdls'] += 1;
            }
        }
        $res['yjd'] = count($info);

        return json(array('code'=>200,'data'=>$info,'res'=>$res));
    }

    //进客 新增客资 页面
    public function createCustomerHtml(){
        //来源渠道
        // $channel = $this->getChannel(session('shop_code'));

        //消费类型
        $consumptionType = $this->getConsumptionType(session('brandclass_id'));

        // 客户来源
        $customerCource = $this->getSource();

        // 销售门市列表
        $where_staff['shop_code'] = session('shop_code');
        $where_staff['work_type'] = MS_WORK_TYPE;
        $reception = getShopStaffs($where_staff);
        foreach ($reception as $key => $value) {
            $reception[$key]['name'] = $value['staffname'];
        }

        //门市标记
        $op_signinfo = $this->getincomingSign();

        //宝宝性别
        $babay_sex = $this->getBabySex();

        return json(array(
            'code'=>200,
            // 'customer_channel'=>$channel,
            'consultation_type'=>$consumptionType,
            'reception_name'=>$reception,
            'customer_cource'=>$customerCource,
            'op_signinfo'=>$op_signinfo,
            'babay_sex'=>$babay_sex,
        ));
    }

    //检查客资信息
    public function checkCustomerRepeat()
    {
        $input = input();
        $input['brandclass'] = session('brandclass');
        $input['shop_code'] = $input['shop_code'] ?: session('shop_code');

        $info = controller('index/Intostore','api')->checkCustomerRepeat($input);
        return json(array('code'=>200,'data'=>$info));
    }
    //进客 新增客资
    public function createCustomer()
    {
        $input = input();
        $input['brandclass'] = session('brandclass');
        $input['shop_code'] = $input['shop_code'] ?: session('shop_code');
        $input['staff_id'] = session('staff_id');

        $info = controller('index/Intostore','api')->createCustomer($input);

        if($info['code']&&$info['code'] != 200){
            return json($info);
        }else{
            return json(array('code'=>200,'data'=>$info,'msg'=>'新增进店成功！'));
        }
    }

    //进客 客资编辑 页面
    public function customerEditHtml()
    {
        $input = input();
        if(empty($input['id'])){
            return json(array('code'=>101,'msg'=>'参数有误，未获取到客资ID'));
        }

        $info = controller('index/Intostore','api')->getCustomerInfo($input['id']);

        //来源渠道
        // $channel = $this->getChannel(session('shop_code'));

        //消费类型
        $consumptionType = $this->getConsumptionType(session('brandclass_id'));

        // 客户来源
        $customerCource = $this->getSource();

        // 销售门市列表
        $where_staff['shop_code'] = session('shop_code');
        $where_staff['work_type'] = MS_WORK_TYPE;
        $reception = getShopStaffs($where_staff);
        foreach ($reception as $key => $value) {
            $reception[$key]['name'] = $value['staffname'];
        }

        //门市标记
        $op_signinfo = $this->getincomingSign();

        //进店状态
        $is_intostore = getIsIntostores(1,1);
        $i = 0;
        foreach ($is_intostore as $key => $value) {
            if($key !=1 ){
                $is_intostores[$i]['id'] = $key;
                $is_intostores[$i]['name'] = $value;
                $i++;
            }
        }

        return json(array(
            'code'=>200,
            'data'=>$info,
            // 'customer_channel'=>$channel,
            'consultation_type'=>$consumptionType,
            'reception_name'=>$reception,
            'customer_cource'=>$customerCource,
            'op_signinfo'=>$op_signinfo,
            'is_intostore'=>$is_intostores
        ));
    }
    //进客 客资编辑
    public function customerEdit()
    {
        $input = input();
        $input['staff_id'] = session('staff_id');
        $input['staff_name'] = session('staff_name');
        $input['entrance_type'] = 'appwxerp';

        $info = controller('index/Intostore','api')->customerEdit($input);

        if($info['code']&&$info['code'] != 200){
            return json($info);
        }else{
            return json(array('code'=>200,'data'=>$info,'msg'=>'操作成功'));
        }
    }

    //进客 删除进客
    public function deleteInto()
    {
        $input = input();
        $input['staff_id'] = session('staff_id');
        $input['staff_name'] = session('staff_name');

        $info = controller('index/Intostore','api')->deleteInto($input);
        if($info['code']&&$info['code'] != 200){
            return json($info);
        }else{
            return json(array('code'=>200,'data'=>$info,'msg'=>'删除进客成功'));
        }
    }

    //修改实际进店时间的时分秒
    public function editSyjd()
    {
        $input = input();
        $input['staff_id'] = session('staff_id');
        $input['staff_name'] = session('staff_name');
        $input['time'] = str_replace(":","",$input['time'])."00";

        $info = controller('index/Intostore','api')->editSyjd($input);
        if($info['code']&&$info['code'] != 200){
            return json($info);
        }else{
            return json(array('code'=>200,'data'=>$info,'msg'=>'操作成功'));
        }
    }

    //修改进店 状态
    public function intostore()
    {
        $input = input();
        $input['staff_id'] = session('staff_id');
        $input['staff_name'] = session('staff_name');

        $info = controller('index/Intostore','api')->intostore($input);
        if($info['code']&&$info['code'] != 200){
            return json($info);
        }else{
            return json(array('code'=>200,'data'=>$info,'msg'=>'操作成功'));
        }
    }

    //标记未进店
    public function notIntostore()
    {
        $input = input();
        $input['staff_id'] = session('staff_id');
        $input['staff_name'] = session('staff_name');

        $info = controller('index/Intostore','api')->notIntostore($input);
        if($info['code']&&$info['code'] != 200){
            return json($info);
        }else{
            return json(array('code'=>200,'data'=>$info,'msg'=>'操作成功'));
        }
    }

    /*今日数据 毛客资  有效客资 进店 订单 流失客资（不再追踪） 有效率 进店率 成交率 一销套系 一销均价 总实收
     * todayData
     * 参数：start end staff_id shop_code
     * [
            'code'=>200,
            'mkz'=>$mkz,                        //毛客资
            'valid'=>$valid,                    //有效
            'order'=>$order,                    //订单
            'fact'=>$fact,                      //总实收
            'jdl'=>$jdl                         //客资进店率
        ];
     * */
    public function todayData(){
        $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');

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

        $tar = new Target();
        $param = [
            'start_day' => $start,
            'end_day' => $end,
            'staff_id' => $staffId,
            'shop_code' => session('shop_code'),
            'department_id' => session('department_id')
        ];
        $mkz = $tar->newCustomerNum($param);
        $valid = $tar->validCustomerNumber($param);
        $order = $tar->orderNumber($param);
        $fact = $tar->dealAmount($param);
        $jdl = $tar->valueCustomerIntoRate($param);
        $arr = [
            'code'=>200,
            'data'=>[
                'mkz'=>$mkz,
                'valid'=>$valid,
                'order'=>$order,
                'fact'=>$fact,
                'jdl'=>$jdl
            ]
        ];
        return json($arr);
    }
    //渠道数据分析
    public function channelDataAnalysis()
    {
        $data = input();
        $start = $data['start'] ? date('Y-m-d 00:00:00', strtotime($data['start'])) : date('Y-10-01 00:00:00');
        $end   = $data['end'] ? date('Y-m-d 23:59:59', strtotime($data['end'])) : date('Y-m-d 23:59:59');

        $shop_code = $data['shop_code'] ?: session('shop_code');
        // 来源渠道
        $channels = $this->getChannel($shop_code);
        if ($data['type'] == 2) {
            //二级渠道
            foreach ($channels as $key => $value) {
                $chanl_info[$value['channel_name']] = $value['channel_class_name'];
            }
        }
        
        $channels = array_column($channels,'channel_name');
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;
        $whereCost['shop_code'] = $shop_code;

        $sql = '';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'") as mkz,';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid in (\'1\',\'5\',\'4\',\'2\')) as valid,';
        $sql .= 'sum(yjd_day between "'.$start.'" and "'.$end.'") as yy,';
        $sql .= 'sum(syjd_day between "'.$start.'" and "'.$end.'" and is_intostore in (\'2\',\'3\',\'5\')) as jd,';
        $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1) as `order`, ';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=2) as dd,';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=3) as unValid';
        
        $info = db('crm_c_customerinfo')
            ->where($where)
            ->where('customer_channel','in',$channels)
            ->group('customer_channel')
            ->column($sql, 'customer_channel');
        //花费
        $cost = db('crm_s_channel_cost')
            ->where('cost_date', 'between time', [$start, $end])
            ->where($whereCost)
            ->where('channel_name','in',$channels)
            ->group('channel_name')
            ->column('sum(cost) as cost','channel_name');
        //实收
        $factMoney = db('crm_c_customerinfo')->alias('c')->join('crm_s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where('c.customer_channel','in',$channels)
            ->where('order_day', 'between time', [$start, $end])
            ->group('c.customer_channel')
            ->column('sum(c.fact_money) as fact,s.channel_name,s.channel_class_name,s.channel_info_name,s.id', 'c.customer_channel');

        //营收
        $totalMoney = db('crm_c_customerinfo')
            ->alias('c')
            ->join('crm_s_channel s', 's.id=c.customer_channel_id')
            ->join('c_customerorder o','c.customer_number=o.crm_customer_number','LEFT')
            ->where($where)
            ->where('c.customer_channel','in',$channels)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.customer_channel')
            ->column('sum(o.payment_money) as total,s.channel_name,s.channel_class_name,s.channel_info_name,s.id','c.customer_channel');
        $returnData = [];
        $arr = [];
        foreach($channels as $k=>$v){
            if($data['type'] == 2){
                //二级渠道
                $returnData[$chanl_info[$v]]['channel_name'] = $chanl_info[$v];
                $returnData[$chanl_info[$v]]['mkz'] += $info[$v]['mkz'];
                $returnData[$chanl_info[$v]]['valid'] += $info[$v]['valid'];
                $returnData[$chanl_info[$v]]['unValid'] += $info[$v]['unValid'];
                $returnData[$chanl_info[$v]]['dd'] += $info[$v]['dd'];
                $returnData[$chanl_info[$v]]['yy'] += $info[$v]['yy'];
                $returnData[$chanl_info[$v]]['jd'] += $info[$v]['jd'];
                $returnData[$chanl_info[$v]]['order'] += $info[$v]['order'];
                $returnData[$chanl_info[$v]]['cost'] += sprintf('%.2f',$cost[$v]);
                $returnData[$chanl_info[$v]]['totalMoney'] +=  sprintf('%.2f',$totalMoney[$v]['total']);
                $returnData[$chanl_info[$v]]['factMoney'] +=  sprintf('%.2f',$factMoney[$v]['fact']);
            }else{
                //三级渠道
                $returnData[$k]['channel_name'] = $v;
                $returnData[$k]['mkz'] = $info[$v]['mkz'];
                $returnData[$k]['valid'] = $info[$v]['valid'];
                $returnData[$k]['unValid'] = $info[$v]['unValid'];
                $returnData[$k]['dd'] = $info[$v]['dd'];
                $returnData[$k]['yy'] = $info[$v]['yy'];
                $returnData[$k]['jd'] = $info[$v]['jd'];
                $returnData[$k]['order'] = $info[$v]['order'];
                $returnData[$k]['validRate'] = $info[$v]['valid'] ? sprintf('%.2f',$info[$v]['valid']/$info[$v]['mkz']*100).'%' : '0%';
                $returnData[$k]['unValidRate'] = $info[$v]['unValid'] ? sprintf('%.2f',$info[$v]['unValid']/$info[$v]['mkz']*100).'%' : '0%';
                $returnData[$k]['ddRate'] = $info[$v]['dd'] ? sprintf('%.2f',$info[$v]['dd']/$info[$v]['mkz']*100).'%' : '0%';
                $returnData[$k]['mkzJdRate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$info[$v]['mkz']*100).'%' : '0%';
                $returnData[$k]['validJdRate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$info[$v]['valid']*100).'%' : '0%';
                $returnData[$k]['jdOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['jd']*100).'%' : '0%';
                $returnData[$k]['mkzOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['mkz']*100).'%' : '0%';
                $returnData[$k]['validOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['valid']*100).'%' : '0%';
                $returnData[$k]['cost'] = sprintf('%.2f',$cost[$v]);
                $returnData[$k]['mkzCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['mkz']) : '';
                $returnData[$k]['validCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['valid']) : '';
                $returnData[$k]['jdCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['jd']) : '';
                $returnData[$k]['orderCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['order']) : '';
                $returnData[$k]['orderAVG'] =  $info[$v]['order'] ? sprintf('%.2f',$totalMoney[$v]['total']/$info[$v]['order']) : '';
                $returnData[$k]['totalMoney'] =  sprintf('%.2f',$totalMoney[$v]['total']);
                $returnData[$k]['factMoney'] =  sprintf('%.2f',$factMoney[$v]['fact']);
                $returnData[$k]['ROI'] = $returnData[$k]['totalMoney'] ? sprintf('%.2f',$returnData[$k]['totalMoney']/$returnData[$k]['cost']) : '';
            }
            
            //总计
            $arr['channel_name'] = '合计';
            $arr['mkz'] += $returnData[$k]['mkz'];
            $arr['valid'] += $returnData[$k]['valid'];
            $arr['unValid'] += $returnData[$k]['unValid'];
            $arr['dd'] += $returnData[$k]['dd'];
            $arr['yy'] += $returnData[$k]['yy'];
            $arr['jd'] += $returnData[$k]['jd'];
            $arr['order'] += $returnData[$k]['order'];
            $arr['validRate'] = '';
            $arr['unValidRate'] = '';
            $arr['ddRate'] = '';
            $arr['mkzJdRate'] = '';
            $arr['validJdRate'] = '';
            $arr['jdOrderRate'] = '';
            $arr['mkzOrderRate'] = '';
            $arr['validOrderRate'] = '';
            $arr['cost'] += $returnData[$k]['cost'];
            $arr['mkzCost'] = '';
            $arr['validCost'] = '';
            $arr['jdCost'] = '';
            $arr['orderCost'] = '';
            $arr['orderAVG'] = '';
            $arr['totalMoney'] += floatval($returnData[$k]['totalMoney']);
            $arr['factMoney'] += floatval($returnData[$k]['factMoney']);
            $arr['ROI'] = '';
        }

        if($data['type'] == 2){
            foreach($returnData as $k=>$v){
                $returnData[$k]['validRate'] = $v['valid'] ? sprintf('%.2f',$v['valid']/$v['mkz']*100).'%' : '0%';
                $returnData[$k]['unValidRate'] = $v['unValid'] ? sprintf('%.2f',$v['unValid']/$v['mkz']*100).'%' : '0%';
                $returnData[$k]['ddRate'] = $v['dd'] ? sprintf('%.2f',$v['dd']/$v['mkz']*100).'%' : '0%';
                $returnData[$k]['mkzJdRate'] = $v['jd'] ? sprintf('%.2f',$v['jd']/$v['mkz']*100).'%' : '0%';
                $returnData[$k]['validJdRate'] = $v['jd'] ? sprintf('%.2f',$v['jd']/$v['valid']*100).'%' : '0%';
                $returnData[$k]['jdOrderRate'] = $v['order'] ? sprintf('%.2f',$v['order']/$v['jd']*100).'%' : '0%';
                $returnData[$k]['mkzOrderRate'] = $v['order'] ? sprintf('%.2f',$v['order']/$v['mkz']*100).'%' : '0%';
                $returnData[$k]['validOrderRate'] = $v['order'] ? sprintf('%.2f',$v['order']/$v['valid']*100).'%' : '0%';
                $returnData[$k]['mkzCost'] = $v['cost'] ? sprintf('%.2f',$v['cost']/$v['mkz']) : '';
                $returnData[$k]['validCost'] = $v['cost'] ? sprintf('%.2f',$v['cost']/$v['valid']) : '';
                $returnData[$k]['jdCost'] = $v['cost'] ? sprintf('%.2f',$v['cost']/$v['jd']) : '';
                $returnData[$k]['orderCost'] = $v['cost'] ? sprintf('%.2f',$v['cost']/$v['order']) : '';
                $returnData[$k]['orderAVG'] =  $v['order'] ? sprintf('%.2f',$v['totalMoney']/$v['order']) : '';
                $returnData[$k]['ROI'] = $v['totalMoney'] ? sprintf('%.2f',$v['totalMoney']/$v['cost']) : '';
            }
            $k = 0;
            foreach($returnData as $key=>$v){
                $returnData[$k] = $v;
                unset($returnData[$key]);
                $k++;
            }
        }

        $arr['validRate'] = $arr['valid'] ? sprintf('%.2f',$arr['valid']/$arr['mkz']*100).'%' : '0%';
        $arr['unValidRate'] = $arr['valid'] ? sprintf('%.2f',$arr['unValid']/$arr['mkz']*100).'%' : '0%';
        $arr['ddRate'] = $arr['valid'] ? sprintf('%.2f',$arr['unValid']/$arr['mkz']*100).'%' : '0%';
        $arr['mkzJdRate'] = $arr['valid'] ? sprintf('%.2f',$arr['jd']/$arr['mkz']*100).'%' : '0%';
        $arr['validJdRate'] = $arr['valid'] ? sprintf('%.2f',$arr['jd']/$arr['valid']*100).'%' : '0%';
        $arr['jdOrderRate'] = $arr['valid'] ? sprintf('%.2f',$arr['order']/$arr['jd']*100).'%' : '0%';
        $arr['mkzOrderRate'] = $arr['valid'] ? sprintf('%.2f',$arr['order']/$arr['mkz']*100).'%' : '0%';
        $arr['validOrderRate'] = $arr['valid'] ? sprintf('%.2f',$arr['order']/$arr['valid']*100).'%' : '0%';
        $arr['mkzCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['mkz']) : '';
        $arr['validCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['valid']) : '';
        $arr['jdCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['jd']) : '';
        $arr['orderCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['order']) : '';
        $arr['orderAVG'] = $arr['totalMoney'] ? sprintf('%.2f',$arr['totalMoney']/$arr['order']) : '';
        $arr['totalMoney'] = sprintf('%.2f',$arr['totalMoney']);
        $arr['factMoney'] = sprintf('%.2f',$arr['factMoney']);
        $arr['ROI'] = $arr['totalMoney'] ? sprintf('%.2f',$arr['totalMoney']/$arr['cost']) : '';

        $returnData[] = $arr;
        $return['code'] = 200;
        $return['msg'] = '';
        $return['data'] = $returnData;
        return json($return);
    }
    //权限
    public function getFunction(){
        $menu = include(APP_PATH.'menu.php');
        $menuCustomize = include(APP_PATH.'menu_customize.php');
        $auth = getAuthMenu($menu,'auth',$menuCustomize);
        $list = [];
        foreach ($auth['list'] as $key => $value) {
            if($value['menu_code'] == 'menu1640831171'){
                $list[] = $value;
            }
        }
        $newAuth = controller('crm/Setting','lib')->arrayDuoZhuanEr($list);
        $menuCode= array_column($newAuth,'menu_code');


        return json(array('code'=>200,'data'=>$menuCode));
    }

























    
    /**
     * 岗位查询 
     * 
     * @param  position_code  岗位code(支持多个code，用用英文逗号分隔)
     * 
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getPosition($params){

        $mc = new \app\common\lib\mcInterface();
        $positions = $mc->getPosition(['position_code'=>$params['position_code']]);
        if ($positions===false) {
            $positions = [];
        }
        return json(array('code'=>200,'data'=>$positions));
    }


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

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

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

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

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

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

        return json(array('code'=>200,'data'=>$return));
    }


    /*
     * 发送短信
     * appSendMsg
     * ids  客资id，多个用 ，隔开
     * send_msg 短信内容
     * receive_name 接收人 多个用 ，隔开
     * model_id  短信模板id
     * */
    public function appSendMsg(){
        $res = controller('crm/Customer','lib')->send_message(input());
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }
    /*
     * 获取短信模板
     * getMsgModel
     * shop_code
     * staff_id
     * */
    public function getMsgModel(){
        if(empty(input('param.shop_code'))){
            return json(array('code'=>110,'msg'=>'未获取到店面编码'));
        }
        $res = controller('crm/Customer','lib')->getModel(input('post.shop_code'));
        return json($res);
    }
    /*
     * getSetting
     * 获取客资标记，追踪标记，驳回原因,追踪失败原因
     * shop_code
     * staff_id
     * token
     * */
    public function getSetting(){
        $shop_code = input('param.shop_code');
        if(empty($shop_code)){
            return json(array('code'=>110,'msg'=>'未获取到店面编码'));
        }
        // 追踪标记
        $allSet['track'] = controller('crm/Customer','lib')->markSet();
        //客资标记
        $allSet['sign'] = $this->getTracksign();
        //驳回原因
        $allSet['reject'] = db('s_reject_reason')->where('shop_code',$shop_code)->select();
        //追踪失败原因
        $allSet['reason'] = db('s_file_reason')->where('shop_code',$shop_code)->select();
        return json(array('code'=>200,'data'=>$allSet));
    }
    /*
     * 我提报的 可通过客资状态 关键词 分配日期 进行筛选 返回:返回数量 和客资列表 分页加载
     * customerDj
     * start    开始时间
     * end    结束时间
     * search    查询关键字
     * staff_id    员工id
     * shop_code    店面
     * is_success    成交状态；1：已成交；2未成交；3：已定金
     * is_valid      客资状态；1：有效；2：待定；3：无效；4：驳回；5：反驳回
     * is_fp         分配状态；1：已分配；2：未分配；3：待接收；4：分配失败；
     * is_intostore  进店状态；1：未进店；2：进店进客；3：进店非进客
     *limit          每页条数
     * page             页数
     * 返回值：
     *  code 200
     *  data: status未客资目前状态
     * */
    public function customerDj(){
        $data = input();
        $data['start_time'] = $data['start'] ? date('Y-m-d',strtotime($data['start'])) : date('Y-m-d');
        $data['end_time'] = $data['end'] ? date('Y-m-d',strtotime($data['end'])) : date('Y-m-d');
        $data['rows'] = $data['limit'] ? intval($data['limit']) : 10;
        $data['page'] = $data['page'] ? intval($data['page']) : 1;
        $data['more_like'] = $data['search'] ? trim($data['search']) : '';
        $data['tab'] = 1;
        $data['all_time'] = 'dj_day';
        $data['sord'] = 'desc';
        $data['dj_staff_id'] = intval($data['staff_id']);

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

        $ret = controller('crm/Customer','lib')->customerListData($data);
        $info = getCustomerStatus($ret['new_rows']);
        $count = $ret['records'];
        $staff_name = $data['staff_name']?$data['staff_name']:session('staff_name');
        if(!empty($info)){
            action_log($data,[],0,$data['staff_id'],$staff_name);
            $return = array('code'=>200,'data'=>$info,'count'=>$count);
        }else{
            $return = array('code'=>100,'msg'=>'暂无数据');
        }
        return json($return);
    }
    /*我的工作情况  毛客资  有效客资 进店 订单 流失客资（不再追踪） 有效率 进店率 成交率 一销套系 一销均价 总实收
     * myWork
     * 参数：start end staff_id shop_code
     * [
            'code'=>200,
            'mkz'=>$mkz,                        //毛客资
            'valid'=>$valid,                    //有效
            'jd'=>$jd,                          //进店
            'order'=>$order,                    //订单
            'loss'=>$loss,                      //不再追踪
            'validRate'=>$validRate,            //有效率
            'jdRate'=>$jdRate,                  //进店率
            'orderRate'=>$orderRate,            //成交率
            'total'=>$total,                    //一销套系
            'avg'=>$avg,                        //一销均价
            'fact'=>$fact,                      //总实收
        ];
     * */
    public function myWork(){
        $data = input();
        $start = $data['start'] ? date('Y-m-d 00:00:00', strtotime($data['start'])) : date('Y-m-d 00:00:00');
        $end   = $data['end'] ? date('Y-m-d 23:59:59', strtotime($data['end'])) : date('Y-m-d 23:59:59');
        $tar = new Target();
        $param = [
            'start_day' => $start,
            'end_day' => $end,
            'staff_id' => intval($data['staff_id']),
            'shop_code' => trim($data['shop_code'])
        ];
        $mkz = $tar->newCustomerNum($param);
        $valid = $tar->validCustomerNumber($param);
        $jd = $tar->actualIntoCustomerNumber($param);
        $order = $tar->orderNumber($param);
        /*$loss = db('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('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);
    }



    /*
     * 渠道花费查询
     * channelCostSearch
     * shop_code
     * belong_shop_code
     * cost_date  花费设定时间
     * staff_id
     * department_id
     * channel_name  模糊搜索渠道名
     * page 页数
     * limit 每页条数
     * */
    public function channelCostSearch(){
        $param = input();
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 20;
        $where = [];


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

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

        $info['data'] =  db('s_channel')->where($where)->page($page)->limit($limit)->field('id,channel_name,order_sort')->order('order_sort')->select();
        $info['count'] = db('s_channel')->where($where)->count();
        if($param['cost_date']){
            $where['cost_date'] = date('Y-m-d',strtotime($param['cost_date']));
        }else{
            return json(array('code'=>99,'msg'=>'请选择花费设定日期'));
        }
        if($param['department_id']){
            $where['department_id'] = $param['department_id'];
        }
        if($param['belong_shop_code']){
            $where['belong_shop_code'] = $param['belong_shop_code'];
        }
        if($param['province_id']){
            $where['province_id'] = $param['province_id'];
        }
        if($param['city_id']){
            $where['city_id'] = $param['city_id'];
        }
        $cost = db('s_channel_cost')->where($where)->column('cost,belong_shop_code','channel_id');
        foreach($info['data'] as $k=>$v){
            $info['data'][$k]['cost'] = $cost[$v['id']]['cost'];
            $info['data'][$k]['belong_shop_code'] = $cost[$v['id']]['belong_shop_code'];
        }
        if(empty($info)){
            return json(array('code'=>100,'msg'=>'未获取到渠道花费'));
        }else{
            $total = array_sum(array_column($info['data'],'cost'));
            $info['total'] = sprintf('%.2f',$total);
            return json(array('code'=>200,'data'=>$info));
        }
    }
    /*
     *channelCostEdit
     * 渠道花费修改
     * staff_id
     * shop_code
     * shop_name
     * channel_id  渠道id
     * cost 花费
     * cost_date 花费设定日期
     * province_id 省id
     * province_name
     * city_id 市id
     * city_name
     * department_id 部门id
     * department_name
     * belong_shop_code 归属店
     * belong_shop_name
     * */
    public function channelCostEdit(){
        $data = input();
        if(empty($data['channel_id'])){
            return json(array('code'=>100,'msg'=>'未获取到渠道ID'));
        }
        if(empty($data['cost'])){
            return json(array('code'=>101,'msg'=>'花费不能为空'));
        }
        if(empty($data['shop_code'])){
            return json(array('code'=>102,'msg'=>'未获取到店面编码'));
        }
        if(empty($data['cost_date'])){
            return json(array('code'=>103,'msg'=>'未获取到花费日期'));
        }
        $res = controller('crm/Customer','lib')->appChannelCostEdit($data);
        if($res['code'] == 200){
            $this->data = input();
        }else{
            $this->data = array_push(input(),['error'=>$res['data']]);
        }
        $this->result_code = $res['code'];
        $this->appApiLog();
        return json($res);
    }

    /*
     * showCost
     * 花费录入界面
     * brandclass_id
     * shop_code
     * staff_id
     * valid_date
     * shop_type
     * belong_shop_code
     * belong_shop_name
     *
     * return 'code'=>200,'flag'=>$flag,'data'=>$info  其中，flag=region，是地域，要显示省市，flag=belong，是归属店
     * */
    public function showCost(){
        $data = input();
        if(empty($data['shop_code'])){
            return json(array('code'=>101,'msg'=>'参数有误，未获取到店面编码'));
        }
        //维度
        $method = db_config('cost_method_'.$data['shop_code']);
        if($method == 'belong' && ($data['valid_date'] == 0)){
            $array = [
                'brandclass_id' => $data['brandclass_id'],
                'staff_id' => $data['staff_id'],
                'shop_type' =>$data['shop_type'],
                'shop_code' =>$data['shop_code'],
                'belong_shop_code' =>$data['belong_shop_code'],
                'belong_shop_name' =>$data['belong_shop_name'],
            ];
            $info = getBelongShop($array);
            $flag = 'belong';
        }else{
            $p = [
                'type'=>1,
                'shop_code'=>$data['shop_code']
            ];
            $info=controller("crm/Customer","lib")->address($p);
            $flag = 'region';
        }
        return json(array('code'=>200,'flag'=>$flag,'data'=>$info,'android'=>array_values($info)));
    }
    /*
     *getCity
     * 根据省份获取市
     * shop_code
     * staff_id
     * pid  省份id
     * */
    public function getCity(){
        $data = input();
        if(empty($data['shop_code'])){
            return json(array('code'=>101,'msg'=>'参数有误，未获取到店面编码'));
        }else{
            $p['shop_code'] = $data['shop_code'];
        }
        if(empty($data['pid'])){
            return json(array('code'=>102,'msg'=>'参数有误，未获取到省份ID'));
        }else{
            $p['pid'] = $data['pid'];
        }
        $p['type']= 2;
        $info=controller("crm/Customer","lib")->address($p);
        return json(array('code'=>200,'data'=>$info));
    }
    /*
     * getMenu
     * 获取用户权限接口
     * staff_id
     * shop_code
     * main_position_code
     * token
     * */
    public function getMenu(){
        $data = input();
        if(empty($data['shop_code'])){
            return json(array('code'=>101,'msg'=>'参数有误，未获取到店面编码'));
        }
        if(empty($data['staff_id'])){
            return json(array('code'=>102,'msg'=>'参数有误，未获取到用户ID'));
        }
        if(empty($data['main_position_code'])){
            return json(array('code'=>102,'msg'=>'参数有误，未获取到用户岗位编号'));
        }
        $staffInfo = getStaffInfoById($data['staff_id']);
        if(in_array(SYSTEM_AUTH_ADMIN,explode(',',$staffInfo['main_work_type'].','.$staffInfo['work_type']))){
            $info = db('s_menu')->field('menu_code,menu_name')->select();
            return json(array('code'=>200,'data'=>$info));
        }
        $menu = db('s_position_menu')->where('position_code',$data['main_position_code'])->value('menu_code');
        $menu = explode(',',$menu);
        $info = db('s_menu')->where('menu_code','in',$menu)->field('menu_code,menu_name')->select();
        return json(array('code'=>200,'data'=>session('crm_auth')));
    }

    /*
     * 切换岗位  changePosition
     * @param main_position_code  主岗位code  全局
     * return true/false
     * */
    public function changePosition(){
        $main_position_code = input('main_position_code');
        $info = changeMyPosition($main_position_code);
        $shop_code = input('shop_code')?input('shop_code'):session('shop_code');
        if($info){
            return json(array('code'=>200,'msg'=>'切换岗位成功','session'=>$shop_code,'cookie'=>$_COOKIE,'main_position_code'=>$main_position_code));
        }else{
            return json(array('code'=>100,'msg'=>'切换岗位失败'));
        }
    }
    /*
     * @param file
     * 图片上传接口
     * */
    public function upload_img(){
        $base_path = 'upload';
        $addr = config('app_host');
        $addr = trim(trim($addr), '/');
        // 多文件
        // $files = request()->file("imgs");
        // 单文件
        $files = request()->file();

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

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

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


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

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

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