<?php
/**
 * ERP 对应模块
 * 默认接口方法，此方法内定议基础框架所需要的方法，用于验证模块合法性，模块版本，对接基础架构中需要的方法
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2018-11-14 $
 */
namespace app\erp\controller;
use think\Cache;
use app\index\controller\Base;
use think\Exception;
use think\Request;
use think\Session;
use think\Controller;
class Erp extends Base{

    //体验拍主页面
    public function mark(){
        /*if(!config('sx_erp')){
            alert('暂不支持，请前往项目配置文件设置','/');
            exit();
        }*/
        return $this->fetch();
    }
    
    //门市转订单
    public function order(){
        $id = (int)input('param.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','c.c_unique=l.c_unique and l.cid=c.id','right')
            ->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.pc_shop_code,l.pc_shop_name')
            ->find();
        $this->assign('info',$cusInfo);
        $sInfo = $res = 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);
        $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'];
        $order_sn = $erpInterface->getOrderSn($param);
        $this->assign('order_sn',$order_sn);
        //开单相关信息
        $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);
        //渠道
        $channel = controller('crm/Customer','lib')->getChannel();
        $this->assign('channel',$channel);
        //门市
        $rec = getShopStaffs(['shop_code'=>$sInfo['data']['shop_code'],'work_type'=>1]);
        $this->assign('rec',$rec);
        //网销
        $sales = getShopStaffs(['shop_code'=>$sInfo['data']['shop_code'],'work_type'=>21]);
        $this->assign('sales',$sales);
        //摄影师
        $cameraman = getShopStaffs(['shop_code'=>$sInfo['data']['shop_code'],'work_type'=>3]);
        $this->assign('cameraman',$cameraman);
        //化妆师
        $dresser = getShopStaffs(['shop_code'=>$sInfo['data']['shop_code'],'work_type'=>7]);
        $this->assign('dresser',$dresser);
        //引导师
        $mentor = getShopStaffs(['shop_code'=>$sInfo['data']['shop_code'],'work_type'=>25]);
        $this->assign('mentor',$mentor);
        return $this->fetch();
    }
    //转订单
    public function zhuanOrder(){
        $param = input();
        $listTime = microtime(true).'==>Line'.__LINE__.';';
        if(db_config('set_order_money_'.session('brandclass_id')) == 2){
            $param['paytype'] = null;    //收款方式
            $param['paymentmoney'] = null; //实收金额：
            $param['order_amount'] = null;
            $param['duikuanma'] = null;
        }
        // var_dump($param);
        // exit;
        $time = date('Y-m-d H:i:s',time());
        $target_time = trim($param['target_time']);
        $order_method = $param['order_method'] ? $param['order_method'] : null;
        /*if($param['target_time'] && $target_time > $time){
            $arr = array('code'=>600,'msg'=>'开单时间不能大于当前时间','data'=>$param['target_time']);
            return $arr;
        }*/
        $order_sn = $param['order_sn'];
        $orderid = db('c_customerorder')->where('orderId', $param['order_sn'])->value('id');
        if($orderid){
            $arr = array('code'=>100,'msg'=>'开单失败，订单号重复','data'=>$param['order_sn']);
            return $arr;
        }

        $isParam['package_name'] = $param['package_name'];
        $isParam['wphone'] = $param['customer_tel'];
        $isAddPackage = controller('erp/Erp','lib')->isAddPackage($isParam);
        if ($isAddPackage['code'] != 200) {
            return $isAddPackage;
        }
        
        $customerInfo = db('crm_c_customerinfo')->where('id', $param['cid'])->find();
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        $data['shop_code'] = $param['consulation_shop_code'];
        $data['shop_name'] = $param['consulation_shop'];
        $data['photo_shop_code'] = $param['photo_shop_code'];
        $data['photo_shop_name'] = $param['photo_shop_name'];
        $data['setkey'] = session('setkey');
        $data['target_time'] = $param['target_time'] ? date('Y-m-d H:i:s',strtotime($param['target_time'])) : $time;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            getSalesTracking($data['customer_id']);

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

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

        $time = date('Y-m-d H:i:s',time());
        $target_time = trim($param['target_time']);
        $order_method = $param['order_method'] ? $param['order_method'] : null;
        $order_sn = $param['order_sn'];

        /*if($param['target_time'] && $target_time > $time){
            $arr = array('code'=>600,'msg'=>'开单时间不能大于当前时间','data'=>$param['target_time']);
            return $arr;
        }*/
        $customerInfo = db('crm_c_customerinfo')->where('id', $param['cid'])->where('is_status',1)->find();
        if (!$customerInfo) {
            return array('code'=>99,'msg'=>'查询客资信息失败','error'=>db()->getLastSql());
        }

        // 相同的体验套在有效期(90天)内不允许开单
        $nine = date('Y-m-d',strtotime('-90 days'));
        $isRepSql = " date_format(targetdate, '%Y-%m-%d') > '".$nine."' ";
        $isRepPackage = db('c_customerinfo')->alias('c')
            ->join('c_customerorder o','c.customerid=o.customerid','left')
            ->join('c_consumptioncontent con','o.orderId=con.orderId AND con.sorting = 0','left')
            ->where('c.wphone',$param['customer_tel'])->where('o.total_money','0')
            ->where('con.consumption_name|o.package_name|o.yxpackage_name',$param['package_name'])
            ->where($isRepSql)
            ->field('o.orderId,targetdate')
            ->find();
        if ($isRepPackage) {
            $msg = '该客资已定'.$param['package_name'].'套系，单号：'.$isRepPackage['orderId'].'。不可以在预定'.$param['package_name'].'套系了，请悉知。';
            return array('code'=>100,'msg'=>$msg,'data'=>'','sql'=>db()->getLastSql());
        }
        /*
        $res = controller('erp/Erp','lib')->getCustomerOrdersCount($customerInfo['customer_number']);
        if($res['nopay'] >0){
            if(!$param['paymentmoney']){
                return array('code'=>100,'msg'=>'当前客资有未收款订单，只能再转收款订单。');
            }
        }
        */
        // var_dump($res);
        // echo '=====end';die;
        // 妈妈姓名
        if ($param['customer_name'] != $customerInfo['customer_name']) {
            $cData['customer_name'] = $param['customer_name'];
            $newData['customer_name'] = $param['customer_name'];
            $oldData['customer_name'] = $customerInfo['customer_name'];
        }
        // 妈妈微信
        if ($param['customer_wechat'] != $customerInfo['customer_wechat']) {
            $cData['customer_wechat'] = $param['customer_wechat'];
            $newData['customer_wechat'] = $param['customer_wechat'];
            $oldData['customer_wechat'] = $customerInfo['customer_wechat'];
        }
        // 爸爸姓名
        if ($param['mate_name'] != $customerInfo['mate_name']) {
            $cData['mate_name'] = $param['mate_name'];
            $newData['mate_name'] = $param['mate_name'];
            $oldData['mate_name'] = $customerInfo['mate_name'];
        }
        // 爸爸手机
        if ($param['mate_tel'] != $customerInfo['mate_tel']) {
            $cData['mate_tel'] = $param['mate_tel'];
            $newData['mate_tel'] = $param['mate_tel'];
            $oldData['mate_tel'] = $customerInfo['mate_tel'];
        }
        // 爸爸微信
        if ($param['mate_wechat'] != $customerInfo['mate_wechat']) {
            $cData['mate_wechat'] = $param['mate_wechat'];
            $newData['mate_wechat'] = $param['mate_wechat'];
            $oldData['mate_wechat'] = $customerInfo['mate_wechat'];
        }
        // 宝宝姓名
        if ($param['baby_name'] != $customerInfo['baby_name']) {
            $cData['baby_name'] = $param['baby_name'];
            $newData['baby_name'] = $param['baby_name'];
            $oldData['baby_name'] = $customerInfo['baby_name'];
        }
        // 宝宝性别
        if ($param['baby_sex'] != $customerInfo['baby_sex']) {
            $cData['baby_sex'] = $param['baby_sex'];
            $newData['baby_sex'] = $param['baby_sex'];
            $oldData['baby_sex'] = $customerInfo['baby_sex'];
        }
        // 宝宝生日
        if ($param['baby_birthday'] != $customerInfo['baby_birthday']) {
            $cData['baby_birthday'] = $param['baby_birthday'] ? date('Y-m-d', strtotime($param['baby_birthday'])) : NULL;
            $newData['baby_birthday'] = $param['baby_birthday'] ? date('Y-m-d', strtotime($param['baby_birthday'])) : NULL;
            $oldData['baby_birthday'] = $customerInfo['baby_birthday'] ? date('Y-m-d', strtotime($customerInfo['baby_birthday'])) : NULL;
        }
        // 预产期
        if ($param['ready_baby_day'] != $customerInfo['ready_baby_day']) {
            $cData['ready_baby_day'] = $param['ready_baby_day'] ? date('Y-m-d', strtotime($param['ready_baby_day'])) : NULL;
            $newData['ready_baby_day'] = $param['ready_baby_day'] ? date('Y-m-d', strtotime($param['ready_baby_day'])) : NULL;
            $oldData['ready_baby_day'] = $customerInfo['ready_baby_day'] ? date('Y-m-d', strtotime($customerInfo['ready_baby_day'])) : NULL;
        }
        // 妈妈生日
        if ($param['customer_birthday'] != $customerInfo['customer_birthday']) {
            $cData['customer_birthday'] = $param['customer_birthday'] ? date('Y-m-d', strtotime($param['customer_birthday'])) : NULL;
            $newData['customer_birthday'] = $param['customer_birthday'] ? date('Y-m-d', strtotime($param['customer_birthday'])) : NULL;
            $oldData['customer_birthday'] = $customerInfo['customer_birthday'] ? date('Y-m-d', strtotime($customerInfo['customer_birthday'])) : NULL;
        }
        // 爸爸生日
        if ($param['mate_birthday'] != $customerInfo['mate_birthday']) {
            $cData['mate_birthday'] = $param['mate_birthday'] ? date('Y-m-d', strtotime($param['mate_birthday'])) : NULL;
            $newData['mate_birthday'] = $param['mate_birthday'] ? date('Y-m-d', strtotime($param['mate_birthday'])) : NULL;
            $oldData['mate_birthday'] = $customerInfo['mate_birthday'] ? date('Y-m-d', strtotime($customerInfo['mate_birthday'])) : NULL;
        }
        // 结婚日期
        if ($param['marry_day'] != $customerInfo['marry_day']) {
            $cData['marry_day'] = $param['marry_day'] ? date('Y-m-d', strtotime($param['marry_day'])) : NULL;
            $newData['marry_day'] = $param['marry_day'] ? date('Y-m-d', strtotime($param['marry_day'])) : NULL;
            $oldData['marry_day'] = $customerInfo['marry_day'] ? date('Y-m-d', strtotime($customerInfo['marry_day'])) : NULL;
        }
        // email
        if ($param['email'] != $customerInfo['email']) {
            $cData['email'] = $param['email'];
            $newData['email'] = $param['email'];
            $oldData['email'] = $customerInfo['email'];
        }
        // 消费类型
        if ($param['consultation_type_id'] != $customerInfo['consultation_type_id']) {
            $cData['consultation_type_id'] = $param['consultation_type_id'];
            $cData['consultation_type'] = $param['consultation_type'];
            $newData['consultation_type'] = $param['consultation_type'];
            $oldData['consultation_type'] = $customerInfo['consultation_type'];
        }
        // 渠道名称
        if ($param['customer_channel_id'] != $customerInfo['customer_channel_id']) {
            $cData['customer_channel_id'] = $param['customer_channel_id'];
            $cData['customer_channel'] = $param['customer_channel'];
            $newData['customer_channel'] = $param['customer_channel'];
            $oldData['customer_channel'] = $customerInfo['customer_channel'];
        }
        // 宝宝出生地（医院）
        if ($param['baby_address'] != $customerInfo['baby_address']) {
            $cData['baby_address'] = $param['baby_address'];
            $newData['baby_address'] = $param['baby_address'];
            $oldData['baby_address'] = $customerInfo['baby_address'];
        }
        // 省
        if ($param['province_id'] != $customerInfo['province_id']) {
            $cData['province_id'] = $param['province_id'];
            $cData['province'] = $param['province'];
            $newData['province'] = $param['province'];
            $oldData['province'] = $customerInfo['province'];
        }
        // 市
        if ($param['city_id'] != $customerInfo['city_id']) {
            $cData['city_id'] = $param['city_id'];
            $cData['city'] = $param['city'];
            $newData['city'] = $param['city'];
            $oldData['city'] = $customerInfo['city'];
        }
        // 区
        if ($param['county_id'] != $customerInfo['county_id']) {
            $cData['county_id'] = $param['county_id'];
            $cData['county'] = $param['county'];
            $newData['county'] = $param['county'];
            $oldData['county'] = $customerInfo['county'];
        }
        // 详细地址
        if ($param['customer_address'] != $customerInfo['customer_address']) {
            $cData['customer_address'] = $param['customer_address'];
            $newData['customer_address'] = $param['customer_address'];
            $oldData['customer_address'] = $customerInfo['customer_address'];
        }
        // 销售门市
        if ($param['reception_id'] != $customerInfo['reception_id']) {
            $cData['reception_id'] = $param['reception_id'];
            $cData['reception_name'] = $param['reception_name'];
            $newData['reception_name'] = $param['reception_name'];
            $oldData['reception_name'] = $customerInfo['reception_name'];
        }
        // 接单点
        if ($param['customer_orderaddress_id'] != $customerInfo['customer_orderaddress_id']) {
            $cData['customer_orderaddress_id'] = $param['customer_orderaddress_id'];
            $cData['customer_orderaddress'] = $param['customer_orderaddress'];
            $newData['customer_orderaddress'] = $param['customer_orderaddress'];
            $oldData['customer_orderaddress'] = $customerInfo['customer_orderaddress'];
        }
        // 网销  如果是上门拍订单，不修改网销 如果不是上门拍订单，有实收才修改追踪人，如果没有，不修改追踪人
        if($order_method != '上门拍订单' && $param['paymentmoney']>0){
            $cData['sales_staff'] = session('staff_name');
            $cData['sales_staff_id'] = session('staff_id');
            $cData['sales_staff_number'] = session('staff_number');
            $cData['sales_department_id'] = session('department_id');
            $cData['sales_department_name'] = session('department_name');
            $cData['shop_code'] = session('shop_code');
            $cData['shop_name'] = session('shop_name');

            $newData['sales_staff'] = session('staff_name');
            $newData['sales_department_name'] = session('department_name');
            $newData['shop_name'] = session('shop_name');

            $oldData['sales_staff'] = $customerInfo['sales_staff'];
            $oldData['sales_department_name'] = $customerInfo['department_name'];
            $oldData['shop_name'] = $customerInfo['shop_name'];

            $dataErp['Storeconsuitant2'] = session('staff_name');
            $dataErp['crm_shop_code'] = session('shop_code');
            $dataErp['crm_shop_name'] = session('shop_name');
            $dataErp['crm_sales_department_name'] = session('department_name');
        }else{
            $dataErp['Storeconsuitant2'] = $customerInfo['sales_staff'] ? $customerInfo['sales_staff'] : session('staff_name');
        }
        $dataErp['ShopSn'] = $param['shop_sn'];
        $dataErp['StaffSN'] = $param['staff_sn'];
        // var_dump($dataErp);
        // var_dump($newData);
        // var_dump($cData);
        // die;
        //摄影师
        $lData['cameraman_id'] = intval($param['cameraman_id']);
        $lData['cameraman_name'] = trim($param['cameraman']);
        //引导师
        $lData['tutor_id'] = intval($param['tutor_id']);
        $lData['tutor_name'] = trim($param['tutor_name']);
        $lData['status'] = 2;

        // 订单有效标准 线下 （order_rule） 1：实收款；2：占比
        $ordervalid = getPercent($param['paymentmoney'],$param['order_amount'],$customerInfo['brandclass_id'],'order');
        // var_dump($ordervalid);die;
        if($ordervalid){
            $cData['is_success'] = 1;
            $cData['order_start_time'] = $target_time;
            $cData['order_day']  = $target_time;
            $dataErp['orderyouxiao'] = 1;
            $dataErp['orderyouxiaodate'] = $target_time;
        }else{
            $cData['is_success'] = 3;
            $cData['order_start_time'] = $target_time;
            $dataErp['orderyouxiao'] = 0;
            $dataErp['orderyouxiaodate'] = NULL;
        }
        // ----------  ERP接口数据  开始  -------- //
        $dataErp['OrderId'] = $order_sn ? $order_sn : '';
        // 来源渠道
        $dataErp['Customer_channel'] = $cData['customer_channel'] ? $cData['customer_channel'] : $customerInfo['customer_channel'];
        // 客资编号
        $dataErp['crm_customer_id'] = $customerInfo['id'];
        $dataErp['Customer_from_index'] = $customerInfo['customer_number'];
        $dataErp['crm_c_unique'] = $customerInfo['c_unique'];
        // 联系邮箱
        $dataErp['Email'] = $param['email'] ? $param['email'] : '';
        // 客户来源
        $dataErp['Cssname'] = $param['customer_cource_id'] ? $param['customer_cource_id'] : '';
        // 客户分区
        $dataErp['Area'] = $param['customer_area_id'] ? $param['customer_area_id'] : '';
        // 结婚日期
        $dataErp['Weddingdate']= $param['marry_day'] ? $param['marry_day'] : '';
        $dataErp['Wname']      = $param['customer_name'] ? $param['customer_name'] : '';
        $dataErp['Wphone']     = $param['customer_tel'] ? $param['customer_tel'] : '';
        $dataErp['Wwechat']    = $param['customer_wechat'] ? $param['customer_wechat'] : '';
        $dataErp['Wbirthdate'] = $param['customer_birthday'] ? $param['customer_birthday'] : '';
        $dataErp['Mname']      = $param['mate_name'] ? $param['mate_name'] : '';
        $dataErp['Mphone']     = $param['mate_tel'] ? $param['mate_tel'] : '';
        $dataErp['Mwechat']    = $param['mate_wechat'] ? $param['mate_wechat'] : '';
        $dataErp['Mbirthdate'] = $param['mate_birthday'] ? $param['mate_birthday'] : '';
        // 客户所属店面
        $dataErp['Shop_code']  = $param['consulation_shop_code'];
        // 客户所属店面
        $dataErp['Shop_name']  = $param['consulation_shop'];
        // 客户所属店面
        $dataErp['photo_shop_code']  = $param['photo_shop_code'];
        // 客户所属店面
        $dataErp['photo_shop_name']  = $param['photo_shop_name'];
        // 事业部id
        $dataErp['Brandid']    = session('brandclass_id');
        // 订单备注  data里有
        $dataErp['Ordernote']  = $param['order_note'] ? trim($param['order_note']) : '';
        // 宝宝姓名 目前客资表中没有
        $dataErp['Bbname']     = $param['baby_name'] ? $param['baby_name'] : '';
        // 宝宝生日（阳历）
        $dataErp['Bbithdate']  = $param['baby_birthday'] ? date('Ymd', strtotime($param['baby_birthday'])) : '';
        // 宝宝性别
        $dataErp['Bbsex']      = $param['baby_sex'] ? $param['baby_sex'] : '';
        $dataErp['Bb_hospital']= $param['baby_address'] ? $param['baby_address'] : '';
        $dataErp['Cameraman']  = $lData['cameraman_name'] ? $lData['cameraman_name'] : '';
        $dataErp['mentor_a']  = $lData['tutor_name'] ? $lData['tutor_name'] : '';
        // 客户订单店面
        $dataErp['Shop_order_code'] = $param['shop_code'] ? $param['shop_code'] : session('shop_code');
        $dataErp['Shop_order_name'] = $param['shop_name'] ? $param['shop_name'] : session('shop_name');
        // 消费类型
        $dataErp['Consumption_type']= $param['consultation_type'] ? $param['consultation_type'] : '';
        // 开单方式（网付订单或者上门拍订单）
        $dataErp['order_method'] = $order_method;
        if($order_method == '上门拍订单'){
            $dataErp['Package_name'] = $param['package_name'] ? $param['package_name'] : '';
        }
        // 订单日期
        $dataErp['Targetdate']   = date('Ymd',strtotime($target_time));
        // 销售门市
        $dataErp['Storeconsuitant1'] = $param['reception_name'] ? $param['reception_name'] : '';
        // 地址
        $dataErp['Address_sheng'] = $param['province']?mb_substr($param['province'], 0,-1):'';
        $dataErp['Address_shi'] = $param['city']?$param['city']:'';
        $dataErp['Address_qu'] = $param['county']?$param['county']:'';
        $dataErp['Address'] = $param['customer_address'] ? $param['customer_address'] : '';
        // 接单点
        $dataErp['Acceptor_address'] = $param['customer_orderaddress'] ? $param['customer_orderaddress'] : '';
        // 预产日期
        $dataErp['Yc_day'] = $param['ready_baby_day'] ? $param['ready_baby_day'] : '';
        // 宝宝出生地
        $dataErp['Bb_hospital'] = $param['baby_address'] ? $param['baby_address'] : '';
        // 客资系统来源
        $dataErp['Customer_from']    = 'CRM';
        // 操作店
        $dataErp['Opershop']        = session('shop_name');
        $dataErp['Jiandangren']     = session('staff_name');
        // 意向套系
        $dataErp['Yxpackage_name']  = $param['package_name'];
        $dataErp['Yxpackage_price'] = $param['order_amount'];
        //消费类型
        $dataErp['Consumption_type'] = $param['consultation_type'] ? $param['consultation_type'] : '';
        $dataErp['Paymentmoney']= $param['paymentmoney'] ? $param['paymentmoney'] : 0;
        $dataErp['Paytype']     = $param['paytype'];
        $dataErp['Duikuanma']   = $param['duikuanma'];
        // 赠送底片数量
        $dataErp['give_photo_num'] = $param['give_photo_num'] ? (int)$param['give_photo_num'] : 0;
        if ($dataErp['Paymentmoney']>0) {
            if (!$dataErp['Paytype']) {
                return array('code'=>105,'msg'=>'请选择收款方式');
            }
        }
        $dataErp['Duikuanma']   = $param['duikuanma'];
        $dataErp['crm_visit_id']= $param['visit_id'];
        $dataErp['package_type']= $param['package_type'];
        $dataErp['tuiguangstaff'] = $customerInfo['recommend_staff'] ? $customerInfo['recommend_staff'] : NULL;
        // var_dump($dataErp);die;
        //一销锁定
        // var_dump($dataErp);
        // exit;
        // $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>session('shop_type')]);
        // ----------  ERP接口数据  结束  -------- //
        // 开启事务
        db()->startTrans();
        try {
            //更新主表
            dealMain($customerInfo['c_unique'],$cData);
            // 调 erp 接口
            // var_dump(json_encode($dataErp));
            // $response = $erpInterface->createOrder(json_encode($dataErp));
            
            $response = controller('erp/Erp','lib')->createOrder($dataErp);
            if($response['code'] != 200){
                $response['error'] = 1;
                db()->rollback();
                return $response;
            }
            // 记录日志
            $dataErp['OrderId'] = $response['orderId'];
            $requestLog['request_url'] = '/Erp/erp/zhuanOrder';
            $requestLog['request_data'] = json_encode($dataErp);
            $requestLog['request_start_time'] = microtime(true);
            $requestLog['create_time'] = $time;
            $requestLog['create_ip'] = get_client_ip();
            $requestLog['response_code'] = $response['code'];
            $requestLog['response_data'] = json_encode($response);
            $requestLog['request_end_time'] = microtime(true);
            db('crm_request_logs','db_logs')->insert($requestLog);

            // 写入客资表
            $cData['order_number'] = $response['orderId'];
            //修改客资为有效
            if($customerInfo['is_valid'] != 1){
                $cData['is_valid']= 1;
                $cData['yx_day']  = $time;
            }
            $cData['update_time'] = $time;
            // 修改追踪时间
            if(empty($customerInfo['c_star_day'])){
                $cData['c_star_day'] = $time;
                $cData['c_end_day'] = $time;
                $cData['last_trackday'] = $time;
            }else{
                $cData['c_end_day'] = $time;
                $cData['last_trackday'] = $time;
            }
            db('crm_c_customerinfo')->where('id', $customerInfo['id'])->update($cData);
            history_log($newData, $oldData, $customerInfo['id'], session('staff_id'), session('staff_name'));
            if($order_method != '上门拍订单'){
                // 作废未收款订单
                $zfSql = ' p.photodate="" OR p.photodate is null ';
                $zfOrder = db('c_customerorder')->alias('o')
                    ->join('c_customerphoto p','p.orderid=o.orderid','left')
                    ->join('c_paymentcontent c','c.orderid=o.orderid','left')
                    ->where('o.orderId','<>',$dataErp['OrderId'])
                    ->where('crm_customer_number',$customerInfo['customer_number'])
                    ->where('crm_c_unique',$customerInfo['c_unique'])
                    ->where('o.crm_order_type',1)
                    ->where('o.blankoutannal',0)
                    ->where('c.id', 'null')->where($zfSql)
                    ->column('o.orderId');

                if ($zfOrder) {
                    // $zfOrders = '';
                    // foreach ($zfOrder as $key => $value) {
                    //     $zfOrders .= $value.',';
                    // }
                    // $zfOrders = trim($zfOrders, ',');
                    // 调用作废方法
                    $zfParam['orderids']= $zfOrder;
                    $zfParam['zfTimes'] = $time;
                    $zfParam['zfReason']= 'CRM开单作废其他未付款订单';
                    $zfParam['staff_name']= session('staff_name');
                    $zfParam['staff_id']= session('staff_id');
                    $zfRes = controller('crm/Order', 'lib')->zfOrder($zfParam);
                    $zpLogs = '作废其他未支付订单，单号：'.implode(',', $zfOrder);
                }
            }
            
            //追踪记录
            $params['customer_id'] = $customerInfo['id'];
            $params['c_unique'] = $customerInfo['c_unique'];
            $params['customer_name'] = $customerInfo['customer_name'];
            $params['customer_number'] = $customerInfo['customer_number'];
            if($order_method == '上门拍订单'){
                $params['sales_remark'] = '上门拍订单';
            }else{
                $params['sales_remark'] = 'CRM网付订单。'.$zpLogs;
            }
            $params['sales_day'] = date('Y-m-d H:i:s',time());
            $params['sales_staff'] = session('staff_name');
            $params['sales_staff_id'] = session('staff_id');
            $params['sales_staff_number'] = session('staff_number');
            $params['shop_name'] = $customerInfo['shop_name'];
            $params['shop_code'] = $customerInfo['shop_code'];
            db('crm_c_salestrackinginfo')->insert($params);
            // cache('getCustomerTrackInfos'.$customerInfo['id'],null);
            cache('track_log_'.$customerInfo['c_unique'], null);
            getSalesTracking($customerInfo['id']);

            // var_dump($response);
            if ($response['code'] != '200') {
                db()->rollback();
                $arr = array('code'=>$response['code'],'msg'=>$response['msg'],'error'=>json_encode($response));
            }else{
                
                if($param['visit_id']){
                    db('crm_l_pc_log')->where('id',$param['visit_id'])->update($lData);
                }
                // 如果返回单号不一样，更改单号
                // if($response['Data'] != $order_sn){ 
                //     $order_sn = $response['Data'];
                //     db('crm_c_customerinfo')->where('id',$data['customer_id'])->update(['order_number'=>$order_sn]);
                //     db('crm_c_customer_order')->where('id',$oid)->update(['order_sn'=>$order_sn]);
                // }
                /**/
                // crm记录日志
                if($order_method == '上门拍订单'){
                    $crmLog = '上门拍订单';
                }else{
                    $crmLog = 'CRM转单';
                }
                $crmLog .= '，订单单号：'.$dataErp['orderId'].'；意向套系：'.$dataErp['Yxpackage_name'].'；';

                if ($dataErp['Paymentmoney']>0 ) {
                    $crmLog .= '收款方式：'.$dataErp['Paytype'].'；收款金额：'.$dataErp['Paymentmoney'].'；收款编号：'.$dataErp['Duikuanma'];
                }
                // history_log($crmLog, '', $customerInfo['id'], session('staff_id'), session('staff_name'));
                // history_log($newData, $oldData, $customerInfo['id'], session('staff_id'), session('staff_name'));
                // erp记录开单日志
                $erpLog[0]['module'] = 'erp';
                if($order_method == '上门拍订单'){
                    $erpLog[0]['controller'] = '上门拍手机端开单';
                }else{
                    $erpLog[0]['controller'] = 'CRM开单';
                }
                $erpLog[0]['action'] = 'add';
                $erpLog[0]['old_data']='开立订单；订单编号：'.$dataErp['OrderId'].'；意向套系：'.$dataErp['Yxpackage_name'].'；';
                $erpLog[0]['data'] = '';
                $erpLog[0]['customer_id'] = $dataErp['orderId'];
                $erpLog[0]['staff_name'] = session('staff_name');
                $erpLog[0]['staff_id'] = session('staff_id');
                $erpLog[0]['ip'] = get_client_ip();
                $erpLog[0]['create_time'] = $time;
                if ($dataErp['Paymentmoney']>0 ) {
                    $erpLog[1]['module'] = 'erp';
                    if($order_method == '上门拍订单'){
                        $erpLog[1]['controller'] = '上门拍手机端开单';
                    }else{
                        $erpLog[1]['controller'] = 'CRM开单';
                    }
                    $erpLog[1]['action'] = 'add';

                    $erpLog[1]['old_data'] = '订单编号：'.$dataErp['OrderId'].'；[CRM系统开单,款项名称：前期包套；支付方式：'.$dataErp['Paytype'].'；收款日期：'.date('Ymd').'；收款金额：'.$dataErp['Paymentmoney'].'；收款人：'.session('staff_name').'；收款编号：'.$dataErp['Duikuanma'].'。]';
                    $erpLog[1]['data'] = '';
                    $erpLog[1]['customer_id'] = $dataErp['orderId'];
                    $erpLog[1]['staff_name'] = session('staff_name');
                    $erpLog[1]['staff_id'] = session('staff_id');
                    $erpLog[1]['ip'] = get_client_ip();
                    $erpLog[1]['create_time'] = $time;
                }
                db('action_log','db_logs')->insertAll($erpLog);

                // 开完单 调vip接口
                $vipParam['tel']        = $dataErp['Wphone'];
                $vipParam['brand_id']   = session('brandclass_id');;
                $vipParam['order_code'] = $response['orderId'];
                $vipParam['one_money']  = 0;
                $vipParam['two_money']  = 0;
                $vipParam['one_detail'] = $dataErp['Paymentmoney'];
                $vipParam['two_detail'] = 0;
                $vipParam['order_time'] = date('Y-m-d');
                $vipParam['total_money']= 0;
                $vipParam['package_nam']= '';
                $vip = new \app\common\lib\vipInterface();
                $createRes = $vip->createOrder($vipParam);
                db()->commit();
                $arr = array('code'=>200,'msg'=>'开单成功');
            }
        } catch (Exception $e) {
            db()->rollback();
            if($order_method == '上门拍订单'){
                $error['action'] = '上门拍手机端开单';
            }else{
                $error['action'] = 'CRM开单';
            }
            $error['error_reason'] = '开单报错：客资id为：'.$customerInfo['id'].',单号为：'.$response['Data'];
            $error['create_time'] = date('Y-m-d H:i:s');
            $arr = array('code'=>100,'msg'=>'开单失败','data'=>$e->getMessage(),'sql'=>db()->getLastSql(),'line'=>$e->getLine(),'e'=>$e);
            db('crm_l_error_log')->insert($error);
        }
        return $arr;
    }
    //手机端转订单调用
    public function onlinezhuanOrder($param){
        // var_dump($param);
        // exit;
        $time = date('Y-m-d H:i:s',time());
        $target_time = trim($param['target_time']);
        /*if($param['target_time'] && $target_time > $time){
            $arr = array('code'=>600,'msg'=>'开单时间不能大于当前时间','data'=>$param['target_time']);
            return $arr;
        }*/
        if (!$param['customer_channel']) {
            return array('code'=>301, 'msg'=>'开单失败，没有渠道信息，无法转单','data'=>'','error'=>'没有渠道信息，无法转单');
        }
        $order_sn = $param['order_sn'];
        $customerInfo = db('crm_c_customerinfo')->where('id', $param['customer_id'])->find();

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

        $data['create_time'] = $time;
        $data['customer_id'] = (int)$customerInfo['id'];
        $data['customer_name'] = $param['customer_name'];
        $cData['customer_name'] = $param['customer_name'];
        $cData['customer_tel'] = $param['customer_tel'];
        $cData['customer_wechat'] = $param['customer_wechat'];
        $cData['mate_name'] = $param['mate_name'];
        $cData['mate_tel'] = $param['mate_tel'];
        $cData['mate_wechat'] = $param['mate_wechat'];
        $cData['baby_name'] = $param['baby_name'];
        $cData['baby_sex'] = $param['baby_sex'];
        $cData['baby_birthday'] = $param['baby_birthday'];
        $cData['baby_sex'] = $param['baby_sex'];
        $cData['reception_id'] = $param['reception_id'];
        $cData['reception_name'] = $param['reception_name'];
        $cData['sales_staff_id'] = $param['sales_staff_id'];
        $cData['sales_staff'] = $param['sales_staff'];
        // $cData['customer_area_id'] = intval($param['customer_area_id']);
        $cData['customer_area'] = $param['customer_area_id'];
        // $cData['customer_cource_id'] = intval($param['customer_cource_id']);
        $cData['customer_cource'] = $param['customer_cource_id'];
        $cData['customer_channel_id']=$data['customer_channel_id'] = intval($param['customer_channel_id']);
        $cData['customer_channel'] = $data['customer_channel'] = $param['customer_channel'];
        $cData['customer_orderaddress_id'] = intval($param['customer_orderaddress_id']);
        $cData['customer_orderaddress']=$data['customer_orderaddress'] = $param['customer_orderaddress'];
        $cData['mate_birthday'] = $param['mate_birthday'];
        $cData['customer_birthday'] = $param['customer_birthday'];
        $cData['totalpay_money'] = $param['order_amount'];
        $cData['marry_day'] = $param['marry_day'] ? $param['marry_day'] : null;
        $cData['ready_baby_day'] = $param['ready_baby_day'] ? $param['ready_baby_day'] : null;
        $cData['baby_address'] = $mData['babyhospital'] = $param['baby_address'];
        $cData['province_id'] = $param['province_id'];
        $cData['province'] = $param['province'];
        $cData['city_id'] = $param['city_id'];
        $cData['city'] = $param['city'];
        $cData['county_id'] = $param['county_id'];
        $cData['county'] = $param['county'];

        $data['consultation_type'] = $param['consultation_type'];

        $data['order_note'] = $param['order_note'];
        $data['order_sn'] = $order_sn;
        $data['order_type'] = 1;
        $data['brandclass_id'] = $param['brandclass_id'];
        $data['brandclass'] = $param['brandclass'];

        $cData['consultation_type_id']= (int)$param['consultation_type_id'];
        $cData['consultation_type']   = $param['consultation_type'];

        $mData['email'] = $param['email'];

        //摄影师
        $lData['cameraman_id'] = intval($param['cameraman_id']);
        $lData['cameraman_name'] = trim($param['cameraman']);

        $cData['is_success'] = 3;
        $cData['order_start_time'] = $data['target_time'];

        $data['order_valid'] = 1;
        // 是否安装erp
        $is_erp = is_install('sx_erp');
        if ($is_erp === false) {
            db()->startTrans();
            try {
                $order_sn = 'sx_crm'.time().generate_code();
                $data['order_sn'] = $order_sn;
                db('crm_c_customer_order')->insert($data);
                if($param['log_id']){
                    db('crm_l_pc_log')->where('id',$param['log_id'])->update($lData);
                }
                // 写入客资表
                $cData['order_number'] = $order_sn;
                $cData['c_end_day'] = $time;
                $cData['last_trackday'] = $time;


                $cData['order_type']    = 1;
                //修改客资为有效
                $info = db('crm_c_customerinfo')->where('id',$data['customer_id'])->find();
                if($info['is_valid'] != 1 || empty($info['yx_day'])){
                    $cData['is_valid'] = 1;
                    $cData['yx_day'] = $time;
                }
                $cData['update_time'] = date('Y-m-d H:i:s');
                db('crm_c_customerinfo')->where('id', $data['customer_id'])->update($cData);

                if($cData['is_success']){
                    //如果是爆破活动，修改对应的爆破表数据
                    if($info['is_act'] == 2){
                        db('crm_c_swap_customer')->where('customer_number',$info['customer_number'])->update(['is_success'=>$cData['is_success']]);
                    }
                }
                //修改主表
                db('crm_c_customer_main')->where('c_unique',$info['c_unique'])->update($mData);

                // crm记录日志
                history_log($cData, $customerInfo, $param['customer_id'], $param['staff_id'], $param['staff_name']);
                //追踪记录
                $params['customer_id'] = $data['customer_id'];
                $params['c_unique'] = $customerInfo['c_unique'];
                $params['customer_name'] = $customerInfo['customer_name'];
                $params['customer_number'] = $customerInfo['customer_number'];
                $params['sales_remark'] = '体验拍转订单-'.$data['order_note'];
                $params['sales_day'] = date('Y-m-d H:i:s',time());
                $params['sales_staff'] = $param['staff_name'];
                $params['sales_staff_id'] = $param['staff_id'];
                $params['sales_staff_number'] = $param['staff_number'];
                $params['shop_name'] = $param['shop_name'];
                $params['shop_code'] = $param['shop_code'];
                db('crm_c_salestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$data['customer_id'],null);

                getSalesTracking($data['customer_id']);

                db()->commit();
                $arr = array('code'=>200,'msg'=>'转订单成功');
            } catch (Exception $e) {
                db()->rollback();
                $arr = array('code'=>100,'msg'=>'转订单失败','data'=>$e->getMessage());
            }
            return $arr;
        }

        // ----------  ERP接口数据  开始  -------- //
        $dataErp = [];
        $dataErp['OrderId'] = $order_sn ? $order_sn : '';
        // 来源渠道
        // if ($customerInfo['customer_channel_id']) {
        //     $channel_info_name = db('crm_s_channel')->where('id', $customerInfo['customer_channel_id'])->value('channel_info_name');
        //     $dataErp['Customer_channel'] = $channel_info_name;
        // }else{
        //     $dataErp['Customer_channel'] = '';
        // }
        $dataErp['Customer_channel'] = $cData['customer_channel'];
        // 客资编号
        $dataErp['crm_customer_id'] = $customerInfo['id'];
        $dataErp['Customer_from_index'] = $customerInfo['customer_number'];
        $dataErp['crm_c_unique'] = $customerInfo['c_unique'];
        // 联系邮箱
        $dataErp['Email'] = $param['email'] ? $param['email'] : '';
        // 客户来源
        $dataErp['Cssname'] = $param['customer_cource_id'] ? $param['customer_cource_id'] : '';
        // 客户分区
        $dataErp['Area'] = $param['customer_area_id'] ? $param['customer_area_id'] : '';
        // 结婚日期
        $dataErp['Weddingdate']= $param['marry_day'] ? $param['marry_day'] : '';
        $dataErp['Wname']      = $param['customer_name'] ? $param['customer_name'] : '';
        $dataErp['Wphone']     = $param['customer_tel'] ? $param['customer_tel'] : '';
        $dataErp['Wwechat']    = $param['customer_wechat'] ? $param['customer_wechat'] : '';
        $dataErp['Wbirthdate'] = $param['customer_birthday'] ? $param['customer_birthday'] : '';
        $dataErp['Mname']      = $param['mate_name'] ? $param['mate_name'] : '';
        $dataErp['Mphone']     = $param['mate_tel'] ? $param['mate_tel'] : '';
        $dataErp['Mwechat']    = $param['mate_wechat'] ? $param['mate_wechat'] : '';
        $dataErp['Mbirthdate'] = $param['mate_birthday'] ? $param['mate_birthday'] : '';
        // 客户所属店面
        $dataErp['Shop_code']  = session('shop_code');
        // 客户所属店面
        $dataErp['Shop_name']  = session('shop_name');
        // 客户所属店面
        $dataErp['photo_shop_code'] = $param['photo_shop_code'];
        // 客户所属店面
        $dataErp['photo_shop_name']  = $param['photo_shop_name'];
        // 事业部id
        $dataErp['Brandid']    = session('brandclass_id');

        // 订单备注  data里有
        $dataErp['Ordernote']  = $param['order_note'] ? trim($param['order_note']) : '';
        // 宝宝姓名 目前客资表中没有
        $dataErp['Bbname']     = $param['bbname'] ? $param['bbname'] : '';
        // 宝宝生日（阳历）
        $dataErp['Bbithdate']  = $param['baby_birthday'] ? date('Ymd', strtotime($param['baby_birthday'])) : '';
        // 宝宝性别
        $dataErp['Bbsex']      = $param['bbsex'] ? $param['bbsex'] : '';
        $dataErp['Bb_hospital']= $param['baby_address'] ? $param['baby_address'] : '';
        $dataErp['Cameraman']  = $param['cameraman'] ? $param['cameraman'] : '';
        // 客户订单店面
        $dataErp['Shop_order_code'] = $param['consulation_shop_code'];
        $dataErp['Shop_order_name'] = $param['consulation_shop'];
        // 消费类型
        $dataErp['Consumption_type']= $param['consultation_type'] ? $param['consultation_type'] : '';
        // 套餐名称 目前客资表中没有
        $dataErp['Package_name'] = $param['Package_name'] ? $param['Package_name'] : '';
        // 订单日期
        $dataErp['Targetdate']   = date('Ymd',strtotime($target_time));
        // 销售门市
        $dataErp['Storeconsuitant1'] = $param['reception_name'] ? $param['reception_name'] : '';
        $dataErp['Address_sheng'] = $param['province']?$param['province']:'';
        $dataErp['Address_shi'] = $param['city']?$param['city']:'';
        $dataErp['Address_qu'] = $param['county']?$param['county']:'';
        // 地址
        $dataErp['Address'] = $param['customer_address'] ? $param['customer_address'] : '';
        // 网销门市
        $dataErp['Storeconsuitant2'] = $param['sales_staff'] ? $param['sales_staff'] : session('staff_name');
        // 接单点
        $dataErp['Acceptor_address'] = $param['customer_orderaddress'] ? $param['customer_orderaddress'] : '';
        // 预产日期
        $dataErp['Yc_day'] = $param['ready_baby_day'] ? $param['ready_baby_day'] : '';
        // 宝宝出生地
        $dataErp['Bb_hospital'] = $param['baby_address'] ? $param['baby_address'] : '';
        // 客资系统来源
        $dataErp['Customer_from']    = 'CRM';
        // 操作店
        $dataErp['Opershop']        = session('shop_name');
        $dataErp['Jiandangren']     = session('staff_name');
        // 意向套系
        $dataErp['Yxpackage_name']  = $param['package_name'];
        $dataErp['Yxpackage_price'] = $param['order_amount'];
        //消费类型
        $dataErp['Consumption_type'] = $param['consultation_type'] ? $param['consultation_type'] : '';
        $dataErp['Paymentmoney']= $param['paymentmoney'] ? $param['paymentmoney'] : 0;
        $dataErp['Paytype']     = $param['paytype'];
        $dataErp['Duikuanma']   = $param['duikuanma'];
        // 赠送底片数量
        $dataErp['give_photo_num'] = $param['give_photo_num'] ? (int)$param['give_photo_num'] : 0;
        if ($dataErp['Paymentmoney']>0 ) {
            if (!$dataErp['Paytype']) {
                return array('code'=>105,'msg'=>'请选择收款方式');
            }
            if (!$dataErp['Duikuanma']) {
                return array('code'=>105,'msg'=>'请输入收款编号');
            }
        }
        $dataErp['Duikuanma']   = $param['duikuanma'];
        //一销锁定
        // var_dump($dataErp);
        // exit;
        // $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>session('shop_type')]);
        // ----------  ERP接口数据  结束  -------- //
        // 开启事务
        db()->startTrans();
        try {
            $data['order_sn'] = $order_sn;
            if($param['log_id']){
                db('crm_l_pc_log')->where('id',$param['log_id'])->update($lData);
            }
            $oid = db('crm_c_customer_order')->insertGetId($data);

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

            //修改客资为有效
            if($customerInfo['is_valid'] != 1){
                $cData['is_valid']= 1;
                $cData['yx_day']  = $time;
            }
            $cData['update_time'] = $time;
            // if($cData['is_success']){
            //     //如果是爆破活动，修改对应的爆破表数据
            //     if($customerInfo['is_act'] == 2){
            //         db('crm_c_swap_customer')->where('customer_number',$customerInfo['customer_number'])->update(['is_success'=>$cData['is_success']]);
            //     }
            // }
            // 修改追踪时间
            if(empty($customerInfo['c_star_day'])){
                $cData = array(
                    'c_star_day' => $time,
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }else{
                $cData = array(
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }
            db('crm_c_customerinfo')->where('id', $data['customer_id'])->update($cData);

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

            getSalesTracking($data['customer_id']);

            //更新主表
            dealMain($customerInfo['c_unique'],$cData);
            // 调 erp 接口
            // var_dump(json_encode($dataErp));
            // $response = $erpInterface->createOrder(json_encode($dataErp));
            $response = controller('erp/Erp','lib')->createOrder($dataErp);
            // var_dump($response);
            if ($response['code'] != '200') {
                db()->rollback();
                $arr = array('code'=>$response['code'],'msg'=>$response['msg'],'error'=>json_encode($response));
            }else{
                // 如果返回单号不一样，更改单号
                // if($response['Data'] != $order_sn){
                //     $order_sn = $response['Data'];
                //     db('crm_c_customerinfo')->where('id',$data['customer_id'])->update(['order_number'=>$order_sn]);
                //     db('crm_c_customer_order')->where('id',$oid)->update(['order_sn'=>$order_sn]);
                // }
                // crm记录日志
                $crmLog = '网付订单，订单单号：'.$dataErp['OrderId'].'；意向套系：'.$param['package_name'].'；';
                if ($dataErp['Paymentmoney']>0 ) {
                    $crmLog .= '收款方式：'.$dataErp['paytype'].'；收款金额：'.$dataErp['paymentmoney'].'；收款编号：'.$dataErp['duikuanma'];
                }
                history_log($crmLog, $customerInfo, $param['customer_id'], $param['staff_id'], $param['staff_name']);
                // erp记录开单日志
                $erpLog[0]['module'] = 'erp';
                $erpLog[0]['controller'] = 'crm开单';
                $erpLog[0]['action'] = 'add';
                $erpLog[0]['old_data']='开立订单；订单编号：'.$dataErp['OrderId'].'；';
                $erpLog[0]['data'] = '';
                $erpLog[0]['customer_id'] = $dataErp['OrderId'];
                $erpLog[0]['staff_name'] = session('staff_name');
                $erpLog[0]['staff_id'] = session('staff_id');
                $erpLog[0]['ip'] = get_client_ip();
                $erpLog[0]['create_time'] = $time;

                if ($dataErp['Paymentmoney']>0 ) {
                    $erpLog[1]['module'] = 'erp';
                    $erpLog[1]['controller'] = 'CRM开单开单收款';
                    $erpLog[1]['action'] = 'add';
                    $erpLog[1]['old_data'] = '订单编号：'.$dataErp['OrderId'].'；[CRM开单收款,款项名称：前期包套；支付方式：'.$dataErp['paytype'].'；收款日期：'.date('Ymd').'；收款金额：'.$dataErp['paymentmoney'].'；收款人：'.session('staff_name').'；收款编号：'.$dataErp['duikuanma'].'。]';
                    $erpLog[1]['data'] = '';
                    $erpLog[1]['customer_id'] = $dataErp['OrderId'];
                    $erpLog[1]['staff_name'] = session('staff_name');
                    $erpLog[1]['staff_id'] = session('staff_id');
                    $erpLog[1]['ip'] = get_client_ip();
                    $erpLog[1]['create_time'] = $time;
                }
                db('action_log','db_logs')->insertAll($erpLog);

                // 开完单 调vip接口
                $vipParam['tel']        = $dataErp['Wphone'];
                $vipParam['brand_id']   = $param['brandclass_id'];;
                $vipParam['order_code'] = $dataErp['OrderId'];
                $vipParam['one_money']  = 0;
                $vipParam['two_money']  = 0;
                $vipParam['one_detail'] = $dataErp['Paymentmoney'];
                $vipParam['two_detail'] = 0;
                $vipParam['order_time'] = date('Y-m-d');
                $vipParam['total_money']= 0;
                $vipParam['package_nam']= '';
                $vip = new \app\common\lib\vipInterface();
                $createRes = $vip->createOrder($vipParam);

                db()->commit();
                $arr = array('code'=>200,'msg'=>'转订单成功');
            }
        } catch (Exception $e) {
            db()->rollback();
            $error['action'] = '上门拍转订单';
            $error['error_reason'] = '转单报错：客资id为：'.$customerInfo['id'].',单号为：'.$response['Data'];
            $error['create_time'] = date('Y-m-d H:i:s');
            $arr = array('code'=>100,'msg'=>'转订单失败','data'=>$e->getMessage(),'sql'=>db()->getLastSql());
            db('crm_l_error_log')->insert($error);
        }
        return $arr;
    }

    // -------------------------------------------- 儿童排控 (选片、摄影) 开始 -------------------------------------------- //

    // 儿童排程调度 页面 20181110
    public function childArrange(){

        // 权限
        $auth = check_right('menu1542196979');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有排控的权限，请先设置权限');
            return json($return);
            exit;
        }

        // 当前员工的可操作店
        $param = [
            'brandclass_id'   => session('brandclass_id'),
            'staff_id'        => session('staff_id'),
            'shop_type'       => session('shop_type'),
            'shop_code'       => session('shop_code'),
            'belong_shop_code'=> session('belong_shop_code'),
            'belong_shop_name'=> session('belong_shop_name'),
        ];
        $shop_list = getBelongShop($param);
        $this->assign('shop_list', $shop_list);

        // 分区
        $area_list = controller('crm/Customer', 'lib')->areaSet();
        $this->assign('area_list', $area_list);
        return $this->fetch();
    }

    // 获取订单信息 (直接调erp库)
    public function getOrderList(){

        $param = input('get.param');
        $param = json_decode($param, true);
        $keyword = $param['keyword'];
        $shop_code = $param['shop_code'];
        $area = $param['area'];

        $where['b.shop_code']= $shop_code;
        // 测试数据
        // $where['b.shop_code']= 'RT001';
        if ($area) {
            $where['a.area'] = $area;
        }

        $start= $param['start'] ? date('Ymd', strtotime($param['start'])) : '0';
        $end  = $param['end'] ? date('Ymd', strtotime($param['end'])) : date('Ymd');

        $order_list = db('c_customerinfo')->alias('a')
            ->join('c_customerorder b','a.customerid = b.customerid', 'left')
            ->join('c_customerphoto c','b.orderId = c.orderId', 'left')
            ->where($where)
            ->where('b.targetdate','>=',$start)
            ->where('b.targetdate','<=',$end)
            ->where('a.mphone|a.wphone|b.orderId', 'like','%'.$keyword.'%')
            ->field('CONCAT_WS(" ",a.mname,a.wname) as xingming,a.mname,a.wname,a.bbname,a.wphone,a.mphone,a.cssname,a.area,a.customerid,b.orderId,b.targetdate,b.consumption_type,b.acceptor_address,b.total_money,b.payment_money,b.nopayment_money,b.ordertopic,b.dresstheme, b.ordernote,c.currentfc,c.phototype,c.photodate, c.phototime ,c.photostate,c.cameraman,c.photoassistant,c.lighting_engineer,c.designer,c.mentor_a,c.mentor_b,c.dresser,c.photonote ,c.photobase,c.id,c.id as photoid,c.shop_code,c.jiaji,c.huazhuangzhuli,c.communication_date,c.communicationtime,c.communication_state,c.communication_man,c.secretaireman,c.shop_name,c.shop_code')
            ->order('b.targetdate desc')
            ->select();
        return json(array('code' => 0, 'msg' => '', 'count' => count($order_list), 'data' => $order_list));
    }

    // 获取排控列表
    public function getPcList(){
        $param = input('post.');
        $shop_code = $param['shop_code'];
        // 测试数据
        //$shop_code = 'RT001';
        $start= $param['start'] ? date('Ymd', strtotime($param['start'])) : '0';
        $end  = $param['end'] ? date('Ymd', strtotime($param['end'])) : date('Ymd');

        $time_area = getDateFromRange($start,$end);

        $returnData = [];

        foreach ($time_area as $key => $value) {
            $returnData[$key]['day'] = date('Ymd', strtotime($value));
        }
        unset($time_area);
        // 查设定 (可排程)
        $pc_set = db('s_pcdefault_monthset')
            ->where('pctype', 0) // 0:拍照排程;1:选片排程
            ->where('shop_code', $shop_code)
            ->where('pcday','between',[$start,$end])
            ->group('pcday')
            ->field('pcday,sum(timecount) ss')
            ->select();
        foreach ($returnData as $key => $value) {
            if ($value['day'] == $pc_set[$key]['pcday']) {
                $returnData[$key]['allPc'] = $pc_set[$key]['ss'];
            }else{
                $returnData[$key]['allPc'] = 0;
            }
        }
        unset($pc_set);
        // 查排程 已排程
        $pc_list = db('c_customerphoto')
            ->where('shop_code', $shop_code)
            ->where('photodate','between',[$start,$end])
            ->field('photodate,count(orderId) as su,cameraman,photoassistant,dresser')
            ->group('photodate')
            ->order('photodate')
            ->select();
        foreach ($returnData as $key => $value) {
            if ($value['day'] == $pc_list[$key]['photodate']) {
                $returnData[$key]['yPc'] = $pc_list[$key]['su'];
                $returnData[$key]['nPc'] = $value['allPc'] - $pc_list[$key]['su'];
            }else{
                $returnData[$key]['yPc'] = 0;
                $returnData[$key]['nPc'] = $value['allPc'];
            }
        }

        //已排程 摄影师 摄影助理 化妆师数量
        foreach ($returnData as $key => $value) {
            //摄影师
            $sql = 'select cameraman,COUNT(1)AS all_num FROM c_customerphoto GROUP BY cameraman';
            $syer = db('c_customerphoto')
                ->where('photodate',$value['day'])
                ->field('cameraman AS staffname,COUNT(1) AS num')
                ->group('cameraman')
                ->select();

            foreach($syer as $syKey => $syVal){
                if(empty($syVal['staffname']))  unset($syer[$syKey]);
            }

            $returnData[$key]['syer'] = $syer;

            // 摄影助理
            $syzler = db('c_customerphoto')
                ->where('photodate',$value['day'])
                ->field('photoassistant AS staffname,COUNT(1) AS num')
                ->group('photoassistant')
                ->select();

            foreach($syzler as $zlKey => $zlVal){
                if(empty($zlVal['staffname']))  unset($syzler[$zlKey]);
            }
            $returnData[$key]['syzler'] = $syzler;

            //化妆师
            $hzer = db('c_customerphoto')
                ->where('photodate',$value['day'])
                ->field('dresser AS staffname,COUNT(1) AS num')
                ->group('dresser')
                ->select();

            foreach($hzer as $hzKey => $hzVal){
                if(empty($hzVal['staffname']))  unset($hzer[$hzKey]);
            }
            $returnData[$key]['hzer'] = $hzer;

        }

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

    //获取某个列表上方下方 排控统计数量
    public function reloadTableNum(){

        $photodate = input('photodate');
        $shop_code = input('shop_code');

        $res = controller('erp/Erp','lib')->reloadTableNum($photodate,$shop_code);

        return json(array('code'=>200,'msg'=>'success','data'=>$res));

    }

    /*
     * 获取可排控数量
     * $shop_code   店面识别码
     * $photodate   时间
     */
    public function getPcNum(){
        $photodate = input('photodate');
        $shop_code = input('shop_code');
        $res = controller('erp/Erp','lib')->getPcNum($photodate,$shop_code);
        if($res['nPc'] < 1){
            return json(array('code'=>201,'msg'=>'不可再添加排程'));
        }else{
            return json(array('code'=>200,'msg'=>'ok'));
        }
    }

    // 获取每一天的排程列表
    public function getPcListDay(){
        $param = input('get.');
        $shop_code = $param['shop_code'];
        $photodate = date('Ymd',strtotime($param['day']));

        $all_list = controller('erp/Erp','lib')->getPcListDay($photodate,$shop_code);

        return json(array('code'=>0, 'msg'=>'', 'count'=>count($all_list), 'data'=>$all_list));
    }

    // 某个订单排控信息
    public function singlePcInfo(){

        $orderId = input('orderId');
        $list = db('c_customerinfo')->alias('a')
            ->join('c_customerorder b','a.customerid = b.customerid', 'left')
            ->join('c_customerphoto c','b.orderId = c.orderId', 'left')
            ->where('c.orderId',$orderId)
            ->field('CONCAT_WS(" ",a.mname,a.wname) as xingming,a.mname,a.wname,a.bbname,a.wphone,a.mphone,a.cssname,a.area,a.customerid,b.targetdate,b.consumption_type,b.acceptor_address,b.total_money,b.payment_money,b.nopayment_money  ,b.ordertopic,b.dresstheme, b.ordernote,c.orderId,c.currentfc,c.phototype,c.photodate, c.phototime ,c.photostate,c.cameraman,c.photoassistant,c.lighting_engineer,c.designer,c.mentor_a,c.mentor_b,c.dresser,c.photonote ,c.photobase,c.id,c.id as photoid,c.shop_code,c.jiaji,c.huazhuangzhuli,c.communication_date,c.communicationtime,c.communication_state,c.communication_man,c.secretaireman,c.shop_name,c.shop_code')
            ->order('b.targetdate desc')
            ->select();
        return json(array('code'=>0, 'msg'=>'', 'count'=>count($list), 'data'=>$list));

    }

    // 新增、编辑 排程页面
    public function addPc(){
        if(Request::instance()->isPost()){
            //新增或编辑排程信息
            $id = input('id');

            $time = date('Y-m-d H:i:s');
            $data = [
                'phototype' => input('phototype'),
                'photodate' => input('photodate'),
                'phototime' => input('phototime'),
                'photostate'=> input('photostate'),
                'cameraman' => input('cameraman'),
                'photoassistant' => input('photoassistant'),
                'huazhuangzhuli' => input('huazhuangzhuli'),
                'secretaireman'  => input('secretaireman'),
                'lighting_engineer' => input('lighting_engineer'),
                'dresser'   => input('dresser'),
                'mentor_a'  => input('mentor_a'),
                'mentor_b'  => input('mentor_b'),
                'paikongstaff' => session('staff_name'),
                'paikongtime'  => $time,
                'shop_name' => input('shop_name'),//排控店名称
                'shop_code' => input('shop_code'),//排控店code
                'setkey'    => session('shop_code'),//操作人店code
                'photo_shop_code' => session('shop_code'),//操作人店code
            ];

            //操作日志
            $logData = [
                'module' => 'erp',
                'controller'=>'线上排程',
                'action' => 'line',
                'customer_id' => input('orderId'),
                'staff_name'  => session('staff_name'),
                'staff_id'    => session('shop_code'),
                'ip' => get_client_ip(),
            ];


            db()->startTrans();
            try{
                //选择了新增拍照 或者选择的是订单还未排程
                if(input('is_add') == 1 || !$id){
                    $add = $data;
                    $add['orderId']  = input('orderId');
                    $add['currentfc'] = 1;
                    $add['customerid'] = input('customerid');
                    $add['create_time'] = $time;
                    $lastId = db('c_customerphoto')->insertGetId($add);

                    //操作日志
                    $logData['old_data'] = '新增排程：[';
                    $logData['old_data'] .= '单号：'.input('orderId').'；拍照日期：'.input('photodate').'；拍照时间：'.input('phototime');
                    $logData['old_data'] .= '；拍照类型:'.input('phototype').'；拍照状态：'.$this->photoStateName(input('photostate')).'；摄影师：'.input('cameraman');
                    $logData['old_data'] .= '；摄影助理:'.input('photoassistant').'；化妆师：'.input('dresser').'；化妆助理：'.input('huazhuangzhuli');
                    $logData['old_data'] .= '；灯光师:'.input('lighting_engineer').'；礼服秘书：'.input('secretaireman');
                    $logData['old_data'] .= '；引导师A:'.input('mentor_a').'；引导师B：'.input('mentor_b').']';
                    $logData['create_time'] = $time;

                    db('action_log','sx_erp_logs')->insert($logData);

                }else{
                    $oldData = db('c_customerphoto')->where('id',$id)->find();

                    $addLog = [];
                    // 对比提交数据和原始数据
                    foreach ($data as $key => $value) {
                        $oneLog = [];
                        if ($value != $oldData[$key]) {
                            //排空时间差异不记录操作日志
                            if($key == 'paikongtime')  continue;

                            //获取字段对应文字名称
                            $name = $this -> getName($key);

                            $oneLog = $logData;

                            //若是拍照状态，获取状态码对应文字名称
                            if($key == 'photostate'){
                                $oneLog['old_data'] = $name.':将['.$this->photoStateName($oldData[$key]).']修改为:['.$this->photoStateName($value).']';
                            }else{
                                $oneLog['old_data'] = $name.':将['.$oldData[$key].']修改为:['.$value.']';
                            }

                            $oneLog['update_time'] = $time;
                            $addLog[] = $oneLog;
                        }
                    }

                    db('c_customerphoto')->where('id',$id)->update($data);
                    db('action_log','sx_erp_logs')->insertAll($addLog);

                }

                //在订单表追加备注
                $note = input('note');
                $sql="UPDATE c_customerorder SET ordernote = CONCAT(ordernote,'".$note."')WHERE orderId='".input('orderId')."'";
                db('c_customerorder')->query($sql);

                db()->commit();
                return json(array('code'=>200,'msg'=>'排程成功！','data'=>$lastId));

            }catch (\Exception $e){
                print_r($e->getMessage());
                db()->rollback();
                return json(array('code'=>201,'msg'=>'排程失败，请稍后重试'));

            }

        }else{
            //渲染排程页面
            $photo_id = input('photo_id');   //排程列表中ID
            $orderId = input('orderId');     //选中数据的订单号
            $customerid = input('customerid');//选中数据的客资编号

            $view_phototime = input('view_phototime'); //选中某行规则的拍照时间

            $shop_code = input('shop_code');
            $shop_name = input('shop_name');
            $photodate = input('photodate');

            //若选中的是排程信息 则对此排程信息进行编辑
            if(!empty($photo_id) && $photo_id>0){
                $pcInfo = db('c_customerphoto')->where('id',$photo_id)->find();
            }

            //$orderInfo = db('c_customerorder')->where('orderId',$orderId)->find();

            //摄影师
            $cameraman = getShopStaffs(['shop_code'=>$shop_code,'work_type'=>3]);
            //摄影助理
            $photoassistant = getShopStaffs(['shop_code'=>$shop_code,'work_type'=>4]);
            //化妆师、化妆助理
            $dresser = getShopStaffs(['shop_code'=>$shop_code,'work_type'=>7]);
            //灯光师
            $lighting_engineer = getShopStaffs(['shop_code'=>$shop_code,'work_type'=>5]);
            //礼服秘书
            $secretaireman = getShopStaffs(['shop_code'=>$shop_code,'work_type'=>2]);
            //引导师A、引导师B
            $mentor = getShopStaffs(['shop_code'=>$shop_code,'work_type'=>25]);

            $this->assign([
                'mentor'  => $mentor,
                'dresser' => $dresser,
                'cameraman' => $cameraman,
                'secretaireman'  => $secretaireman,
                'photoassistant' => $photoassistant,
                'lighting_engineer' => $lighting_engineer,
            ]);
            $this->assign([
                'pcInfo'  => $pcInfo,
                'orderId' => $orderId,
                //'orderInfo' =>$orderInfo,
                'shop_code' => $shop_code,
                'shop_name' => $shop_name,
                'customerid'=> $customerid,
                'photodate' => $photodate,
                'view_phototime' => $view_phototime
            ]);

            return $this->fetch();
        }

    }

    //获取服务人员对应名称
    public function getName($key){
        $name = '';
        if($key == 'photodate'){
            $name = '拍照日期';
        }elseif($key == 'phototime'){
            $name = '拍照时间';
        }elseif($key == 'photostate'){
            $name = '拍照状态';
        }elseif($key == 'photostate'){
            $name = '拍照状态';
        }elseif($key == 'phototype'){
            $name = '拍摄类型';
        }elseif($key == 'cameraman'){
            $name = '摄影师';
        }elseif($key == 'photoassistant'){
            $name = '摄影助理';
        }elseif($key == 'dresser'){
            $name = '化妆师';
        }elseif($key == 'huazhuangzhuli'){
            $name = '化妆助理';
        }elseif($key == 'lighting_engineer'){
            $name = '灯光师';
        }elseif($key == 'secretaireman'){
            $name = '礼服秘书';
        }elseif($key == 'mentor_a'){
            $name = '引导师A';
        }elseif($key == 'mentor_b'){
            $name = '引导师B';
        }
        return $name;
    }

    //获取拍照状态对应名称
    public function photoStateName($photostate){
        switch($photostate){
            case '0':
                $photostate = '全未拍';
                break;
            case '1':
                $photostate = '未拍完';
                break;
            case '2':
                $photostate = '已拍完';
                break;
            default:
                $photostate = '未选择';
        }
        return $photostate;
    }

    // 删除排程信息
    public function delPc(){
        $id = input('id');

        if(!$id)   return array('code'=>201,'msg'=>'未获取到排程信息，请稍后重试！');

        //原信息
        $oldData = db('c_customerphoto')->where('id',$id)->find();
        $orderId = $oldData['orderId'];
        $currentfc = $oldData['currentfc'];

        if(!$orderId || !$currentfc){
            $pcInfo = db('c_customersp')->where('id',$id)->find();
            $orderId = $pcInfo['orderId'];
            $currentfc = $pcInfo['currentfc'];
        }

        //查看选片表 是否有选片时间
        $spInfo = db('c_customersp')
            ->where(['orderId'=>$orderId,'currentfc'=>$currentfc])
            ->where('selectday is not null')
            ->find();


        $old_data = '删除排程:[';
        $old_data .= '单号：'.$orderId.'；拍照日期：'.$oldData['photodate'].'；拍照时间：'.$oldData['phototime'];
        $old_data .= '；拍照类型：'.$oldData['phototype'].'；拍照状态：'.$this->photoStateName($oldData['photostate']).'；摄影师：'.$oldData['cameraman'];
        $old_data .= '；摄影助理：'.$oldData['photoassistant'].'；化妆师：'.$oldData['dresser'].'；化妆助理：'.$oldData['huazhuangzhuli'];
        $old_data .= '；灯光师：'.$oldData['lighting_engineer'].'；礼服秘书：'.$oldData['secretaireman'];
        $old_data .= '；引导师A：'.$oldData['mentor_a'].'；引导师B：'.$oldData['mentor_b'].']';

        //操作日志
        $logData = [
            'module' => 'erp',
            'controller'=>'线上排程',
            'action' => 'line',
            'old_data' => $old_data,
            'customer_id' => $oldData['orderId'],
            'staff_name'  => session('staff_name'),
            'staff_id'    => session('shop_code'),
            'ip' => get_client_ip(),
            'delete_time' => date('Y-m-d H:i:s')
        ];

        db()->startTrans();
        try{
            //若未选片 删除，否则情况排程时间
            if(empty($spInfo)){
                db('c_customerphoto')->where('id',$id)->delete();
            }else{
                db('c_customerphoto')->where('id',$id)->update(['photodate'=>null,'phototime'=>null]);
            }

            //日志
            db('action_log','sx_erp_logs')->insert($logData);

            db()->commit();
            return json(array('code'=> 200,'msg'=>'删除排程成功！'));

        }catch (\Exception $e){
            db()->rollback();
            return json(array('code'=> 202,'msg'=>'删除排程失败，请稍后重试！'));
        }

    }

    // -------------------------------------------- 儿童排控 (选片、摄影) 结束 -------------------------------------------- //
    
}