<?php
/**
 * CRM 预约上门模块
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: Lilong<Lilong@suxuantech.cn> 2019-10-28 $
 */
namespace app\crm\controller;
use app\crm\lib\Target;
use think\Cache;
use app\index\controller\Base;
use think\Exception;
use think\exception\PDOException;
use think\Log;
use think\Request;
use think\Session;
use PHPExcel_IOFactory;
use PHPExcel;
use Excel5;
use think\Controller;
use app\common\lib\redisQueue;
use app\common\lib\erpInterface;
use app\common\lib\mcInterface;
class Visit extends Base{
    /*------------------------------------------------------- 核销相关 开始 ------------------------------------------------------- */
        //改期原因设定
        public function changedateReason(){
            return $this->fetch();
        }
        //核销改期原因列表
        public function getHXChangeDateReasonToJSON(){
            $reason = input('param.reason');
            $result['code'] = 0;
            $result['msg'] = '';
            $res = db('crm_s_changedate_reason')->where('brandclass_id',session('brandclass_id'))->where('reason','like','%'.$reason.'%')->select();
            $count = db('crm_s_changedate_reason')->where('brandclass_id',session('brandclass_id'))->where('reason','like','%'.$reason.'%')->count();
            if($res){
                $result['data'] = $res;
                $result['count'] = $count;
            }else{
                $result['data'] = array();
            }
            return ($result);
        }
        //核销取消原因列表
        public function getHXCancelReasonToJSON(){
            $reason = input('param.reason');
            $result['code'] = 0;
            $result['msg'] = '';
            $res = db('crm_s_hx_cancel_reason')->where('brandclass_id',session('brandclass_id'))->where('reason','like','%'.$reason.'%')->select();
            $count = db('crm_s_hx_cancel_reason')->where('brandclass_id',session('brandclass_id'))->where('reason','like','%'.$reason.'%')->count();
            if($res){
                $result['data'] = $res;
                $result['count'] = $count;
            }else{
                $result['data'] = array();
            }
            return ($result);
        }
        /**
         * @cc 新增核销改期原因
         * */
        public function addChangeDateReason(){
            $param = input();
            $data['brandclass_id'] = session('brandclass_id');
            $data['brandclass'] = session('brandclass');
            $data['reason'] = trim($param['reason']);
            if(db('crm_s_changedate_reason')->where($data)->find()){
                return array('code'=>100,'msg'=>'已有此原因，请改名！','data'=>'');
            }
            db()->startTrans();
            try{
                db('crm_s_changedate_reason')->insert($data);
                action_log('添加核销改期原因：'.$data['reason'],'',0,session('staff_id'),session('staff_name'));
                db()->commit();
                return array('code'=>200,'msg'=>'添加核销改期原因成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'添加改期原因失败','data'=>$e->getMessage());
            }
        }
        /**
         * @cc 新增核销取消原因
         * */
        public function addCancelReason(){
            $param = input();
            $data['brandclass_id'] = session('brandclass_id');
            $data['brandclass'] = session('brandclass');
            $data['reason'] = trim($param['reason']);
            if(db('crm_s_hx_cancel_reason')->where($data)->find()){
                return array('code'=>100,'msg'=>'已有此原因，请改名！','data'=>'');
            }
            db()->startTrans();
            try{
                db('crm_s_hx_cancel_reason')->insert($data);
                action_log('添加核销取消原因：'.$data['reason'],'',0,session('staff_id'),session('staff_name'));
                db()->commit();
                return array('code'=>200,'msg'=>'添加核销取消原因成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'添加取核销消原因失败','data'=>$e->getMessage());
            }
        }
        /**
         * @cc 修改核销改期原因
         * */
        public function editChangeDateReason(){
            $param = input();
            $id = $param['id'];
            $data['brandclass_id'] = session('brandclass_id');
            $data['reason'] = trim($param['reason']);
            if(db('crm_s_changedate_reason')->where('id','<>',$id)->where($data)->find()){
                return array('code'=>100,'msg'=>'已有此原因，请改名！','data'=>'');
            }
            $reason = db('crm_s_changedate_reason')->where('id',$id)->value('reason');
            db()->startTrans();
            try{
                db('crm_s_changedate_reason')->where('id',$id)->update($data);
                action_log('修改核销改期原因：'.$reason.'->'.$data['reason'],'',0,session('staff_id'),session('staff_name'));
                db()->commit();
                return array('code'=>200,'msg'=>'添加核销改期原因成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'添加改期原因失败','data'=>$e->getMessage());
            }
        }
        /**
         * @cc 修改核销取消原因
         * */
        public function editCancelReason(){
            $param = input();
            $id = $param['id'];
            $data['brandclass_id'] = session('brandclass_id');
            $data['reason'] = trim($param['reason']);
            if(db('crm_s_hx_cancel_reason')->where('id','<>',$id)->where($data)->find()){
                return array('code'=>100,'msg'=>'已有此原因，请改名！','data'=>'');
            }
            $reason = db('crm_s_hx_cancel_reason')->where('id',$id)->value('reason');
            db()->startTrans();
            try{
                db('crm_s_hx_cancel_reason')->where('id',$id)->update($data);
                action_log('修改核销取消原因：'.$reason.'->'.$data['reason'],'',0,session('staff_id'),session('staff_name'));
                db()->commit();
                return array('code'=>200,'msg'=>'添加核销取消原因成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'添加取核销消原因失败','data'=>$e->getMessage());
            }
        }
        /**
         * @cc 删除核销取消原因
         * */
        public function delCancelReason(){
            $id = input('param.id');
            db()->startTrans();
            try{
                db('crm_s_hx_cancel_reason')->where('id',$id)->delete();
                action_log('删除核销取消原因：'.input('param.reason'),'',0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'删除核销取消原因成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'删除核销取消原因失败','data'=>$e->getMessage());
            }
        }
        /**
         * @cc 删除核销改期原因
         * */
        public function delChangeDateReason(){
            $id = input('param.id');
            db()->startTrans();
            try{
                db('crm_s_changedate_reason')->where('id',$id)->delete();
                action_log('删除核销改期原因：'.input('param.reason'),'',0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'删除核销改期原因成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'删除核销改期原因失败','data'=>$e->getMessage());
            }
        }
        //取消原因设定
        public function cancelReason(){
            return $this->fetch();
        }
    /*------------------------------------------------------- 核销相关 开始 ------------------------------------------------------- */

    /*--------------------------------------------------- 预约上门排程设定 开始 ---------------------------------------------------*/
        /**
         * 上门排程设定 - 页面
         *
         * @param   nothing
         * @return  page
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function SmpcSet(){
            //排程设置
            if(session('shop_type') == 2){
                $pc = db_config('paicheng_'.session('shop_code'));
                $this->assign('pc',$pc);

                $week = getdateArea('this_week');
                $time['start']= date('Y-m-d', strtotime($week['0']));
                $time['end']  = date('Y-m-d', strtotime($week['1']));
                $this->assign('time',$time);
                return $this->fetch();
            }
        }
        /**
         * 上门排程设定 - 页面数据
         *
         * @param   nothing
         * @return  page
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function getSmPCToJSON(){
            $data = input();
            $page = $data['page'] ? $data['page'] : 1;
            $limit = $data['limit'] ? $data['limit'] : 20;
            $shop_code = session('shop_code');

            $where['shop_code']= $shop_code;
            $where['pc_type']  = 2;
            $whereSql = '1=1';

            if (!$data['ysm_start'] && !$data['ysm_end']) {
                $week = getdateArea('this_week');
                $whereSql .= ' and setting_date >= "'.date('Y-m-d',strtotime($week[0])).'" and setting_date <= "'.date('Y-m-d',strtotime($week[1])).'"';
            }else if ($data['ysm_start'] && !$data['ysm_end']) {
                $whereSql .= ' and setting_date >= "'.date('Y-m-d',strtotime($data['ysm_start'])).'"';
            }else if (!$data['ysm_start'] && $data['ysm_end']) {
                $whereSql .= ' and setting_date <= "'.date('Y-m-d',strtotime($data['ysm_end'])).'"';
            }else if ($data['ysm_start'] && $data['ysm_end']) {
                $whereSql .= ' and setting_date >= "'.date('Y-m-d',strtotime($data['ysm_start'])).'" and setting_date <= "'.date('Y-m-d',strtotime($data['ysm_end'])).'"';
            }

            $result['code'] = 0;
            $result['msg'] = '';
            $res = db('crm_l_pc_setting_log')
                ->where($where)
                ->where($whereSql)
                ->order('sm_type,setting_date asc')
                // ->order('setting_date desc')
                ->page($page)
                ->limit($limit)
                ->select();
            $sql = db()->getLastSql();
            foreach($res as $k=>$v){
                if ($v['num']===NULL) {
                    $res[$k]['num'] = '--';
                }
                if ($v['week'] == '0') {
                    $res[$k]['week'] = '星期日';
                }else if ($v['week'] == '1') {
                    $res[$k]['week'] = '星期一';
                }else if ($v['week'] == '2') {
                    $res[$k]['week'] = '星期二';
                }else if ($v['week'] == '3') {
                    $res[$k]['week'] = '星期三';
                }else if ($v['week'] == '4') {
                    $res[$k]['week'] = '星期四';
                }else if ($v['week'] == '5') {
                    $res[$k]['week'] = '星期五';
                }else if ($v['week'] == '6') {
                    $res[$k]['week'] = '星期六';
                }

                if($v['setting_date'] >= date('Y-m-d')){
                    $res[$k]['is_show'] = 1;
                }else{
                    $res[$k]['is_show'] = 0;
                }
            }
            $count = db('crm_l_pc_setting_log')->where($where)->where($whereSql)->count();
            if($res){
                $result['data'] = $res;
                $result['count'] = $count;
            }else{
                $result['data'] = array();
            }
            $result['sql'] = $sql;
            return ($result);
        }
        /**
         * 上门排程设定 - 新增/编辑(按周)
         *
         * @param   nothing
         * @return  page
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function addSmPcByWeek(){
            if(request()->isAjax()){
                $data = input();
                if(empty($data['sm_type'])){
                    return array('code'=>100,'msg'=>'上门类型不能为空','data'=>'');
                }
                $time = getDateFromRange($data['start'],$data['end']);

                $shop_code = session('shop_code');
                $shop_name = session('shop_name');

                $temp = [];
                $new_time = [];
                foreach($time as $k=>$v){
                    $temp[$v] = date('w',strtotime($v));
                    $new_time[] = $v;
                }
                $arr = [];
                $logs = [];
                foreach($new_time as $k=>$v){
                    $num = NULL;
                    if($temp[$v] == 1){
                        if ($data['one'] || $data['one'] === '0') {
                            $num = (int)$data['one'];
                        }
                    }elseif($temp[$v] == 2){
                        if ($data['two'] || $data['two'] === '0') {
                            $num = (int)$data['two'];
                        }
                    }elseif($temp[$v] == 3){
                        if ($data['three'] || $data['three'] === '0') {
                            $num = (int)$data['three'];
                        }
                    }elseif($temp[$v] == 4){
                        if ($data['four'] || $data['four'] === '0') {
                            $num = (int)$data['four'];
                        }
                    }elseif($temp[$v] == 5){
                        if ($data['five'] || $data['five'] === '0') {
                            $num = (int)$data['five'];
                        }
                    }elseif($temp[$v] == 6){
                        if ($data['six'] || $data['six'] === '0') {
                            $num = (int)$data['six'];
                        }
                    }elseif($temp[$v] == 0){
                        if ($data['seven'] || $data['seven'] === '0') {
                            $num = (int)$data['seven'];
                        }
                    }
                    $pc = [
                        'num' => $num,
                        'setting_date'=> $v,
                        'week' => $temp[$v],    
                        'staff_id' => session('staff_id'),
                        'staff_name' => session('staff_name'),
                        'shop_code' => $shop_code,
                        'shop_name' => $shop_name,
                        'ip' => get_client_ip(),
                        'pc_type' => 2,
                        'sm_type' => $data['sm_type'],
                        'create_time'=> date('Y-m-d H:i:s')
                    ];
                    $log['module']     = 'crm';
                    $log['controller'] = 'Setting';
                    $log['action']     = 'addSmPcByWeek';
                    $log['old_data']   = json_encode([]);
                    $log['data']       = json_encode($pc);
                    $log['customer_id']= 0;
                    $log['staff_name'] = session('staff_name');
                    $log['staff_id']   = session('staff_id');
                    $log['ip']         = get_client_ip();
                    $log['create_time']= date('Y-m-d H:i:s');
                    $logs[] = $log;
                    $arr[] = $pc;
                }
                $whereDel['shop_code']= $shop_code;
                $whereDel['pc_type']  = 2;
                try{
                    db('crm_l_pc_setting_log')->where($whereDel)
                        ->where('setting_date', '>=', $data['start'])
                        ->where('setting_date', '<=', $data['end'])
                        ->where('sm_type',$data['sm_type'])
                        ->delete();
                    db('crm_l_pc_setting_log')->insertAll($arr);
                    db('crm_action_log','db_logs')->insertAll($logs);

                    db()->commit();
                    db_config('add_smPcSet_'.$shop_code, json_encode($data));
                    return array('code'=>200,'msg'=>'上门排程次数设定成功','data'=>'');
                }catch (\Exception $e){
                    db()->rollback();
                    return array('code'=>100,'msg'=>'上门排程次数设定失败','data'=>$e->getMessage());
                }
            }else {
                $old_data = db_config('add_smPcSet_'.session('shop_code'));
                // 店面列表
                $shop = controller('crm/Customer', 'lib')->get_shop(['brandclass_id' => session('brandclass_id')]);
                $this->assign('shop', $shop);
                
                if ($old_data) {
                    $yjdinfo['shop_code'] = $old_data['shop_code'];
                    $yjdinfo['shop_name'] = $old_data['shop_name'];
                    $this->assign('smpcinfo',$old_data);

                    // 开始结束时间
                    $start= date('Y-m-d',strtotime($old_data['start']));
                    $end  = date('Y-m-d',strtotime($old_data['end']));
                }
                // 开始结束时间
                $start= $start ? $start : date('Y-m-d', time());
                $end  = $end ? $end : date('Y-m-d', strtotime("$start +1 month -1 day"));
                $this->assign('start', $start);
                $this->assign('end', $end);
                //上门类型
                $type = db('crm_s_pc_type_set')->where('status',2)->select();
                if(empty($type)){
                    $type = [
                        0=>['sm_type'=>'拍摄'],
                        1=>['sm_type'=>'理发'],
                        2=>['sm_type'=>'售后'],
                        3=>['sm_type'=>'其它']
                    ];
                }
                $this->assign('type',$type);
                return $this->fetch();
            }
        }
        /**
         * 上门排程设定 - 编辑(按天)
         *
         * @param   nothing
         * @return  page
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function editSmpc(){
            if(request()->isAjax()){
                $data = input();
                $arr = [
                    'sm_type' => $data['sm_type'],
                    'num' => $data['num'],
                    'staff_id' => session('staff_id'),
                    'staff_name' => session('staff_name'),
                    'ip' => get_client_ip(),
                    'pc_type' => 2,
                    'create_time'=> date('Y-m-d H:i:s')
                ];
                $sWhere['pc_type'] = 2;
                $sWhere['sm_type'] = $data['sm_type'];
                $sWhere['shop_code'] = trim($data['shop_code']);
                $sWhere['setting_date']= date('Y-m-d', strtotime($data['time'][0]));
                $set = db('crm_l_pc_setting_log')->where($sWhere)->where('id','<>',$data['id'])->find();

                if($set){
                    return array('code'=>102,'msg'=>'已有此排程，不能修改','data'=>'');
                }
                $res = db('crm_l_pc_setting_log')->where('id',$data['id'])->find();
                if($res['setting_date'] < date('Y-m-d')){
                    return array('code'=>101,'msg'=>'已是之前排程，不能修改','data'=>'');
                }
                try{
                    db('crm_l_pc_setting_log')->where('id',$data['id'])->update($arr);
                    db()->commit();
                    action_log($data,$res,0,session('staff_id'),session('staff_name'));
                    return array('code'=>200,'msg'=>'每天排程次数设定成功','data'=>'');
                }catch (\Exception $e){
                    db()->rollback();
                    return array('code'=>100,'msg'=>'每天排程次数设定失败','data'=>$e->getMessage());
                }
            }else {
                $id = input('param.id');
                $res = db('crm_l_pc_setting_log')->where('id',$id)->find();
                if ($res['week'] == '0') {
                    $res['week'] = '星期日';
                }else if ($res['week'] == '1') {
                    $res['week'] = '星期一';
                }
                else if ($res['week'] == '2') {
                    $res['week'] = '星期二';
                }
                else if ($res['week'] == '3') {
                    $res['week'] = '星期三';
                }
                else if ($res['week'] == '4') {
                    $res['week'] = '星期四';
                }
                else if ($res['week'] == '5') {
                    $res['week'] = '星期五';
                }
                else if ($res['week'] == '6') {
                    $res['week'] = '星期六';
                }
                $this->assign('info',$res);
                // var_dump($res);die;
                return $this->fetch();
            }
        }
        /**
         * 上门排程设定 - 删除
         *
         * @param   nothing
         * @return  page
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function delMoreSmPC(){
            $data = input();
            $old = db('crm_l_pc_setting_log')->where('id','in',$data['id'])->select();
            $msg = '';
            foreach($old as $k=>$v){
                $msg .= '删除的上门排程设定ID为【'.$v['id'].'】;';
                $msg .= '排程数量为：【'.$v['num'].'】;';
            }
            db()->startTrans();
            try{
                db('crm_l_pc_setting_log')->where('id','in',$data['id'])->delete();
                action_log($data['id'],$msg,0,session('staff_id'),session('staff_name'));
                db()->commit();
                return array('code'=>200,'msg'=>'批量删除排程成功','data'=>'');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'批量删除排程失败','data'=>$e->getMessage());
            }
        }
    /*--------------------------------------------------- 预约上门排程设定 结束 ---------------------------------------------------*/

    /*-------------------------------------------------- 预约上门客资列表、功能 开始 --------------------------------------------------*/
        /**
         * 上门客资列表 - 页面
         *
         * @param   nothing
         * @return  page
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function toHome(){
            $brandclass_id = session('brandclass_id');
            $shop_code = session('shop_code');
            //改期原因
            $gq = db('crm_s_changedate_reason')->where('brandclass_id',$brandclass_id)->select();
            $this->assign('gq',$gq);
            //取消原因
            $cancel = db('crm_s_hx_cancel_reason')->where('brandclass_id',$brandclass_id)->select();
            $this->assign('cancel',$cancel);
            // 地区
            $arae = db('crm_s_shop_address')->where('type', 3)->where('shop_code', $shop_code)->select();
            $this->assign('arae',$arae);
            // 渠道
            $channel = controller('crm/Customer','lib')->getChannel($shop_code);
            $this->assign('channel',$channel);
            // 来源
            $cource = controller('crm/Customer','lib')->source($shop_code);
            $this->assign('cource',$cource);
            // 今天
            $today = date('Y-m-d');
            $this->assign('today',$today);
            // 查人
            $data['shop_code'] = $shop_code;
            // 邀约人(网销)
            $data['work_type'] = RECEIVE_WORK_TYPE;
            $sales_staff = getShopStaffs($data);
            $this->assign('sales_staff',$sales_staff);
            //摄影师
            $data['work_type'] = PZ_WORK_TYPE;
            $cameramans = getShopStaffs($data);
            $this->assign('cameramans',$cameramans);
            //导师
            $data['work_type'] = 25;
            $tutors = getShopStaffs($data);
            $this->assign('tutors',$tutors);
            // 分组
            $param['shop_code']= $shop_code;
            $param['date']     = $today;
            $param['end']      = $today;
            $smgroup = controller('crm/Visit', 'lib')->getSmGroup($param);
            $this->assign('smgroup',$smgroup);
            // 上门类型
            $smtype = db('crm_s_pc_type_set')->where('status',2)->order('id desc')->select();
            $this->assign('smtype',$smtype);
            $this->assign('hiddenColumns',explode('|',cookie('tohome_colums_hidden')));
            /*
            上门状态[
                1：未上门；
                2：已上门（核销）
                3：已成交（上门开单，即在上门拍列表开单，或在手机端预约上页面开单）；
                4：已取消（在上门拍页面取消）；默认不显示
                5：已删除（改期，默认上一条客资删除）；默认不显示
            ]
            */
            return $this->fetch('tohome');
        }
        public function getPCCount(){
            $param = input();
            $start = $param['start'] ? date('Y-m-d H:i:s',strtotime($param['start'])):date('Y-m-d 00:00:00');
            $end = $param['end'] ? date('Y-m-d 23:59:59',strtotime($param['end'])):date('Y-m-d 23:59:59');
            $whereTime = ' l.pc_time between \''.$start.'\' and \''.$end.'\' ';
            $result['code'] = 0;
            $result['msg'] = '';
            $page = $param['page'] ? $param['page'] : 1;
            $limit = $param['limit'] ? $param['limit'] : 100;

            $shop_code = session('shop_code');
            $where['l.pc_type'] = 2;
            // 查询 已删除 的预约上门  默认不显示
            if ($param['smstatus']==99) {
                $where['l.is_delete'] = 1;
            }else{
                $where['l.is_delete'] = 2;
            }
            // 查询 已取消 的预约上门  默认不显示
            // if ($param['smstatus']==4) {
            //     $where['l.status'] = 4;
            // }else{
            //     $where['l.status'] = ['<','4'];
            // }
            if ($param['smstatus']) {
                $where['l.status'] = $param['smstatus'];
            }else{
                $where['l.status'] = ['<','4'];
            }
            // 查询本店上门拍
            if(check_right('menu1576489359')){
                $where['l.pc_shop_code|l.shop_code'] = $shop_code;
                // if ($shop_code!=='xaf002') {
                //     $where['l.pc_shop_code'] = $shop_code;
                // }
            }
            // 查询本人上门拍
            elseif(check_right('menu1576489412')){
                $where['l.cameraman_id|l.tutor_id|c.sales_staff_id'] = session('staff_id');
            }else{
                $result['data'] = 0;
                $result['count']= 0;
                return json($result);
                // return $this->redirect('crm/Index/index');
            }

            // 宝宝姓名
            if($param['baby_name']){
                $where['c.baby_name'] = ['like','%'.trim($param['baby_name']).'%'];
            }
            // 妈妈名字
            if($param['customer_name']){
                $where['c.customer_name'] = ['like','%'.trim($param['customer_name']).'%'];
            }
            // 妈妈手机号
            if($param['customer_tel']){
                $whereTime = '';
                $where['c.customer_tel'] = trim($param['customer_tel']);
            }
            // 爸爸名字
            if($param['mate_name']){
                $where['c.mate_name'] = ['like','%'.trim($param['mate_name']).'%'];
            }
            // 爸爸手机号
            if($param['mate_tel']){
                $whereTime = '';
                $where['c.mate_tel'] = trim($param['mate_tel']);
            }
            // 核销码
            if($param['code']){
                $where['l.code'] = trim($param['code']);
            }
            // 上门类型
            if($param['sm_type']){
                $where['l.sm_type'] = trim($param['sm_type']);
            }
            // 分组
            if($param['smgroup']){
                // $where['l.smgroup'] = ['like','%'.trim($param['smgroup'].'%')];
                $where['l.smgroup'] = trim($param['smgroup']);
            }
            // 邀约人
            if($param['sale_id']){
                $where['c.sales_staff_id'] = trim($param['sale_id']);
            }
            // 摄影师
            if($param['cameraman_id']){
                $where['l.cameraman_id'] = trim($param['cameraman_id']);
            }
            // 导师
            if($param['tutor_id']){
                $where['l.tutor_id'] = trim($param['tutor_id']);
            }
            // 地区
            if($param['county']){
                $where['c.county_id'] = (int)$param['county'];
            }
            // 渠道
            if($param['customer_channel']){
                $where['c.customer_channel_id'] = (int)$param['customer_channel'];
            }
            // 来源
            if($param['customer_cource']){
                $where['c.customer_cource_id'] = (int)$param['customer_cource'];
            }
            
            $all = db('crm_l_pc_log')->alias('l')
                ->join('crm_c_customerinfo c','c.c_unique=l.c_unique and c.id=l.cid','left')
                ->where('l.pc_time','between',[$start,$end])
                ->where($where)
                ->where($sql)
                ->column('l.id');
            $sql1 = db()->getLastSql();
            //上门状态
            $status = db('crm_l_pc_log')->alias('l')
                ->join('crm_c_customerinfo c','c.c_unique=l.c_unique and c.id=l.cid','left')
                ->where('l.pc_time','between',[$start,$end])
                ->where($where)
                ->where($sql)
                ->group('status')
                ->column('count(l.id)','l.status');
            $sql2 = db()->getLastSql();
            //按组分组
            $where['l.smgroup'] = ['not null'];
            $group = db('crm_l_pc_log')->alias('l')
                ->join('crm_c_customerinfo c','c.c_unique=l.c_unique and c.id=l.cid','left')
                ->where('l.pc_time','between',[$start,$end])
                // ->fetchSql()
                ->where($where)
                ->where($sql)
                ->group('l.smgroup')
                ->column('count(l.id)','l.smgroup');
            $sql3 = db()->getLastSql();
            $owhere = [];
            if($param['small'] || $param['big']){
                $small = $param['small'] ? $param['small'] : 0;
                $big = $param['big'] ? $param['big'] : 0;
                $owhere['yixiaoshishou'] = ['between',[$small,$big]];
            }
            //一销套系，实收
            $order = db('c_customerorder')
                ->where('crm_visit_id', 'in',$all)
                ->where($owhere)
                ->field('sum(bargain_money)as amount,sum(yixiaoshishou) as fact')
                ->find();
            $sql4 = db()->getLastSql();
            //把删除数量取出来，算取消---待定-sdm
            /*
            $where['l.is_delete'] = 1;
            $delete = db('crm_l_pc_log')->alias('l')
                ->join('crm_c_customerinfo c','c.c_unique=l.c_unique and c.id=l.cid','left')
                ->where('l.pc_time','between',[$start,$end])
                ->where($where)
                ->where($sql)
                ->count();
            $status[4] += $delete;
            */
            return array(
                'sql1'=>$sql1,
                'sql2'=>$sql2,
                'sql3'=>$sql3,
                'sql4'=>$sql4,
                'all' => count($all),
                'status1' => $status[1] ? $status[1] : 0,
                'status2' => $status[2] ? $status[2] : 0,
                'status3' => $status[3] ? $status[3] : 0,
                'status4' => $status[4] ? $status[4] : 0,
                'intoRate' => sprintf('%.2f',($status[2]+$status[3])/count($all)*100).'%',
                'orderRate' => sprintf('%.2f',$status[2]/count($all)*100).'%',
                'cancerRate' => sprintf('%.2f',$status[4]/count($all)*100).'%',
                'amount'    => $order['amount'] ? $order['amount'] : 0,
                'fact'    => $order['fact'] ? $order['fact'] : 0,
                'group'     => $group,
            );
        }
        /**
         * 上门客资列表 - 数据
         *
         * @param   nothing
         * @return  page
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function customerListHome(){
            $param = input();
            $start = $param['start'] ? date('Y-m-d H:i:s',strtotime($param['start'])):date('Y-m-d 00:00:00');
            $end = $param['end'] ? date('Y-m-d 23:59:59',strtotime($param['end'])):date('Y-m-d 23:59:59');
            $whereTime = ' l.pc_time between \''.$start.'\' and \''.$end.'\' ';
            $result['code'] = 0;
            $result['msg'] = '';
            $page = $param['page'] ? $param['page'] : 1;
            $limit = $param['limit'] ? $param['limit'] : 100;

            $shop_code = session('shop_code');
            $where['l.pc_type'] = 2;
            // 查询 已删除 的预约上门  默认不显示
            if ($param['smstatus']==99) {
                $where['l.is_delete'] = 1;
            }else{
                $where['l.is_delete'] = 2;
            }
            // 查询 已取消 的预约上门  默认不显示
            // if ($param['smstatus']==4) {
            //     $where['l.status'] = 4;
            // }else{
            //     $where['l.status'] = ['<','4'];
            // }
            if ($param['smstatus']) {
                $where['l.status'] = $param['smstatus'];
            }else{
                $where['l.status'] = ['<','4'];
            }
            // 查询本店上门拍
            if(check_right('menu1576489359')){
                $where['l.pc_shop_code|l.shop_code'] = $shop_code;
                // if ($shop_code!=='xaf002') {
                //     $where['l.pc_shop_code'] = $shop_code;
                // }
            }
            // 查询本人上门拍
            elseif(check_right('menu1576489412')){
                $where['l.cameraman_id|l.tutor_id|c.sales_staff_id'] = session('staff_id');
            }else{
                $result['data'] = 0;
                $result['count']= 0;
                return json($result);
                // return $this->redirect('crm/Index/index');
            }
            // 宝宝姓名
            if($param['baby_name']){
                $where['c.baby_name'] = ['like','%'.trim($param['baby_name']).'%'];
            }
            // 妈妈名字
            if($param['customer_name']){
                $where['c.customer_name'] = ['like','%'.trim($param['customer_name']).'%'];
            }
            // 妈妈手机号
            if($param['customer_tel']){
                $whereTime = '';
                $where['c.customer_tel'] = trim($param['customer_tel']);
            }
            // 爸爸名字
            if($param['mate_name']){
                $where['c.mate_name'] = ['like','%'.trim($param['mate_name']).'%'];
            }
            // 爸爸手机号
            if($param['mate_tel']){
                $whereTime = '';
                $where['c.mate_tel'] = trim($param['mate_tel']);
            }
            // 核销码
            if($param['code']){
                $where['l.code'] = trim($param['code']);
            }
            // 上门类型
            if($param['sm_type']){
                $where['l.sm_type'] = trim($param['sm_type']);
            }
            // 分组
            if($param['smgroup']){
                // $where['l.smgroup'] = ['like','%'.trim($param['smgroup'].'%')];
                $where['l.smgroup'] = trim($param['smgroup']);
            }
            // 邀约人
            if($param['sale_id']){
                $where['c.sales_staff_id'] = trim($param['sale_id']);
            }
            // 摄影师
            if($param['cameraman_id']){
                $where['l.cameraman_id'] = trim($param['cameraman_id']);
            }
            // 导师
            if($param['tutor_id']){
                $where['l.tutor_id'] = trim($param['tutor_id']);
            }
            // 地区
            if($param['county']){
                $where['c.county_id'] = (int)$param['county'];
            }
            // 渠道
            if($param['customer_channel']){
                $where['c.customer_channel_id'] = (int)$param['customer_channel'];
            }
            // 来源
            if($param['customer_cource']){
                $where['c.customer_cource_id'] = (int)$param['customer_cource'];
            }
            $owhere = [];
            if($param['small'] || $param['big']){
                $small = $param['small'] ? $param['small'] : 0;
                $big = $param['big'] ? $param['big'] : 0;
                $owhere['payment_money'] = ['between',[$small,$big]];
                $where['l.status'] = 2;
            }
            
            $info = db('crm_l_pc_log')->alias('l')
                ->join('crm_c_customerinfo c','c.id=l.cid','left')
                ->join('c_customerorder o', 'o.crm_visit_id=l.id', 'left')
                ->join('crm_s_channel sc', 'c.customer_channel_id=sc.id', 'left')
                ->where($whereTime)
                ->where($where)
                // ->where($sql)
                ->order('l.smgroup desc,c.county')
                ->field('l.id,l.cid,l.status,l.is_delete,l.smgroup,l.cameraman_name,l.tutor_name,l.pc_time,l.time,l.code,l.pc_shop_name,l.shop_name,l.sm_type,l.consulation_type,l.remark,l.reason,l.sale_name,l.visit_order,l.cloth,c.sales_staff,c.sales_staff_id,c.customer_name,c.customer_tel,c.mate_name,c.mate_tel,DATE_FORMAT(c.baby_birthday, "%Y-%m-%d") as baby_birthday,c.baby_name,c.baby_sex,c.customer_channel,sc.channel_info_name,c.sign_name,c.customer_cource,c.province,c.city,c.county,c.customer_address,c.baby_address,c.customer_remark, o.package_name,GROUP_CONCAT(o.orderId) as orderIds,SUM(bargain_money) as orderTotal, SUM(yixiaoshishou) as orderFact')
                ->group('l.id')
                ->page($page)->limit($limit)
                ->select();
            $sql = db('crm_l_pc_log')->getLastSql();
            foreach ($info as $key => $value) {
                if ($value['status']==1 && $value['is_delete']==2) {
                    $info[$key]['status'] = '未上门';
                }else if ($value['status']==2) {
                    $info[$key]['status'] = '已成交';
                }else if ($value['status']==3) {
                    $info[$key]['status'] = '未成交';
                }else if ($value['status']==4) {
                    $info[$key]['status'] = '已取消';
                }else if ($value['is_gq']==2) {
                    $info[$key]['status'] = '已改期';
                }else if ($value['status']==99) {
                    $info[$key]['status'] = '已删除';
                }else{
                    $info[$key]['status'] = '未上门';
                }
            }
            $count = db('crm_l_pc_log')->alias('l')
                ->join('crm_c_customerinfo c','c.id=l.cid','left')
                ->where($whereTime)
                ->where($where)
                // ->where($sql)
                ->group('l.id')
                ->count();
            $result['data'] = $info;
            $result['count'] = $count;
            $result['sql'] = $sql;
            
            //导出  explode =1
            if ($param['explode'] == 1) {
                if ($count > 0) {
                    set_time_limit(0);
                    $file = 'tohome.csv';
                    //ini_set('memory_limit', '256M');
                    //不限制内存了，按PHP.INI给多大，这里就能导多大。
                    $title=export_tohome_child();
                    foreach ($title as $key => $value) {
                        $title[$key] = iconv("UTF-8", "GBK", $value);
                    }
                    $fp = fopen('php://output', 'a');
                    fputcsv($fp, $title);

                    header('Content-Type: application/vnd.ms-execl');
                    header("Content-type:text/csv;charset=utf-8");
                    header("Cache-Control: public");
                    header("Content-Description: File Transfer");
                    header('Content-disposition: attachment; filename='.$file);

                    $pdo = db('crm_l_pc_log')->getConnection()->getPdo();
                    $pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
                    // 生成客资的查询语句
                    $field = 'l.smgroup,l.cameraman_name,l.tutor_name,l.pc_time,l.time,c.sales_staff,l.remark,c.customer_remark,c.province,c.city,c.county,c.customer_address,c.customer_name,c.customer_tel,c.mate_name,c.mate_tel,c.baby_address,c.baby_name,c.baby_sex,DATE_FORMAT(c.baby_birthday, "%Y-%m-%d") as baby_birthday,l.sm_type,l.consulation_type,c.customer_channel,sc.channel_info_name,c.sign_name,l.status,l.reason,l.sale_name,o.package_name,GROUP_CONCAT(o.orderId) as orderIds,SUM(bargain_money) as orderTotal,SUM(yixiaoshishou) as orderFact,l.pc_shop_name,l.code,l.cid';
                    $customerSql = db('crm_l_pc_log')->alias('l')
                                    ->join('crm_c_customerinfo c','c.id=l.cid','left')
                                    ->join('c_customerorder o', 'o.crm_visit_id=l.id', 'left')
                                    ->join('crm_s_channel sc', 'c.customer_channel_id=sc.id', 'left')
                                    ->where($whereTime)
                                    ->where($where)
                                    // ->where($sql)
                                    ->order('l.smgroup desc,c.county')
                                    ->field($field)
                                    ->group('l.id')
                                    ->fetchSql()
                                    ->select();

                    $sth = $pdo->prepare($customerSql);
                    $sth->execute();
                    $count = 0;

                    while ($value = $sth->fetch(\PDO::FETCH_ASSOC)) {

                        // if ($value['customer_type']) {
                        //     $value['customer_type'] = $value['customer_type']==1?'新客资':'转介绍';
                        // }

                        foreach ($value as $k => $v) {
                            $value[$k] = iconv("UTF-8", "GBK", $v);
                        }
                        ++$count;
                        fputcsv($fp, $value);
                        unset($value);
                        ob_flush();
                        flush();
                    }

                    $log = '由【'.session('staff_name').'】于【'.date('Y-m-d H:i:s').'】导出【'.session('shop_name').'】 预约上门拍【'.$count.'】条，所在IP【'.get_client_ip().'】';
                    //释放stmt内存
                    db('crm_l_pc_log')->getConnection()->free();
                    // echo '占用内存大小：' . memory_get_usage() . "\n";
                    //fputcsv($fp, ['运行内存：',memory_get_usage()]);
                    
                    /*
                    fclose($fp);
                    @readfile('upload'.DS.$file);
                    unlink('upload'.DS.$file);
                    */
                    action_log($log,$customerSql,0,session('staff_id'),session('staff_name'));
                    exit;
                }else{
                    $this->error('没有数据！');
                }
                exit;
            }

            return json($result);
        }
        // 取消，核销
        // 客资分组 页面
        public function setSmGroup(){
            return $this->fetch();
        }
        // 客资分组 功能
        public function setSmGroupAction(){
            $data = input();

            $smgroup = trim($data['smgroup']);
            if (!$smgroup) {
                $return['code'] = '101';
                $return['msg']  = '请设置分组名称。';
                return $return;
            }

            $ids = trim($data['ids'], ',');
            $smInfo = db('crm_l_pc_log')->where('id', 'in', $ids)->select();
            if (count(!$smInfo)<=0) {
                $return['code'] = '100';
                $return['msg']  = '请选择要分配的客资。';
                return $return;
            }
            $date = date('Y-m-d H:i:s');
            $ip = \think\Request::instance()->ip();
            $inids = '';
            $lData = [];
            foreach ($smInfo as $key => $value) {
                // 未上门
                if ($value['status']==1) {
                    $inids .= $value['id'].',';
                    // action_log 用数据
                    $temp['module']     = 'crm';
                    $temp['controller'] = 'Visit';
                    $temp['action']     = 'setSmGroupAction';
                    $temp['old_data']   = $value['smgroup'] ? '原上门组名：'.$value['smgroup'] : '无上门组别';
                    $temp['data']       = '上门组名：'.$smgroup;
                    $temp['customer_id']= $value['cid'];
                    $temp['staff_name'] = session('staff_name');
                    $temp['staff_id']   = session('staff_id');
                    $temp['ip']         = $ip;
                    $temp['create_time']= $date;
                    array_push($lData, $temp);
                }
            }
            $inids = trim($inids, ',');
            if (!$inids) {
                $return['code'] = '102';
                $return['msg']  = '暂无未上门客资。';
                return $return;
            }
            $up['smgroup'] = $smgroup;
            db()->startTrans();
            try {
                db('crm_l_pc_log')->where('id', 'in', $inids)->update($up);
                db('crm_action_log','db_logs')->insertAll($lData);
                $return['code'] = '200';
                $return['msg']  = '分组设置成功。';
                db()->commit();
            } catch (\Exception $e) {
                $return['code'] = '103';
                $return['msg']  = '设置分组失败，请重试。';
                $return['error']= $e->getMessage();
                db()->rollback();
            }
            return $return;
        }
        // 分配上门 页面
        public function cameramanFP(){
            $shop_code = session('shop_code');
            // 今天
            $today = date('Y-m-d');
            $this->assign('today',$today);
            // 是否根据选中店查询对应人员
            $getStaff = false;
            // 拍照店
            $shop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id'),'is_photo'=>1]);
            foreach ($shop as $key => $value) {
                // 如果当前店就是拍照店，则默认选中
                if ($value['shop_code'] == $shop_code) {
                    $shop[$key]['select'] = 1;
                    $getStaff = true;
                }else{
                    $shop[$key]['select'] = 2;
                }
            }
            $this->assign('shop',$shop);
            if ($getStaff) {
                // 导师
                $tParam['work_type'] = 25;
                $tParam['shop_code'] = $shop_code;
                $tutors = getShopStaffs($tParam);
                $this->assign('tutors',$tutors);
                // 摄影师
                $cParam['work_type'] = 3;
                $cParam['shop_code'] = $shop_code;
                $cameraman = getShopStaffs($cParam);
                $this->assign('cameraman',$cameraman);
            }
            
            // 查询当日分组信息
            $param['shop_code']= $shop_code;
            $param['date']     = $today;
            $param['end']      = $today;
            $smgroup = controller('crm/Visit', 'lib')->getSmGroup($param);
            // var_dump($smgroup);die;
            $this->assign('smgroup',$smgroup);

            return $this->fetch();
        }
        // 分配上门页面，ajax 日期切换 查询小组
        public function getSmGroup(){
            $param = input();
            $shop_code = session('shop_code');
            // 查询当日分组信息
            $sParam['shop_code']= $shop_code;
            $sParam['date']     = $param['pc_time'] ? date('Y-m-d', strtotime($param['pc_time'])) : date('Y-m-d');
            $sParam['end']      = $param['end_time'] ? date('Y-m-d', strtotime($param['end_time'])) : $sParam['date'];
            $smgroup = controller('crm/Visit', 'lib')->getSmGroup($sParam);
            return json($smgroup);
        }
        // 分配上门页面ajax查询客资
        public function getGroupCustomer(){
            $param = input();
            $shop_code = session('shop_code');
            $pc_time = trim($param['pc_time']);
            if (!$pc_time) {
                return array('code'=>100, 'msg'=>'请选择预约上门时间');
            }
            $where['l.pc_shop_code'] = $shop_code;
            $where['l.pc_time'] = date('Y-m-d', strtotime($pc_time));
            if($param['smgroup']){
                $where['l.smgroup'] = $param['smgroup'];
            }
            $groupCustomer = db('crm_l_pc_log')->alias('l')
                ->join('crm_c_customerinfo c','c.id=l.cid','left')
                ->where($where)
                ->field('l.id,l.smgroup,c.county,c.customer_name,c.customer_tel')
                ->select();
            foreach ($groupCustomer as $key => $value) {
                $groupCustomer[$key]['smgroup'] = $value['smgroup'] ? $value['smgroup'] : '未分组';
            }
            return json($groupCustomer);
        }
        // 分配上门页面ajax切换服务店面获取上门员工
        public function getSmStaffs(){
            $param = input();
            $shop_code = trim($param['shop_code']);
            // 导师
            $tParam['work_type'] = 25;
            $tParam['shop_code'] = $shop_code;
            $return['tutors'] = getShopStaffs($tParam);
            // 摄影师
            $cParam['work_type'] = 3;
            $cParam['shop_code'] = $shop_code;
            $return['cameraman'] = getShopStaffs($cParam);
            return json($return);
        }
        //分配 功能
        public function fpCamera(){
            $param = input();
            $pc_time = trim($param['pc_time']);
            if (!$pc_time) {
                return array('code'=>100, 'msg'=>'请选择预约上门时间');
            }
            $shop_code = trim($param['pc_shop_code']);
            if (!$shop_code) {
                return array('code'=>101, 'msg'=>'请选择服务店面');
            }
            $tutor_id = (int)$param['tutor_id'];
            if (!$tutor_id) {
                return array('code'=>102, 'msg'=>'请选择上门导师');
            }
            $cameraman_id = (int)$param['cameraman_id'];
            if (!$cameraman_id) {
                return array('code'=>103, 'msg'=>'请选择上门摄影师');
            }
            $smWhere['status']  = 1;
            $smWhere['pc_type'] = 2;
            $smWhere['is_delete']=2;
            $smWhere['pc_time'] = $pc_time;
            $smWhere['smgroup'] = $param['smgroup'] ? trim($param['smgroup']) : NULL;
            $smWhere['pc_shop_code'] = $shop_code;
            $smCus = db('crm_l_pc_log')->where($smWhere)->select();

            if (!$smCus) {
                return array('code'=>104, 'msg'=>'未查询到‘未上门’的客资，请确认。','sql'=>db()->getLastSql());
            }

            $smids = '';
            foreach ($smCus as $key => $value) {
                $smids .= $value['id'].',';
                // 上门分配日志
                $fLog[$key]['cid']              = $value['cid'];
                $fLog[$key]['fp_model']         = 2;
                $fLog[$key]['fp_status']        = 1;
                $fLog[$key]['fp_time']          = date('Y-m-d H:i:s');
                $fLog[$key]['jr_time']          = date('Y-m-d H:i');
                $fLog[$key]['fp_staff_id']      = session('staff_id');
                $fLog[$key]['fp_staff_name']    = session('staff_name');
                $fLog[$key]['fp_shop_code']     = session('shop_code');
                $fLog[$key]['fp_shop_name']     = session('shop_name');
                $fLog[$key]['fp_brandclass_id'] = session('brandclass_id');
                $fLog[$key]['jr_staff_id']      = $cameraman_id;
                $fLog[$key]['jr_staff_name']    = trim($param['cameraman']).'/'.trim($param['tutor']);
                $fLog[$key]['jr_shop_code']     = $shop_code;
                $fLog[$key]['jr_shop_name']     = trim($param['pc_shop_name']);
            }
            $smids = trim($smids, ',');

            $smUpdate['pc_shop_code'] = $shop_code;
            $smUpdate['pc_shop_name'] = trim($param['pc_shop_name']);

            $smUpdate['tutor_id']  = $tutor_id;
            $smUpdate['tutor_name']= trim($param['tutor']);

            $smUpdate['cameraman_id']  = $cameraman_id;
            $smUpdate['cameraman_name']= trim($param['cameraman']);

            db()->startTrans();
            try {
                db('crm_l_pc_log')->where('id', 'in', $smids)->update($smUpdate);
                db('crm_l_camera_log')->insertAll($fLog);
                db()->commit();
                return array('code'=>200,'msg'=>'分配成功');
            } catch (\Exception $e) {
                db()->rollback();
                return array('code'=>199,'msg'=>'分配失败','data'=>$e->getMessage(),'sql'=>db()->getLastSql());
            }
        }
        //通过核销码获取客资信息
        public function tan_home_code(){
            $code = input('param.code');
            $info = db('crm_c_customerinfo')->alias('c')->join('crm_l_pc_log l','c.id=l.cid')
                ->where('l.shop_code',session('shop_code'))
                ->where('l.code',$code)
                ->field('l.id,l.cid,c.customer_name,c.customer_tel,l.result,customer_address,l.pc_time,l.pc_shop_name,l.cameraman_name,l.sale_name,l.tutor_name,l.remark,l.code,l.status,l.hx_time,l.staff_name,c.is_success')
                ->find();
            if($info['status'] && $info['status'] != 1){
                $this->assign('msg','此核销码已经核销过，不能再次操作');
                return $this->fetch();
            }
            if(empty($info)){
                $this->assign('msg','查无信息或此核销码已失效');
                return $this->fetch();
            }

            $info['customer_name'] = $info['customer_name'] ? $info['customer_name'] : '';
            $info['result'] = $info['result']==1 ? '未完成' : '已完成';
            $info['customer_address'] = $info['customer_address'] ? $info['customer_address'] : '';
            $info['pc_time'] = $info['pc_time'] ? $info['pc_time'] : '';
            $info['area_name'] = $info['area_name'] ? $info['area_name'] : '';
            $info['time'] = $info['time'] ? $info['time'] : '';
            $info['shop_name'] = $info['shop_name'] ? $info['shop_name'] : '';
            $info['pc_shop_name'] = $info['pc_shop_name'] ? $info['pc_shop_name'] : '';
            $info['cameraman_name'] = $info['cameraman_name'] ? $info['cameraman_name'] : '';
            $info['sale_name'] = $info['sale_name'] ? $info['sale_name'] : '';
            $info['tutor_name'] = $info['tutor_name'] ? $info['tutor_name'] : '';
            $info['remark'] = $info['remark'] ? $info['remark'] : '';
            $info['code'] = $info['code'] ? $info['code'] : '';

            $status = '';
            if($info['status'] == 2){
                $status = '已完成';
            }elseif($info['status'] == 3){
                $status = '已改期';
            }elseif($info['status'] == 4){
                $status = '已取消';
            }else{
                $status = '未开始';
            }
            //改期原因
            $gq = db('crm_s_changedate_reason')->where('brandclass_id',session('brandclass_id'))->select();
            $this->assign('gq',$gq);
            //取消原因
            $cancel = db('crm_s_hx_cancel_reason')->where('brandclass_id',session('brandclass_id'))->select();
            $this->assign('cancel',$cancel);
            $info['status'] = $status;
            $info['hx_time'] = $info['hx_time'] ? $info['hx_time'] : '';
            $info['staff_name'] = $info['staff_name'] ? $info['staff_name'] : '';
            $this->assign('info',$info);
            return $this->fetch();
        }
        //上门取消
        public function markHXHome(){
            $data = input();
            if(empty($data['cid'])){
                return array('code'=>100,'msg'=>'未获取到客资id');
            }
            if(empty($data['code'])){
                return array('code'=>101,'msg'=>'未获取到核销码');
            }

            db()->startTrans();
            try{
                $from = [
                    'staff_id'=>session('staff_id'),
                    'staff_name'=>session('staff_name'),
                    'reason'=>$data['reason'] ? $data['reason'] : NULL,
                    'status'=>4,
                ];
                db('crm_l_pc_log')->where('cid',intval($data['cid']))->where('code',$data['code'])->update($from);
                $log = '上门取消：操作人：'.session('staff_name');
                if($data['status']>2){
                    $log .= ',原因：'.$data['reason'];
                }
                db()->commit();
                action_log($log,[],$data['cid'],session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'上门取消成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>103,'msg'=>'上门取消失败','data'=>$e->getMessage());
            }
        }
        //核销
        public function markHX(){
            $data = input();
            if(empty($data['cid'])){
                return array('code'=>100,'msg'=>'未获取到客资id');
            }
            if(empty($data['code'])){
                return array('code'=>101,'msg'=>'未获取到核销码');
            }
            $pc = db('crm_l_pc_log')->where('cid',$data['cid'])->where('code',trim($data['code']))->value('id');
            if(!$pc){
                $return=array('error'=>102,'msg'=>'未通过核销码获取到排程信息','sql'=>db()->getLastSql());
                return json($return);
            }
            // $info = controller('crm/Customer','lib')->getCustomerInfo($data['cid']);
            db()->startTrans();
            try{
                $from = [
                    'staff_id'=>session('staff_id'),
                    'staff_name'=>session('staff_name'),
                    'status'=>3,
                    'hx_time'=>date('Y-m-d H:i:s')
                ];
                db('crm_l_pc_log')->alias('l')
                    ->where('l.cid',intval($data['cid']))
                    ->where('l.code',trim($data['code']))
                    ->update($from);

                db()->commit();
                action_log($data,[],$data['cid'],session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'核销成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>103,'msg'=>'核销失败','data'=>$e->getMessage());
            }
        }
        /**
         * 上门拍修改信息  
         *
         * @param  id                 上门拍id
         * @param  cid                客资id
         * @param  remark             上门拍备注
         * @param  customer_address   客资地址
         *
         * @author lilong<lilong@suxuantech.cn>
         */
        public function changeVisitInfo(){
            $data = input();
            $id = (int)$data['data']['id'];
            $cid= (int)$data['data']['cid'];
            $remark = trim($data['data']['remark']);
            $time = trim($data['data']['time']);
            $customer_address = trim($data['data']['customer_address']);
            $type = $data['data']['type'];
            if(!$id){
                return array('code'=>100,'msg'=>'未获取到上门ID');
            }
            if(!$cid){
                return array('code'=>101,'msg'=>'未获取到客资ID');
            }
            $pc = db('crm_l_pc_log')->where('id',$id)->find();
            if(!$pc){
                $return=array('error'=>102,'msg'=>'未找到上门信息，请确认','sql'=>db()->getLastSql());
                return json($return);
            }
            if ($pc['is_delete']==1) {
                $return=array('error'=>103,'msg'=>'该上门已删除，请重新确认！');
                return json($return);
            }
            if ($pc['status']==4) {
                $return=array('error'=>104,'msg'=>'该上门已取消，请重新确认！');
                return json($return);
            }
            $cInfo = db('crm_c_customerinfo')->where('id',$cid)->field('id,customer_address,is_status,c_unique,customer_number,customer_name')->find();
            if ($cInfo['is_status']<>1) {
                $return=array('error'=>105,'msg'=>'该客资已删除，请重新确认！');
                return json($return);
            }
            $track_log = '';
            switch ($type) {
                case 'remark':
                    if ($remark !== $pc['remark']) {
                        $track_log .= '上门拍修改‘上门备注’，由：'.$pc['remark'].'；修改为：'.$remark;
                        $pcData['remark'] = $remark;
                    }
                    break;
                case 'time':
                    if ($time !== $pc['time']) {
                        $track_log .= '上门拍修改‘上门时间’，由：'.$pc['time'].'；修改为：'.$time;
                        $pcData['time'] = $time;
                    }
                    break;
                case 'customer_address':
                    if ($customer_address !== $cInfo['customer_address']) {
                        $track_log .= '上门拍修改‘客户地址’，由：'.$cInfo['customer_address'].'；修改为：'.$customer_address;
                        $oldData['customer_address'] = $pc['customer_address'];
                        $newData['customer_address'] = $customer_address;
                        $cData['customer_address'] = $customer_address;
                    }
                    break;
            }
            
            db()->startTrans();
            try{
                if ($pcData) {
                    db('crm_l_pc_log')->where('id',$id)->update($pcData);
                }
                if ($cData) {
                    db('crm_c_customerinfo')->where('id',$cid)->update($cData);
                }
                // 操作记录
                action_log($newData,$oldData,$cid,session('staff_id'),session('staff_name'));
                // 追踪记录
                $params['c_unique'] = $cInfo['c_unique'];
                $params['customer_id'] = $cid;
                $params['customer_name'] = $cInfo['customer_name'];
                $params['customer_number'] = $cInfo['customer_number'];
                $params['sales_remark'] = $track_log;
                $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'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                db('crm_c_salestrackinginfo')->insert($params);
                cache('track_log_'.$cInfo['c_unique'],null);
                db()->commit();
                return array('code'=>200,'msg'=>'成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>103,'msg'=>'失败','data'=>$e->getMessage());
            }
        }
        //排程结果确认
        public function markResult(){
            $data = input();
            if(empty($data['id'])){
                return array('code'=>100,'msg'=>'未获取到id');
            }

            db()->startTrans();
            try{
                db('crm_l_pc_log')->where('id',intval($data['id']))->update(['result'=>intval($data['result'])]);
                db()->commit();
                action_log($data,[],$data['cid'],session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'确认成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>103,'msg'=>'确认失败','data'=>$e->getMessage());
            }
        }
        //通过核销码获取客资信息
        public function tan_code(){
            $code = input('param.code');
            $info = db('crm_c_customerinfo')->alias('c')->join('crm_l_pc_log l','c.id=l.cid')
                ->where('l.pc_shop_code',session('shop_code'))
                ->where('l.code',$code)
                ->field('l.id,l.cid,c.customer_name,c.customer_tel,l.result,customer_address,l.pc_time,l.area_name,l.time,c.shop_name,l.pc_shop_name,l.cameraman_name,l.sale_name,l.tutor_name,l.remark,l.code,l.status,l.hx_time,l.staff_name,c.is_success')
                ->find();
            if(empty($info)){
                $this->assign('msg','查无信息或此核销码已失效');
                return $this->fetch();
            }
            $info['customer_name'] = $info['customer_name'] ? $info['customer_name'] : '';
            $info['result'] = $info['result']==1 ? '未完成' : '已完成';
            $info['customer_address'] = $info['customer_address'] ? $info['customer_address'] : '';
            $info['pc_time'] = $info['pc_time'] ? $info['pc_time'] : '';
            $info['area_name'] = $info['area_name'] ? $info['area_name'] : '';
            $info['time'] = $info['time'] ? $info['time'] : '';
            $info['shop_name'] = $info['shop_name'] ? $info['shop_name'] : '';
            $info['pc_shop_name'] = $info['pc_shop_name'] ? $info['pc_shop_name'] : '';
            $info['cameraman_name'] = $info['cameraman_name'] ? $info['cameraman_name'] : '';
            $info['sale_name'] = $info['sale_name'] ? $info['sale_name'] : '';
            $info['tutor_name'] = $info['tutor_name'] ? $info['tutor_name'] : '';
            $info['remark'] = $info['remark'] ? $info['remark'] : '';
            $info['code'] = $info['code'] ? $info['code'] : '';

            $status = '';
            if($info['status'] == 2){
                $status = '已完成';
            }elseif($info['status'] == 2){
                $status = '已改期';
            }elseif($info['status'] == 2){
                $status = '已取消';
            }else{
                $status = '未开始';
            }
            $info['status'] = $status;
            $info['hx_time'] = $info['hx_time'] ? $info['hx_time'] : '';
            $info['staff_name'] = $info['staff_name'] ? $info['staff_name'] : '';
            $this->assign('info',$info);
            return $this->fetch();
        }
    /*-------------------------------------------------- 预约上门客资列表、功能 结束 --------------------------------------------------*/

    /*---------------------------------------------------- 预约上门手机端 开始 ----------------------------------------------------*/
        /**
         * 上门客资列表
         *
         * @param   nothing
         * @return  page
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function experienceList(){
            $param = input();
            $start = $param['time2'] ? date('Y-m-d',strtotime($param['time2'])): date('Y-m-d');
            $end = $param['time2'] ? date('Y-m-d',strtotime($param['time2'])): date('Y-m-d');
            $page = $param['page'] ? $param['page'] : 1;
            $limit = $param['limit'] ? $param['limit'] : 5;
            $shop_code = session('shop_code');
            $where['is_delete'] = 2;
            // $where['pc_shop_code'] = ['in',explode(',',session('work_shop'))];
            
            if($param['pc_type']){
                $where['l.pc_type'] = $param['pc_type'];
            }
            $sql = '';
            if($param['search']){
                $sql = " (c.customer_tel like '%".trim($param['search'])."%' or c.customer_name like '%".trim($param['search'])."%')";
            }

            // if(!check_right('menu1576489359')){
            //     $sql .= ' (c.sales_staff_id='.session('staff_id').' or l.cameraman_id='.session('staff_id').' or tutor_id='.session('staff_id').' or sale_id='.session('staff_id').')';
            // }

            // 查询本店上门拍
            if(check_right('menu1576489359')){
                $where['l.pc_shop_code|l.shop_code'] = $shop_code;
                // if ($shop_code!=='xaf002') {
                //     $where['l.pc_shop_code'] = $shop_code;
                // }
            }
            // 查询本人上门拍
            else
                // if(check_right('menu1576489412'))
            {
                $where['l.cameraman_id|l.tutor_id|c.sales_staff_id'] = session('staff_id');
            }

            if(request()->isAjax()){
                $result = db('crm_c_customerinfo')->alias('c')->join('crm_l_pc_log l','c.id=l.cid','left')
                    ->where('l.pc_time','between',[$start,$end])
                    ->where($where)
                    ->where($sql)
                    ->field('l.id,l.cid,c.customer_name,c.customer_tel,c.baby_name,c.baby_birthday,l.result,customer_address,l.pc_time,c.shop_name,l.pc_shop_name,l.cameraman_name,l.sale_name,l.tutor_name,l.remark,l.code,l.status,l.hx_time,l.staff_name,l.reason,l.backup,c.is_success,c.sales_staff_id,c.sales_staff,l.pc_shop_code,c.consulation_shop_code,c.consulation_shop,c.create_time,c.order_day,l.pc_type,l.sm_type,l.consulation_type')
                    ->page($page)->limit($limit)
                    ->select();
                foreach ($result as $key => $value) {
                    $result[$key]['baby_birthday'] = $value['baby_birthday'] ? date('Y-m-d', strtotime($value['baby_birthday'])) : '';
                }
                // echo db()->getLastSql();die;
                $count = db('crm_c_customerinfo')->alias('c')->join('crm_l_pc_log l','c.id=l.cid')
                    ->where($where)
                    ->where($sql)
                    ->where('l.pc_time','between',[$start,$end])
                    ->count();
                $result['count'] = $count;
                return  json($result);
            }else{
                $info = db('crm_c_customerinfo')->alias('c')->join('crm_l_pc_log l','c.id=l.cid','left')
                    ->where('l.pc_time','between',[$start,$end])
                    ->where($where)
                    ->where($sql)
                    ->field('l.id,l.cid,c.customer_name,c.customer_tel,c.baby_name,c.baby_birthday,l.result,customer_address,l.pc_time,c.shop_name,l.pc_shop_name,l.cameraman_name,l.sale_name,l.tutor_name,l.remark,l.code,l.status,l.hx_time,l.staff_name,c.is_success,c.sales_staff_id,c.sales_staff,l.pc_shop_code,c.consulation_shop_code,c.consulation_shop,c.create_time,c.order_day,l.pc_type,l.sm_type,l.consulation_type')
                    ->page($page)->limit($limit)
                    ->select();
                foreach ($info as $key => $value) {
                    $info[$key]['baby_birthday'] = $value['baby_birthday'] ? date('Y-m-d', strtotime($value['baby_birthday'])) : '';
                }
                // echo db()->getLastSql();die;
                $count = db('crm_c_customerinfo')->alias('c')->join('crm_l_pc_log l','c.id=l.cid')
                    ->where($where)
                    ->where($sql)
                    ->where('l.pc_time','between',[$start,$end])
                    ->count();
                $result['count'] = $count;

                $this->assign('time1',$start);
                $this->assign('time2',$end);
                $this->assign('info',$info);
                return $this->fetch();
            }
        }
        /**
         * 上门客资详情
         *
         * @param   nothing
         * @return  page
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function experienceDetail(){
            $info = db('crm_c_customerinfo')->alias('c')->join('crm_l_pc_log l','c.c_unique=l.c_unique','left')
                ->where('c.id',input('param.id'))
                ->where('l.id',input('param.visit_id'))
                ->field('l.id,l.cid,c.customer_name,c.customer_tel,l.result,l.reason,customer_address,l.pc_time,c.shop_name,l.pc_shop_name,l.cameraman_name,l.sale_name,l.tutor_name,l.remark,l.code,l.status,l.hx_time,l.staff_name,l.consulation_type,l.sm_type,c.is_success,c.sales_staff_id,c.sales_staff,l.pc_shop_code,c.consulation_shop_code,c.consulation_shop,c.create_time,c.order_day')
                ->find();
            // $track = controller("Customer","lib")->getCustomerTrackInfos(input('param.id'));
            $this->assign('info',$info);
            // $this->assign('track',$track);
            //改期原因
            $gq = db('crm_s_changedate_reason')->where('brandclass_id',session('brandclass_id'))->select();
            $this->assign('gq',$gq);
            //取消原因
            $cancel = db('crm_s_hx_cancel_reason')->where('brandclass_id',session('brandclass_id'))->select();
            $this->assign('cancel',$cancel);
            return $this->fetch();
        }
        /**
         * 上门客资详情开单
         *
         * @param   nothing
         * @return  page
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function mobileOrder(){
            $id = (int)input('param.id') ? (int)input('param.id') :110;
            // 权限
            $auth = check_right('menu1519633923');
            /* if (!$auth) {
                $return=array('error'=>'1','msg'=>'您没有操作转订单的权限，请先设置权限');
                return json($return);
            }*/
            $baby_sex = config('baby_sex');
            if(empty($baby_sex)){
                $baby_sex = [
                    ['sex'=>'男',],
                    ['sex'=>'女',],
                ];
            }
            $this->assign('baby_sex',$baby_sex);
            // $cusInfo = controller('crm/Customer', 'lib')->getCustomerInfo($id);
            $cusInfo = db('crm_c_customerinfo')->alias('c')->join('crm_l_pc_log l','l.cid=c.id','left')
                // ->where('c.id',$id) 
                ->where('l.id',$id)
                ->field('l.id,l.cid,c.customer_name,c.customer_tel,c.baby_birthday,c.ready_baby_day,baby_sex,c.marry_day,l.result,customer_address,l.pc_time,l.shop_name,l.shop_code,l.pc_shop_name,l.cameraman_id,l.cameraman_name,l.sale_name,l.tutor_id,l.tutor_name,l.remark,l.code,l.status,l.hx_time,l.staff_name,c.is_success,c.sales_staff_id,c.sales_staff,c.province_id,c.city_id,c.county_id,c.province,c.city,c.county,l.pc_shop_code,c.consulation_shop_code,c.consulation_shop,c.create_time,c.order_day,c.consultation_type_id,c.consultation_type,c.customer_area,c.customer_area_id,c.baby_name,c.customer_channel_id,c.customer_cource,c.customer_area,c.customer_channel,c.customer_orderaddress,c.mate_name,c.mate_tel,c.mate_wechat,c.add_shop_code')
                ->find();
            $cusInfo['baby_birthday']= $cusInfo['baby_birthday'] ? date('Y-m-d', strtotime($cusInfo['baby_birthday'])) : '';
            $cusInfo['ready_baby_day']= $cusInfo['ready_baby_day'] ? date('Y-m-d', strtotime($cusInfo['ready_baby_day'])) : '';
            $cusInfo['marry_day']= $cusInfo['marry_day'] ? date('Y-m-d', strtotime($cusInfo['marry_day'])) : '';
            $this->assign('info',$cusInfo);
            // var_dump($cusInfo);die;
            // $sInfo = getStaffInfoById($cusInfo['sales_staff_id']);
            $sInfo = getStaffInfoById(session('staff_id'));
            $this->assign('sInfo',$sInfo);
            $this->assign('today',date('Ymd'));
            //省
            $province = controller('crm/Customer','lib')->address(['type'=>1,'shop_code'=>$cusInfo['shop_code']]);
            $this->assign('province',$province);
            //拍照店
            $shop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id'),'is_door'=>1]);
            $this->assign('shop',$shop);
            $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>session('shop_type')]);
            // echo '<pre>';
            // print_r($sInfo);die;
            $shopInfo = getShopInfo();
            // $param['ShopSn'] = $shopInfo[$cusInfo['shop_code']]['sn'];
            $param['StaffSN'] =  $sInfo['staff_sn'];
            $param['ShopSn'] = $shopInfo[$cusInfo['shop_code']]['sn'];
            // $param['StaffSN'] =  session('staff_sn');
            // var_dump(session('staff_sn'));
            // exit;
            $order_sn = $erpInterface->getOrderSn($param);
            $this->assign('order_sn',$order_sn);
            $this->assign('shop_sn',$param['ShopSn']);
            $this->assign('staff_sn',$param['StaffSN']);
            //开单相关信息
            $orderInfo = $erpInterface->getCreateOrderInfo(['shop_code'=>$cusInfo['shop_code']]);
            // var_dump($orderInfo);
            // exit;
            $orderInfo['dt_s_packageset'] = my_sort($orderInfo['dt_s_packageset'],'package_price','SORT_ASC');
            foreach($orderInfo['dt_s_consumptiontype'] as $k=>$v){
                $orderInfo['dt_s_consumptiontype'][$k]['mustfill'] = trim($v['mustfill'],';');
            }
            $this->assign('orderInfo',$orderInfo);
            //渠道
            $channel = controller('crm/Customer','lib')->getChannel($cusInfo['add_shop_code']);
            $this->assign('channel',$channel);
            //门市
            $rec = getShopStaffs(['shop_code'=>$cusInfo['consulation_shop_code'],'work_type'=>1]);
            $this->assign('rec',$rec);
            //网销
            /*
            $sales = getShopStaffs(['shop_code'=>$cusInfo['consulation_shop_code'],'work_type'=>21]);
            $is_in = false;
            foreach ($sales as $key => $value) {
                if($value['id'] == session('staff_id')) {
                    $is_in = true;
                };
            }
            if (!$is_in) {
                $temp['id'] = session('staff_id');
                $temp['staffname'] = session('staff_name');
            }
            array_push($sales, $temp);
            
            $this->assign('sales',$sales);
            */
            //摄影师
            $cameraman = getShopStaffs(['shop_code'=>$cusInfo['pc_shop_code'],'work_type'=>3]);
            $this->assign('cameraman',$cameraman);
            //化妆师
            $dresser = getShopStaffs(['shop_code'=>$cusInfo['pc_shop_code'],'work_type'=>7]);
            $this->assign('dresser',$dresser);
            //引导师
            $mentor = getShopStaffs(['shop_code'=>$cusInfo['pc_shop_code'],'work_type'=>25]);
            $this->assign('mentor',$mentor);
            //排程id
            $this->assign('visit_id',$id);
            return $this->fetch();
        }
        /**
         * 删除预约上门
         *
         * @param   id    预约上门id
         * @return  array
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function delVisit(){
            $param = input();
            $vid = (int)$param['id'];

            if (!$vid) {
                $return['code'] = 100;
                $return['msg']  = '未获取到上门ID';
                return $return;
            }
            $info = db('crm_l_pc_log')->alias('p')
                ->join('crm_c_customerinfo c', 'c.id=p.cid', 'left')
                ->where('p.id',$vid)
                ->field('c.id,c.c_unique,c.customer_name,c.customer_number,p.pc_time,sm_type,p.status,p.cameraman_name,p.tutor_name')
                ->find();
            if (!$info) {
                $return['code'] = 100;
                $return['msg']  = '未获取到上门ID';
                return $return;
            }
            if($info['status'] != 1){
                $return['code'] = 101;
                $return['msg']  = '只有未上门的排程可以删除。';
                return $return;
            }
            if($info['cameraman_name'] || $info['tutor_name']){
                $return['code'] = 102;
                $return['msg']  = '已安排上门人员，不允许删除，请改期。';
                return $return;
            }
            db()->startTrans();
            try {
                $upData['is_delete'] = 1;
                $upData['status'] = 99;
                db('crm_l_pc_log')->where('id',$vid)->update($upData);
                //追踪记录
                $params['c_unique'] = $info['c_unique'];
                $params['customer_id'] = $info['id'];
                $params['customer_name'] = $info['customer_name'];
                $params['customer_number'] = $info['customer_number'];
                $params['sales_remark'] = '删除预约上门时间为：'.$info['pc_time'].'；上门拍类型为：'.$info['sm_type'].'；的上门记录';
                $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'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                db('crm_c_salestrackinginfo')->insert($params);
                cache('track_log_'.$info['c_unique'],null);
                $return['code'] = 200;
                $return['msg']  = '删除成功';
                db()->commit();
                return $return;
            } catch (\Exception $e) {
                db()->rollback();
                $return['code'] = 201;
                $return['msg']  = '操作失败，请联系管理员';
                $return['data'] = $e->getMessage();
                return $return;
            }
        }
        /**
         * 预约上门改期页面
         *
         * @param   id    预约上门id
         * @return  page
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function changeVisit(){
            $param = input();
            $vid = (int)$param['id'];
            $info = db('crm_l_pc_log')->alias('p')
                ->join('crm_c_customerinfo c', 'c.id=p.cid', 'left')
                ->where('p.id',$vid)
                ->field('c.id,c.c_unique,c.customer_name,c.customer_number,p.pc_time,sm_type,p.smgroup,p.cameraman_name,p.cameraman_id,p.tutor_name,p.tutor_id,p.shop_code,p.shop_name')
                ->find();
            $this->assign('info',$info);
            // 导师
            $tParam['work_type'] = 25;
            $tParam['shop_code'] = $info['shop_code'];
            $tutors = getShopStaffs($tParam);
            $this->assign('tutors',$tutors);
            // 摄影师
            $cParam['work_type'] = 3;
            $cParam['shop_code'] = $info['shop_code'];
            $cameraman = getShopStaffs($cParam);
            $this->assign('cameraman',$cameraman);
            // 拍摄类型
            $sm_type = db('crm_s_pc_type_set')->where('status',2)->select();
            $this->assign('sm_type',$sm_type);
            return $this->fetch();
        }
        /**
         * 预约上门改期方法
         *
         * @param   id              预约上门id
         * @param   pc_time         预约上门日期
         * @param   sm_type         预约上门类型
         * @param   smgroup         预约上门分组
         * @param   cameraman_id    预约上门摄影师
         * @param   cameraman_name  预约上门摄影师
         * @param   tutor_name      预约上门导师
         * @param   tutor_id        预约上门导师
         * @return  array
         * @author  lilong<lilong@suxuantech.cn>
         */
        public function changeVisitAction(){
            $param = input();
            $vid = (int)$param['id'];
            if (!$vid) {
                $return['code'] = 100;
                $return['msg']  = '未获取到上门ID';
                return $return;
            }
            if (!$param['pc_time']) {
                $return['code'] = 101;
                $return['msg']  = '请选择改期日期';
                return $return;
            }
            if (date('Y-m-d',strtotime($param['pc_time'])) < date('Y-m-d')) {
                $return['code'] = 102;
                $return['msg']  = '改期日期：'.date('Y-m-d',strtotime($param['pc_time'])).'小于当前日期：'.date('Y-m-d').'，请重试！';
                return $return;
            }
            $info = db('crm_l_pc_log')->alias('p')
                ->join('crm_c_customerinfo c', 'c.id=p.cid', 'left')
                ->where('p.id',$vid)
                ->field('c.id as cusid,c.c_unique,c.customer_name,c.customer_number,p.*')
                ->find();
            if (!$info) {
                $return['code'] = 103;
                $return['msg']  = '查询客户信息失败，请联系管理员！';
                $return['sql']  = db()->getLastSql();
                return $return;
            }
            // 目标日期设定排程数量
            $tarWhere['shop_code'] = $info['pc_shop_code'];
            $tarWhere['sm_type'] = trim($param['sm_type']);
            $tarWhere['setting_date'] = date('Y-m-d',strtotime($param['pc_time']));
            $tarWhere['pc_type'] = 2;
            $tagNum = db('crm_l_pc_setting_log')->where($tarWhere)->value('num');
            if (!$tagNum) {
                $return['code'] = 104;
                $return['msg']  = '该上门类型：'.trim($param['sm_type']).'于目标日期：'.date('Y-m-d',strtotime($param['pc_time'])).'，未设定排程，请确认！';
                $return['sql']  = db()->getLastSql();
                return $return;
            }
            // 已排数量
            $alreadyWhere['pc_shop_code'] = $info['pc_shop_code'];
            $alreadyWhere['is_delete'] = 2;
            $alreadyWhere['status'] = ['in', '1,2,3'];
            $alreadyWhere['sm_type'] = trim($param['sm_type']);
            $alreadyWhere['pc_time'] = date('Y-m-d',strtotime($param['pc_time']));
            $alreadyWhere['pc_type'] = 2;
            $alreadyNum = db('crm_l_pc_log')->where($alreadyWhere)->count();
            if ($alreadyNum>=$tagNum) {
                $return['code'] = 104;
                $return['msg']  = '该上门类型：'.trim($param['sm_type']).'于目标日期：'.date('Y-m-d',strtotime($param['pc_time'])).'，排程已满，请确认！';
                $return['sql']  = db()->getLastSql();
                return $return;
            }
            db()->startTrans();
            try {
                // 删除老的预约记录
                $updateOld['is_delete'] = 1;
                $updateOld['is_gq'] = 2;
                $updateOld['status'] = 99;
                $updateOld['remark'] = '改期，由系统删；'.$info['backup'];
                $updateOld['code'] = time();
                db('crm_l_pc_log')->where('id',$vid)->update($updateOld);
                // 写入新的预约记录
                $insertNew['cid'] = $info['cid'];
                $insertNew['c_unique'] = $info['c_unique'];
                $insertNew['smgroup'] = trim($param['smgroup']);
                $insertNew['shop_code'] = $info['shop_code'];
                $insertNew['shop_name'] = $info['shop_name'];
                $insertNew['pc_shop_code'] = $info['pc_shop_code'];
                $insertNew['pc_shop_name'] = $info['pc_shop_name'];
                $insertNew['cameraman_id'] = trim($param['cameraman_id']);
                $insertNew['cameraman_name'] = trim($param['cameraman_name']);
                $insertNew['sale_id'] = session('staff_id');
                $insertNew['sale_name'] = session('staff_name');
                $insertNew['tutor_id'] = trim($param['tutor_id']);
                $insertNew['tutor_name'] = trim($param['tutor_name']);
                $insertNew['remark'] = $info['remark'];
                $insertNew['pc_time'] = date('Y-m-d',strtotime($param['pc_time']));
                $insertNew['code'] = $info['code'];
                $insertNew['status'] = 1;
                $insertNew['pc_type'] = 2;
                $insertNew['consulation_type'] = $info['consulation_type'];
                $insertNew['street_id'] = $info['street_id'];
                $insertNew['street'] = $info['street'];
                $insertNew['address'] = $info['address'];
                $insertNew['create_time'] = date('Y-m-d H:i:s',time());
                $insertNew['backup'] = $info['backup'];
                $insertNew['sm_type'] = $param['sm_type'] ? trim($param['sm_type']) : $info['sm_type'];
                $insertNew['sm_type'] = $info['sm_type'];
                $insertNew['is_chaoju'] = $info['is_chaoju'];
                db('crm_l_pc_log')->insert($insertNew);

                //追踪记录
                $sales_remark  = '预约上门改期，将上门时间由：'.$info['pc_time'].'，修改为：'.$insertNew['pc_time'];
                $sales_remark .= '；将上门类型由：'.$info['sm_type'].'，修改为：'.$param['sm_type'];
                $sales_remark .= '；将上门分组由：'.$info['smgroup'].'，修改为：'.$param['smgroup'];
                $sales_remark .= '；将摄影师由：'.$info['cameraman_name'].'，修改为：'.$param['cameraman_name'];
                $sales_remark .= '；将导师由：'.$info['tutor_name'].'，修改为：'.$param['tutor_name'];
                $params['c_unique'] = $info['c_unique'];
                $params['customer_id'] = $info['cusid'];
                $params['customer_name'] = $info['customer_name'];
                $params['customer_number'] = $info['customer_number'];
                $params['sales_remark'] = $sales_remark;
                $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'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                db('crm_c_salestrackinginfo')->insert($params);
                cache('track_log_'.$info['c_unique'],null);
                $return['code'] = 200;
                $return['msg']  = '改期成功';
                db()->commit();
                return $return;
            } catch (\Exception $e) {
                db()->rollback();
                $return['code'] = 201;
                $return['msg']  = '操作失败，请联系管理员';
                $return['data'] = $e->getMessage();
                return $return;
            }
        }
    /*---------------------------------------------------- 预约上门手机端 结束 ----------------------------------------------------*/
    public function getPCGroup(){
        $data = input();
        $where['is_delete'] = 2;
        $where['pc_shop_code'] = $data['shop_code'];
        $where['l.pc_type'] = 2;
        $group = db('crm_c_customerinfo')->alias('c')->join('crm_l_pc_log l','c.id=l.cid','left')
            ->where('l.pc_time','between',[$data['start'],date('Y-m-d 23:59:59',strtotime($data['end']))])
            ->where($where)
            ->group('l.smgroup')
            ->field('l.smgroup')
            ->select();
        foreach($group as $k=>$v){
            if(empty($v['smgroup'])){
                unset($group[$k]);
            }
        }
        return array_values($group);
    }
    /*-----------------上门类型设定------start-----------------------*/
    public function smTypeSet(){
        return $this->fetch();
    }
    public function addSMType(){
        $data = input();
        if(empty($data['sm_type'])){
            return array('code'=>101,'msg'=>'类型名不能为空');
        }
        db()->startTrans();
        try{
            if($data['id']){
                $info = db('crm_s_pc_type_set')->where('sm_type',$data['sm_type'])->where('id','<>',$data['id'])->where('status',2)->find();
                if(!empty($info)){
                    return array('code'=>101,'msg'=>'此类型名已存在，请修改');
                }
                db('crm_s_pc_type_set')->where('id',$data['id'])->update(['sm_type'=>trim($data['sm_type'])]);
                $log = '由 '.session('staff_name').' 于'.date('Y-m-d H:i:s').' 修改排程类型： '.$info['sm_type'].'->'.$data['sm_type'];
                action_log($log,[]);
                db()->commit();
                return array('code'=>200,'msg'=>'修改上门类型成功');
            }else{
                $type['sm_type'] = trim($data['sm_type']);
                $type['staff_id'] = session('staff_id');
                $type['staff_name'] = session('staff_name');
                $type['create_time'] = date('Y-m-d H:i:s');
                db('crm_s_pc_type_set')->insert($type);
                $log = '由 '.session('staff_name').' 于'.date('Y-m-d H:i:s').' 添加排程类型： '.$data['sm_type'];
                action_log($log,[]);
                db()->commit();
                return array('code'=>200,'msg'=>'添加上门类型成功');
            }
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'操作失败','data'=>$e->getMessage());
        }
    }
    public function delSMType(){
        $data = input();
        if($data['id']){
            db()->startTrans();
            try {
                db('crm_s_pc_type_set')->where('id',$data['id'])->update(['status'=>1]);
                $log = '由 '.session('staff_name').' 于'.date('Y-m-d H:i:s').' 删除排程类型 '.$data['sm_type'];
                action_log($log,[]);
                db()->commit();
                return array('code'=>200,'msg'=>'删除上门类型成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'删除失败','data'=>$e->getMessage());
            }
        }else{
            return array('code'=>101,'msg'=>'未获取到类型ID');
        }
    }
    public function SMTypeJSON(){
        $param = input();
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 10;
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_pc_type_set')->where('sm_type','like','%'.$param['sm_type'].'%')->where('status',2)
            ->order('id desc')
             ->page($page,$limit)
            ->select();
        $count = db('crm_s_pc_type_set')->where('sm_type','like','%'.$param['sm_type'].'%')->where('status',2)->count();
        $result['data'] = $res;
        $result['count'] = $count;

        return ($result);

    }
    /*-----------------上门类型设定------end-----------------------*/
    //手机端上门反馈
    public function visitFeedback(){
        if(request()->isAjax() && request()->isPost()){
            $param = input();

            if(empty($param['id'])){
                return array('code'=>101,'msg'=>'未获取到上门ID');
            }
            if(empty($param['reason']) && (int)$param['status']==4){
                return array('code'=>101,'msg'=>'未获取到反馈结果');
            }
            $reason = trim($param['reason']);
            $status = (int)$param['status'];
            /* 
            switch ($status) {
                case 3:
                    $reason = '状态更新为：3【已上门未成交】'.$reason;
                    break;
                case 4:
                    $reason = '状态更新为：4【已取消】'.$reason;
                    break;
                // default:
                //     return array('code'=>101,'msg'=>'无效的结果状态');
                //     break;
            }
            */
            // 追踪记录 20201126
            $pcInfo = db('crm_l_pc_log')->where('is_delete',2)->where('id',(int)$param['id'])->find();
            if(!$pcInfo){
                return array('code'=>101,'msg'=>'未获取到上门信息');
            }
            if(!$pcInfo['cameraman_name']){
                return array('code'=>101,'msg'=>'未分配摄影师，无法反馈上门信息。');
            }


            $trackRemark = '';
            // 预约上门的服务订单(网销开的)
            if ((int)$param['status']==3) {
                $updatePc['status'] = 3;
                $trackRemark .= '上门成功';
                $sm_order = trim($param['hx_sm_order']);
                if ($sm_order) {
                    $updatePc['status'] = 2;
                    $trackRemark .= '；关联上门订单：'.$sm_order;
                    $smOrderCount = db('c_customerorder')->where('orderId',$sm_order)->where('crm_customer_id',(int)$param['cid'])->count();
                    if (!$smOrderCount) {
                        return array('code'=>100, 'msg'=>'未找到上门订单：'.$sm_order.'，请确认。', 'sql'=>db()->getLastSql());
                    }                    
                    // 更新拍照表
                    $photoData['cameraman'] = $pcInfo['cameraman_name'];
                    $photoData['mentor_a']  = $pcInfo['tutor_name'];
                    $photoData['photodate'] = date('Ymd');
                    $photoData['paikongstaff']= $pcInfo['sale_name'];
                    $photoData['paikongtime'] = $pcInfo['create_time'];
                    $photoData['paikongshop_code'] = $pcInfo['shop_code'];
                    $photoData['paikongshop_name'] = $pcInfo['shop_name'];
                    $photoData['photonote'] = 'CRM上门拍成功反馈自动排程';
                    $trackRemark .= '；设置拍照时间为：'.date('Ymd');
                    // 更新选片表
                    $spData['selectday'] = date('Ymd');
                    $trackRemark .= '；设置选片时间为：'.date('Ymd');
                }elseif ($pcInfo['visit_order']) {
                    $sm_order = $pcInfo['visit_order'];
                    $updatePc['status'] = 2;
                    // 更新拍照表
                    $photoData['cameraman'] = $pcInfo['cameraman_name'];
                    $photoData['mentor_a']  = $pcInfo['tutor_name'];
                    $photoData['photodate'] = date('Ymd');
                    $photoData['paikongstaff']= $pcInfo['sale_name'];
                    $photoData['paikongtime'] = $pcInfo['create_time'];
                    $photoData['paikongshop_code'] = $pcInfo['shop_code'];
                    $photoData['paikongshop_name'] = $pcInfo['shop_name'];
                    $photoData['photonote'] = 'CRM上门拍成功反馈自动排程';
                    $trackRemark .= '；设置拍照时间为：'.date('Ymd');
                    // 更新选片表
                    $spData['selectday'] = date('Ymd');
                    $trackRemark .= '；设置选片时间为：'.date('Ymd');
                }
            }else{
                $updatePc['status'] = 4;
                $trackRemark .= '上门失败；失败原因：'.$param['reason'];
            }
            $customerInfo = db('crm_c_customerinfo')->alias('c')
                ->join('crm_l_pc_log l','c.id=l.cid','left')
                ->where('l.id',(int)$param['id'])
                ->field('c.id,c.c_unique,c.customer_name,customer_number')
                ->find();
            db()->startTrans();
            try {
                $updatePc['reason'] = trim($reason);
                db('crm_l_pc_log')->where('id',(int)$param['id'])->update($updatePc);
                // 更新订单表
                db('c_customerorder')->where('orderId',$sm_order)->update(['crm_visit_id'=>(int)$param['id']]);
                // 更新拍照表
                if ($photoData) {
                    db('c_customerphoto')->where('orderId',$sm_order)->where('photodate','')->update($photoData);
                }
                // 更新选片表
                if ($spData) {
                    db('c_customersp')->where('orderId',$sm_order)->where('selectday','')->update($spData);
                }
                //追踪记录
                $params['customer_id'] = $customerInfo['id'];
                $params['c_unique'] = $customerInfo['c_unique'];
                $params['customer_name'] = $customerInfo['customer_name'];
                $params['customer_number'] = $customerInfo['customer_number'];
                $params['sales_remark'] = $trackRemark;
                $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'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                db('crm_c_salestrackinginfo')->insert($params);
                // cache('getCustomerTrackInfos'.$customerInfo['id'],null);
                cache('track_log_'.$customerInfo['c_unique'],null);
                $log = '由 '.session('staff_name').' 于'.date('Y-m-d H:i:s').' 添加上门反馈： '.$reason;
                action_log($log,[]);
                db()->commit();
                return array('code'=>200,'msg'=>'反馈成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'反馈失败','data'=>$e->getMessage());
            }
        }
        // 上门信息
        $pcInfo = db('crm_l_pc_log')->where('id',(int)input('id'))->field('cid,visit_order')->find();
        // 上门订单
        $smOrder = db('c_customerorder')->alias('o')
            ->join('c_customerphoto p','o.orderId=p.photodate','left')
            ->where('o.crm_customer_id',$pcInfo['cid'])->where("p.photodate='' OR p.photodate IS NULL")->group('o.orderId')
            ->field('o.orderId,o.payment_money,o.total_money')->select();
        foreach ($smOrder as $k => $v) {
            if ($v['orderId']==$pcInfo['visit_order']) {
                $smOrder[$k]['selected'] = 1;
            }else{
                $smOrder[$k]['selected'] = 0;
            }
        }
        $this->assign("smOrder",$smOrder);

        $this->assign('act',input('act'));
        $this->assign('id',input('id'));
        $this->assign('cid',$pcInfo['cid']);
        return $this->fetch();
        
    }
    // 进店转订单
    public function order(){
        $id = (int)input('param.id');
        
        $this->assign('visit_id',$id);
        $baby_sex = config('baby_sex');
        if(empty($baby_sex)){
            $baby_sex = [
                ['sex'=>'男',],
                ['sex'=>'女',],
            ];
        }
        $this->assign('baby_sex',$baby_sex);
        $cusInfo = db('crm_c_customerinfo')->alias('c')->join('crm_l_pc_log l','l.cid=c.id','left')
            ->where('l.id', $id)
            ->field('c.id,l.id as log_id,c.customer_name,c.customer_tel,c.customer_wechat,c.reception_id,c.reception_name,c.consulation_shop_code,c.consulation_shop_code,c.consulation_shop,c.shop_code,c.add_shop_code,c.customer_channel_id,c.customer_channel,c.customer_area,c.baby_address,c.consultation_type,c.brandclass,c.sales_staff_id,l.pc_shop_code,c.consultation_type_id,c.consultation_type,c.customer_cource_id,c.customer_cource,c.customer_area_id,c.customer_area,c.province_id,c.province,c.city_id,c.city,c.county_id,c.county,c.customer_address,c.baby_name,c.baby_sex,c.baby_birthday,c.customer_orderaddress_id,c.customer_orderaddress,c.mate_name,c.mate_tel,c.mate_wechat,c.mate_birthday,c.customer_birthday,c.marry_day,c.ready_baby_day,l.cameraman_id,l.cameraman_name,l.tutor_id,l.tutor_name,l.pc_shop_code,l.pc_shop_name')
            ->find();
        $cusInfo['baby_birthday'] = $cusInfo['baby_birthday'] ? date('Y-m-d',strtotime($cusInfo['baby_birthday'])) : '';
        $cusInfo['ready_baby_day'] = $cusInfo['ready_baby_day'] ? date('Y-m-d',strtotime($cusInfo['ready_baby_day'])) : '';
        $cusInfo['mate_birthday'] = $cusInfo['mate_birthday'] ? date('Y-m-d',strtotime($cusInfo['mate_birthday'])) : '';
        $cusInfo['customer_birthday'] = $cusInfo['customer_birthday'] ? date('Y-m-d',strtotime($cusInfo['customer_birthday'])) : '';
        $cusInfo['marry_day'] = $cusInfo['marry_day'] ? date('Y-m-d',strtotime($cusInfo['marry_day'])) : '';
        
        $cusInfo['sales_staff'] = $cusInfo['sales_staff'] ? $cusInfo['sales_staff'] : session('staff_name');
        $cusInfo['sales_staff_id'] = $cusInfo['sales_staff_id'] ? $cusInfo['sales_staff_id'] : session('staff_id');
        $cusInfo['sales_staff_number'] = $cusInfo['sales_staff_number'] ? $cusInfo['sales_staff_number'] : session('staff_number');

        $cusInfo['customer_channel'] = $cusInfo['customer_channel'] ? strip_tags($cusInfo['customer_channel']) : '';
        $cusInfo['consultation_type'] = $cusInfo['consultation_type'] ? strip_tags($cusInfo['consultation_type']) : '';
        
        $this->assign('info',$cusInfo);
        $sInfo = controller('crm/Customer','lib')->get_staff_info(array('staff_id'=>$cusInfo['sales_staff_id']));
        $this->assign('sInfo',$sInfo['data']);
        $this->assign('today',date('Ymd'));
        //省
        $province = controller('crm/Customer','lib')->address(['type'=>1]);
        $this->assign('province',$province);
        //拍照店
        $shop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id'),'is_photo'=>1]);
        $this->assign('shop',$shop);
        //渠道
        $channel = controller('crm/Customer','lib')->getChannel();
        $this->assign('channel',$channel);

        $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>session('shop_type')]);
        $shopInfo = getShopInfo();
        $param['ShopSn'] = $shopInfo[$cusInfo['pc_shop_code']]['sn'];
        $param['StaffSN'] = $sInfo['data']['staff_sn'];
        foreach ($channel as $key => $value) {
            if($value['id'] == $cusInfo['customer_channel_id']){
                $param['channelCode'] = $value['channel_code'];
            }
        }
        $order_sn = $erpInterface->getOrderSn($param);
        $this->assign('order_sn',$order_sn);
        $this->assign('shop_sn',$param['ShopSn']);
        $this->assign('staff_sn',$param['StaffSN']);
        //开单相关信息
        $orderInfo = $erpInterface->getCreateOrderInfo(['shop_code'=>$cusInfo['pc_shop_code']]);
        // $orderInfo = $erpInterface->getCreateOrderInfo(['shop_code'=>$sInfo['data']['shop_code']]);
        $orderInfo['dt_s_packageset'] = my_sort($orderInfo['dt_s_packageset'],'package_price','SORT_ASC');
        foreach($orderInfo['dt_s_consumptiontype'] as $k=>$v){
            $orderInfo['dt_s_consumptiontype'][$k]['mustfill'] = trim($v['mustfill'],';');
        }
        $this->assign('orderInfo',$orderInfo);
        
        //门市
        $rec = getShopStaffs(['shop_code'=>session('shop_code'),'work_type'=>1]);
        // $rec = getShopStaffs(['shop_code'=>$sInfo['data']['shop_code'],'work_type'=>1]);
        $this->assign('rec',$rec);
        //网销
        $sales = getShopStaffs(['shop_code'=>session('shop_code'),'work_type'=>21]);
        // $sales = getShopStaffs(['shop_code'=>$sInfo['data']['shop_code'],'work_type'=>21]);
        $this->assign('sales',$sales);
        //摄影师
        $cameraman = getShopStaffs(['shop_code'=>session('shop_code'),'work_type'=>3]);
        // $cameraman = getShopStaffs(['shop_code'=>$sInfo['data']['shop_code'],'work_type'=>3]);
        $this->assign('cameraman',$cameraman);
        //化妆师
        $dresser = getShopStaffs(['shop_code'=>session('shop_code'),'work_type'=>7]);
        // $dresser = getShopStaffs(['shop_code'=>$sInfo['data']['shop_code'],'work_type'=>7]);
        $this->assign('dresser',$dresser);
        //引导师
        $mentor = getShopStaffs(['shop_code'=>session('shop_code'),'work_type'=>25]);
        // $mentor = getShopStaffs(['shop_code'=>$sInfo['data']['shop_code'],'work_type'=>25]);
        $this->assign('mentor',$mentor);
        return $this->fetch();
    }
}
