<?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 customerList(){
        $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');
        $result['code'] = 0;
        $result['msg'] = '';
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 100;
        $where = [];
        if($param['customer_name']){
            $where['c.customer_name'] = trim($param['customer_name']);
        }
        if($param['customer_tel']){
            $where['c.customer_tel'] = trim($param['customer_tel']);
        }
        $info = db('c_customerinfo')->alias('c')->join('l_pc_log l','c.id=l.cid')->join('c_customer_from f','f.cid=c.id')
            ->where('l.pc_shop_code',session('shop_code'))
            ->where('l.pc_time','between',[$start,$end])
            ->where($where)
            ->field('l.id,l.cid,l.time,c.customer_name,c.customer_tel,l.result,customer_address,l.pc_time,l.area_name,c.shop_name,l.pc_shop_name,l.cameraman_name,l.sale_name,l.tutor_name,f.hd_name,f.code,l.remark,f.is_hx,f.hx_time,f.staff_name,c.is_success')
            ->page($page)->limit($limit)
            ->order('l.pc_time desc,l.time asc')
            ->select();
        $count = db('c_customerinfo')->alias('c')->join('l_pc_log l','c.id=l.cid')
            ->where('l.pc_shop_code',session('shop_code'))
            ->where($where)
            ->where('l.pc_time','between',[$start,$end])
            ->count();
        $result['data'] = $info;
        $result['count'] = $count;

        return json($result);
    }
    //通过核销码获取客资信息
    public function tan_code(){
        $code = input('param.code');
        $info = db('c_customerinfo')->alias('c')->join('l_pc_log l','c.id=l.cid')->join('c_customer_from f','f.cid=c.id')
            ->where('l.pc_shop_code',session('shop_code'))
            ->where('f.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,f.code,f.hd_name,f.is_hx,f.hx_time,f.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'] ? $info['result'] : '';
        $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'] : '';
        $info['is_hx'] = $info['is_hx']==2 ? '已核销' : '未核销';
        $info['hx_time'] = $info['hx_time'] ? $info['hx_time'] : '';
        $info['staff_name'] = $info['code'] ? $info['staff_name'] : '';
        $info['hd_name'] = $info['code'] ? $info['hd_name'] : '';
        $this->assign('info',$info);
        return $this->fetch();
    }

    //核销
    public function markHX(){
        $data = input();
        if(empty($data['cid'])){
            return array('code'=>100,'msg'=>'未获取到客资id');
        }
        if(empty($data['code'])){
            return array('code'=>101,'msg'=>'未获取到核销码');
        }
        $res = db('c_customer_from')->where('cid',$data['cid'])->where('code',$data['code'])->find();
        if(empty($res)){
            return array('code'=>102,'msg'=>'未获取到信息，请确定此核销码正确？');
        }
        $info = controller('crm/Customer','lib')->getCustomerInfo($data['cid']);
        db()->startTrans();
        try{
            $from = [
                'staff_id'=>session('staff_id'),
                'staff_name'=>session('staff_name'),
                'code'=>NULL,
                'is_hx'=>2,
                'hx_time'=>date('Y-m-d H:i:s')
            ];
            db('l_pc_log')->alias('l')->join('c_customer_from f','l.cid=f.cid','left')
                ->where('l.cid',intval($data['cid']))
                ->where('f.code',$data['code'])
                ->update(['l.result'=>2]);
            db('c_customer_from')->where('cid',intval($data['cid']))->where('code',$data['code'])->update($from);
            $arr = [
                'is_intostore' => 2,
                'syjd_day' => date('Y-m-d H:i:s')
            ];
            db('c_customerinfo')->where('id',intval($data['cid']))->update($arr);

            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 markResult(){
        $data = input();
        if(empty($data['id'])){
            return array('code'=>100,'msg'=>'未获取到id');
        }

        db()->startTrans();
        try{
            db('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 order(){
        $id = (int)input('param.id');
        $cusInfo = db('c_customerinfo')
            ->where('id', $id)
            ->field('id,customer_name,reception_id,reception_name,consulation_shop_code,shop_code,add_shop_code,customer_channel_id,customer_channel,consultation_type,brandclass')
            ->find();
        $this->assign('info',$cusInfo);
        //消费类型
        $consumptionType=controller("crm/Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);

        $erp = config('ext.app_config');

        $addr = $erp['sx_erp']['addr_child'];
        $shop_type = 1;
        //付款方式
        // 婚纱0，儿童1
        $url = trim($addr,'/').'/SX_ChildCrmApi/Sel_ZhiFuTypeSet?Token=^******^&Code=';
        $res = requestERP($url,[]);
        if($res['Code'] == 200){
            $arr = $res['Data'];
        }else{
            $arr = [
                [
                    'key'=>1,
                    'value'=> '现金',
                ],
                [
                    'key'=>2,
                    'value'=> '刷卡',
                ],
                [
                    'key'=>3,
                    'value'=> '微信',
                ],
                [
                    'key'=>4,
                    'value'=> '支付宝',
                ],
                [
                    'key'=>5,
                    'value'=> 'VIP卡',
                ],
                [
                    'key'=>6,
                    'value'=> '银行转账',
                ],
                [
                    'key'=>7,
                    'value'=> '信用卡',
                ],
                [
                    'key'=>8,
                    'value'=> '优惠券',
                ],
                [
                    'key'=>9,
                    'value'=> '会员扫码',
                ],
                [
                    'key'=>10,
                    'value'=> '微信转账',
                ],
                [
                    'key'=>11,
                    'value'=> '支付宝转账',
                ],
                [
                    'key'=>12,
                    'value'=> '京东',
                ],
                [
                    'key'=>13,
                    'value'=> '淘宝',
                ],
                [
                    'key'=>14,
                    'value'=> '天猫',
                ],
                [
                    'key'=>15,
                    'value'=> '汇款',
                ],
            ];
        }
        //款项
        $url1 = trim($addr,'/').'/SX_ChildCrmApi/Sel_KuanXiangSet?Token=^******^&KXType=1&Code=';
        $res1 = requestERP($url1,[]);
        if($res1['Code'] == 200){
            $kuan = $res1['Data'];
        }else{
            $kuan = [
                [
                    'collectitem_name'=>'定金',
                    'collectitem_belongs'=>'前期款',
                ],
                [
                    'collectitem_name'=>'前期补款',
                    'collectitem_belongs'=>'前期补款',
                ],
                [
                    'collectitem_name'=>'全款',
                    'collectitem_belongs'=>'前期款',
                ],
                [
                    'collectitem_name'=>'预约款',
                    'collectitem_belongs'=>'前期补款',
                ],
                [
                    'collectitem_name'=>'预约定金',
                    'collectitem_belongs'=>'前期补款',
                ],
                [
                    'collectitem_name'=>'预约补款',
                    'collectitem_belongs'=>'前期款',
                ],
            ];
        }

        $this->assign('kuan',$kuan);
        $this->assign('pay',$arr);
        return $this->fetch();
    }


    //转订单
    public function zhuanOrder(){
        $param = input();
        $time = date('Y-m-d H:i:s',time());
        $target_time = trim($param['target_time']);
        $pay_time = trim($param['pay_time']);
        /*if($param['target_time'] && $target_time > $time){
            $arr = array('code'=>600,'msg'=>'开单时间不能大于当前时间','data'=>$param['target_time']);
            return $arr;
        }*/
        $customerInfo = db('c_customerinfo')->where('id', $param['cid'])->find();
        $data['shop_code'] = session('shop_code');
        $data['shop_name'] = session('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)$param['cid'];
        $data['customer_name'] = $customerInfo['customer_name'];
        $data['order_fact'] = $param['order_fact'];
        $data['order_amount'] = 0;

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

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

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



        // 根据事业部id查询事业部信息
        $brandclass_id = (int)session('brandclass_id');
        $brandclassInfo= controller('index/Customer','lib')->getBrandClassInfo($brandclass_id);
        $data['brandclass_id'] = $brandclass_id;
        $data['brandclass'] = $brandclassInfo['brandclass'];
        $cash = db_config('onlinecash_'.$brandclass_id);//进店标准设定
        // 订单有效标准 （order_rule） 1：实收款；2：占比
        /*if($brandclassInfo['order_rule'] == 1){
            if($param['order_fact'] >= $brandclassInfo['proportion']){
                $cData['is_success'] = 1;
                $cData['order_day']  = $data['target_time'];

                $data['order_valid'] = 2;
                $data['order_fact'] = $param['order_fact'];
            }else{
                $cData['is_success'] = 3;
                $data['order_valid'] = 1;
                $data['earnest_money'] = $param['order_fact'];
                $data['order_fact'] = 0;
            }
        }else if($brandclassInfo['order_rule'] == 2){
            if( (($param['order_fact']) / $data['order_amount']) >= ($brandclassInfo['proportion']/100) ){
                $cData['is_success'] = 1;
                $cData['order_day']  = $data['target_time'];

                $data['order_valid'] = 2;
                $data['earnest_money'] = 0;
                $data['order_fact'] = $param['order_fact'];
                $data['two_pin_fact'] = $param['two_pin_fact'];
            }else{
                $cData['is_success'] = 3;
                $data['order_valid'] = 1;
                $data['earnest_money'] = $param['order_fact'];
                $data['order_fact'] = 0;
                $data['two_pin_fact'] = $param['two_pin_fact'];
            }
        }else{
            if( (($param['order_fact']+$param['two_pin_fact']) / $data['order_amount']) >= ($brandclassInfo['proportion']/100) ){
                $cData['is_success'] = 1;
                $cData['order_day']  = $data['target_time'];

                $data['order_valid'] = 2;
                $data['earnest_money'] = 0;
                $data['order_fact'] = $param['order_fact'];
                $data['two_pin_fact'] = $param['two_pin_fact'];
            }else{
                $cData['is_success'] = 3;
                $data['order_valid'] = 1;
                $data['earnest_money'] = $param['order_fact'];
                $data['order_fact'] = 0;
                $data['two_pin_fact'] = $param['two_pin_fact'];
            }
        }*/
        $cData['is_success'] = 1;
        $cData['order_day']  = $data['target_time'];

        $data['order_valid'] = 2;
        $data['order_fact'] = $param['order_fact'];

        // 是否安装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;
                $oid = db('c_customer_order')->insert($data);
                history_log($data, [], $data['customer_id'], session('staff_id'), session('staff_name'));
                //写入流水表
                $arr = array(
                    'order_sn' => $data['order_sn'],
                    'order_fact' => $param['order_fact'],
                    'order_type' => 1,
                    'order_valid' => $data['order_valid'],
                    'pay_time' => date('Y-m-d',time()),
                    'pay_type' => 1,
                    'create_time' => date('Y-m-d H:i:s',time())
                );

                controller('crm/Customer','lib')->insert_order_detail($arr);
                // db('c_order_detail')->insert($arr);
                // 写入客资表
                $cData['order_number'] = $order_sn;
                $cData['c_end_day'] = $time;
                $cData['last_trackday'] = $time;
                if($cash && $customerInfo['is_intostore'] != 2 && $param['order_fact'] >= intval($cash)){
                    $cData['is_intostore']  = 2;//进店进客
                    $cData['syjd_day'] = $time;
                }

                $cData['order_type']    = (int)$param['order_type'] ? (int)$param['order_type'] : 2;
                $cData['order_start_time'] = $data['target_time'] ? $data['target_time'] : $time;
                $cData['totalpay_money']   = 0;
                $cData['fact_money']       = $data['order_fact'];
                //修改客资为有效
                $info = db('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('c_customerinfo')->where('id', $data['customer_id'])->update($cData);

                if($cData['is_success']){
                    //如果是爆破活动，修改对应的爆破表数据
                    if($info['is_act'] == 2){
                        db('c_swap_customer')->where('customer_number',$info['customer_number'])->update(['is_success'=>$cData['is_success']]);
                    }
                }
                history_log($cData, $customerInfo, $data['customer_id'], session('staff_id'), session('staff_name'));
                //追踪记录
                $params['customer_id'] = $data['customer_id'];
                $params['customer_name'] = $customerInfo['customer_name'];
                $params['customer_number'] = $customerInfo['customer_number'];
                $params['sales_remark'] = '门市线下CRM转订单-'.$data['order_note'];
                $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('CSalestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$data['customer_id'],null);
                //修改追踪时间
                $time = date('Y-m-d H:i:s',time());
                if(empty($info['c_star_day'])){
                    $arr = array(
                        'c_star_day' => $time,
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }
                db('CCustomerinfo')->where('id',$data['customer_id'])->update($arr);
                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接口数据  开始  -------- //
        $erp = config('ext.app_config');
        // 店面类型 （1：婚纱；2：儿童；3：旅拍；4：艺术；5：其他）
        $s_shop_type = session('shop_type');
        if ($s_shop_type == 2) {
            $addr = $erp['sx_erp']['addr_child'];
            $shop_type = 1;
            // 婚纱0，儿童1
            $url = trim($addr,'/').'/SX_ChildCrmApi/Add_CustomerOrderinfo?Token=^******^&CustomerType='.$shop_type;
        }else{
            $addr = $erp['sx_erp']['addr'];
            $shop_type = 0;
            $url = trim($addr,'/').'/SX_CrmApi/Add_CustomerOrderinfo?Token=^******^&CustomerType='.$shop_type;
        }

        $dataErp = [];
        //付款方式
        $dataErp['paytype'] = $param['paytype'];
        //实收
        $dataErp['payment_money'] = $param['order_fact'];
        //收款款项
        $dataErp['fundname'] = $param['collectitem_name'];
        //收款款项所属
        $dataErp['suoshu'] = $param['collectitem_belongs'];
        //付款分类
        $dataErp['payclass'] = 0;
        //收款人
        $dataErp['cashierman'] = session('staff_name');
        //收款日期 yyyymmdd
        $dataErp['paymentdate'] = $pay_time ? date('Ymd',strtotime($pay_time)) : date('Ymd');
        // 地址
        $dataErp['address']          = $customerInfo['customer_address'] ? $customerInfo['customer_address'] : '';
        // 客户来源
        $dataErp['cssname']          = $customerInfo['customer_cource'] ? $customerInfo['customer_cource'] : '';
        // 客户分区
        $dataErp['area']             = $customerInfo['customer_area'] ? $customerInfo['customer_area'] : '';
        // 介绍人编号
        $dataErp['introducerid']     = $customerInfo['introducer_number'] ? $customerInfo['introducer_number'] : '';
        // 介绍人姓名
        $dataErp['introducer_name']  = $customerInfo['introducer_name'] ? $customerInfo['introducer_name'] : '';
        // 结婚日期
        $dataErp['weddingdate']      = $customerInfo['marry_day'] ? $customerInfo['marry_day'] : '';
        // 订单备注  data里有
        $dataErp['customernote']     = $data['order_note'] ? strip_tags($data['order_note']) : '';
        // 宝宝姓名 目前客资表中没有
        $dataErp['bbname']           = $customerInfo['bbname'] ? $customerInfo['bbname'] : '';
        // 宝宝昵称 目前客资表中没有
        $dataErp['bnickname']        = $customerInfo['bnickname'] ? $customerInfo['bnickname'] : '';
        // 宝宝生日（阳历）
        $dataErp['bbithdate']        = $customerInfo['baby_birthday'] ? $customerInfo['baby_birthday'] : '';
        // 宝宝生日（阳历） 目前客资表中没有
        $dataErp['liunardate']       = $customerInfo['liunardate'] ? $customerInfo['liunardate'] : '';
        // 宝宝性别 目前客资表中没有
        $dataErp['bbsex']            = $customerInfo['bbsex'] ? $customerInfo['bbsex'] : '';
        // 宝宝生肖 目前客资表中没有
        $dataErp['bzodiac']          = $customerInfo['bzodiac'] ? $customerInfo['bzodiac'] : '';
        // 联系邮箱 目前客资表中没有
        $dataErp['email']            = $customerInfo['email'] ? $customerInfo['email'] : '';
        // 客户所属店面
        // $dataErp['shop_code']        = '';
        $dataErp['shop_code']        = $customerInfo['shop_code'];
        // 客户所属店面
        $dataErp['shop_name']        = $customerInfo['shop_name'];
        // 消费类型
        $dataErp['Consumption_type'] = $customerInfo['consultation_type'] ? $customerInfo['consultation_type'] : '';
        // 套餐名称 目前客资表中没有
        $dataErp['Package_name']     = $customerInfo['Package_name'] ? $customerInfo['Package_name'] : '';
        // 订单日期
        // $dataErp['Targetdate']       = $time;
        $dataErp['Targetdate']       = date('Ymd', strtotime($time));
        // 销售门市
        $dataErp['Storeconsuitant1'] = session('staff_name');
        $dataErp['Storeconsuitant1_number'] = session('staff_number');


        // 网销门市 目前没有用 sales_satff
        $dataErp['Storeconsuitant2'] = $customerInfo['sales_staff'] ? $customerInfo['sales_staff'] : '';
        $dataErp['Storeconsuitant2_number'] = $customerInfo['sales_staff_number'] ? $customerInfo['sales_staff_number'] : '';
        // $dataErp['Storeconsuitant2'] = '';
        // 接单点
        $dataErp['Acceptor_address'] = $customerInfo['customer_orderaddress'] ? $customerInfo['customer_orderaddress'] : '';
        // 预产日期
        $dataErp['Yc_day']           = $customerInfo['ready_baby_day'] ? $customerInfo['ready_baby_day'] : '';
        // 宝宝出生地
        $dataErp['Bb_hospital']      = $customerInfo['baby_address'] ? $customerInfo['baby_address'] : '';
        // 客资系统来源
        $dataErp['Customer_from']    = 'CRM';
        // 事业部id
        $dataErp['Brandid']          = session('brandclass_id');
        // 操作店
        $dataErp['Opershop']         = session('shop_name');

        if ($customerInfo['customer_sex'] == '女') {
            $dataErp['wname']      = $customerInfo['customer_name'] ? $customerInfo['customer_name'] : '';
            $dataErp['wphone']     = $customerInfo['customer_tel'] ? $customerInfo['customer_tel'] : '';
            $dataErp['wwechat']    = $customerInfo['customer_wechat'] ? $customerInfo['customer_wechat'] : '';
            $dataErp['wqq']        = $customerInfo['customer_qq'] ? $customerInfo['customer_qq'] : '';
            $dataErp['wbirthdate'] = $customerInfo['customer_birthday'] ? $customerInfo['customer_birthday'] : '';
            $dataErp['wIdtype']    = $customerInfo['customer_idtype'] ? $customerInfo['customer_idtype'] : '';
            $dataErp['wid']        = $customerInfo['customer_idnumber'] ? $customerInfo['customer_idnumber'] : '';
            $dataErp['mname']      = $customerInfo['mate_name'] ? $customerInfo['mate_name'] : '';
            $dataErp['mphone']     = $customerInfo['mate_tel'] ? $customerInfo['mate_tel'] : '';
            $dataErp['mwechat']    = $customerInfo['mate_wechat'] ? $customerInfo['mate_wechat'] : '';
            $dataErp['mqq']        = $customerInfo['mate_qq'] ? $customerInfo['mate_qq'] : '';
            $dataErp['mbirthdate'] = $customerInfo['mate_birthday'] ? $customerInfo['mate_birthday'] : '';
            $dataErp['mIdtype']    = $customerInfo['mate_idtype'] ? $customerInfo['mate_idtype'] : '';
            $dataErp['mid']        = $customerInfo['mate_idnumber'] ? $customerInfo['mate_idnumber'] : '';
        }else if ($customerInfo['customer_sex'] == '男') {
            $dataErp['mname']      = $customerInfo['customer_name'] ? $customerInfo['customer_name'] : '';
            $dataErp['mphone']     = $customerInfo['customer_tel'] ? $customerInfo['customer_tel'] : '';
            $dataErp['mwechat']    = $customerInfo['customer_wechat'] ? $customerInfo['customer_wechat'] : '';
            $dataErp['mqq']        = $customerInfo['customer_qq'] ? $customerInfo['customer_qq'] : '';
            $dataErp['mbirthdate'] = $customerInfo['customer_birthday'] ? $customerInfo['customer_birthday'] : '';
            $dataErp['mIdtype']    = $customerInfo['customer_idtype'] ? $customerInfo['customer_idtype'] : '';
            $dataErp['mid']        = $customerInfo['customer_idnumber'] ? $customerInfo['customer_idnumber'] : '';
            $dataErp['wname']      = $customerInfo['mate_name'] ? $customerInfo['mate_name'] : '';
            $dataErp['wphone']     = $customerInfo['mate_tel'] ? $customerInfo['mate_tel'] : '';
            $dataErp['wwechat']    = $customerInfo['mate_wechat'] ? $customerInfo['mate_wechat'] : '';
            $dataErp['wqq']        = $customerInfo['mate_qq'] ? $customerInfo['mate_qq'] : '';
            $dataErp['wbirthdate'] = $customerInfo['mate_birthday'] ? $customerInfo['mate_birthday'] : '';
            $dataErp['wIdtype']    = $customerInfo['mate_idtype'] ? $customerInfo['mate_idtype'] : '';
            $dataErp['wid']        = $customerInfo['mate_idnumber'] ? $customerInfo['mate_idnumber'] : '';
        }else{
            $dataErp['wname']      = $customerInfo['customer_name'] ? $customerInfo['customer_name'] : '';
            $dataErp['wphone']     = $customerInfo['customer_tel'] ? $customerInfo['customer_tel'] : '';
            $dataErp['wwechat']    = $customerInfo['customer_wechat'] ? $customerInfo['customer_wechat'] : '';
            $dataErp['wqq']        = $customerInfo['customer_qq'] ? $customerInfo['customer_qq'] : '';
            $dataErp['wbirthdate'] = $customerInfo['customer_birthday'] ? $customerInfo['customer_birthday'] : '';
            $dataErp['wIdtype']    = $customerInfo['customer_idtype'] ? $customerInfo['customer_idtype'] : '';
            $dataErp['wid']        = $customerInfo['customer_idnumber'] ? $customerInfo['customer_idnumber'] : '';
            $dataErp['mname']      = $customerInfo['mate_name'] ? $customerInfo['mate_name'] : '';
            $dataErp['mphone']     = $customerInfo['mate_tel'] ? $customerInfo['mate_tel'] : '';
            $dataErp['mwechat']    = $customerInfo['mate_wechat'] ? $customerInfo['mate_wechat'] : '';
            $dataErp['mqq']        = $customerInfo['mate_qq'] ? $customerInfo['mate_qq'] : '';
            $dataErp['mbirthdate'] = $customerInfo['mate_birthday'] ? $customerInfo['mate_birthday'] : '';
            $dataErp['mIdtype']    = $customerInfo['mate_idtype'] ? $customerInfo['mate_idtype'] : '';
            $dataErp['mid']        = $customerInfo['mate_idnumber'] ? $customerInfo['mate_idnumber'] : '';
        }
        $dataErp = json_encode($dataErp);
        // ----------  ERP接口数据  结束  -------- //
        // $response = requestERP($url, $dataErp);
        // print_r($response['Data ']);
        // echo '1111111';
        // print_r($response['Data']);
        // exit;
        // 开启事务
        db()->startTrans();
        try {
            // 调 erp 接口
            // var_dump($url);
            $response = requestERP($url, $dataErp);
            // var_dump($response);die;
            if ($response['Code'] != '200') {

                db()->rollback();
                $arr = array('code'=>300,'msg'=>'转订单失败,ERP请求有误','error'=>json_encode($response));
                // db('c_erp_save')->insert($dataS);
            }else{
                $order_sn = $response['Data'];
                $data['order_sn'] = $order_sn;

                db('c_customer_order')->insert($data);

                history_log($data, [], $data['customer_id'], session('staff_id'), session('staff_name'));
                //写入流水表
                $arr = array(
                    'order_sn' => $data['order_sn'],
                    'order_fact' => $param['order_fact'],
                    'order_valid' => $data['order_valid'],
                    'pay_time' => date('Y-m-d',time()),
                    'order_type' => 1,
                    'pay_type' => 1,
                    'create_time' => date('Y-m-d H:i:s',time())
                );

                controller('crm/Customer','lib')->insert_order_detail($arr);
                // db('c_order_detail')->insert($arr);
                // 写入客资表
                $cData['order_number'] = $order_sn;

                if($cash && $customerInfo['is_intostore'] != 2 && $param['order_fact'] >= intval($cash)){
                    $cData['is_intostore']  = 2;//进店进客
                    $cData['syjd_day'] = $time;
                }
                $cData['order_type']    = $data['order_type'];
                $cData['order_start_time'] = $time;
                $cData['totalpay_money']   = 0;
                $cData['fact_money']       = $data['order_fact'];
                //修改客资为有效
                if($customerInfo['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('c_customerinfo')->where('id', $data['customer_id'])->update($cData);


                history_log($cData, [], $data['customer_id'], session('staff_id'), session('staff_name'));

                $info = db('CCustomerinfo')->where('id',$data['customer_id'])->find();
                if($cData['is_success']){
                    //如果是爆破活动，修改对应的爆破表数据
                    if($info['is_act'] == 2){
                        db('c_swap_customer')->where('customer_number',$info['customer_number'])->update(['is_success'=>$cData['is_success']]);
                    }
                }
                //追踪记录
                $params['customer_id'] = $data['customer_id'];
                $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'] = 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('CSalestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$data['customer_id'],null);
                //修改追踪时间
                $time = date('Y-m-d H:i:s',time());
                if(empty($info['c_start_day'])){
                    $arr = array(
                        'c_star_day' => $time,
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }
                db('CCustomerinfo')->where('id',$data['customer_id'])->update($arr);
                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;
    }

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

    // 儿童排程调度 页面 20181110
    public function childArrange(){
        if(!config('sx_erp')||!config('sx_erp_logs')){
            alert('暂不支持，请前往项目配置文件设置','/');
            exit();
        }

        // 权限
        $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','sx_erp')->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','sx_erp')
            ->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','sx_erp')
            ->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','sx_erp')
                ->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','sx_erp')
                ->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','sx_erp')
                ->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','sx_erp')->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','sx_erp')->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','sx_erp')->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','sx_erp')->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','sx_erp')->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','sx_erp')->where('id',$photo_id)->find();
            }

            //$orderInfo = db('c_customerorder','sx_erp')->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','sx_erp')->where('id',$id)->find();
        $orderId = $oldData['orderId'];
        $currentfc = $oldData['currentfc'];

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

        //查看选片表 是否有选片时间
        $spInfo = db('c_customersp','sx_erp')
            ->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','sx_erp')->where('id',$id)->delete();
            }else{
                db('c_customerphoto','sx_erp')->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'=>'删除排程失败，请稍后重试！'));
        }

    }

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