<?php
/**
 * 门市页面
 * User: sx01
 * Date: 2018/11/10
 * Time: 10:49
 */
namespace app\crm\controller;
use think\Cache;
use app\index\controller\Base;
use think\Exception;
use think\Log;
use think\Request;
use think\Session;
use PHPExcel_IOFactory;
use PHPExcel;
use Excel5;
use think\Controller;
use app\common\lib\redisQueue;
class Market extends Base{
    public function mark(){
        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')
            ->where('l.pc_shop_code',session('shop_code'))
            ->where('l.pc_time','between',[$start,$end])
            ->where($where)
            ->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')
            ->page($page)->limit($limit)
            ->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 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',intval($data['cid']))->where('code',intval($data['code']))->find();
        if(empty($res)){
            return array('code'=>102,'msg'=>'未获取到信息，请确定此核销码正确？');
        }
        $info = controller('crm/Customer','lib')->getCustomerInfo($data['cid']);
        db()->startTrans();
        try{
            db('c_customer_from')->where('cid',intval($data['cid']))->where('code',intval($data['code']))->update(['code'=>NULL]);
            $arr = [
                'is_intostore' => 2,
                'syjd_day' => date('Y-m-d H:i:s')
            ];
            db('c_customerinfo')->where('id',intval($data['cid']))->update($arr);
            $erp = config('ext.app_config');
            if(session('shop_type') == 2){
                $addr = $erp['sx_erp']['addr_child'];
                // 婚纱0，儿童1
                $url = $addr.'SX_ChildCrmApi/Set_Guest_intostore?Token=^******^&CustomerType=1&From_index='.$info['customer_number'];
            }else{
                $addr = $erp['sx_erp']['addr'];
                // 婚纱0，儿童1
                $url = $addr.'SX_CrmApi/Set_Guest_intostore?Token=^******^&CustomerType=0&From_index='.$info['customer_number'];
            }

            // 调 erp 接口
            $response = requestERP($url, []);
//            print_r($response);
//            die;
            if ($response['Code'] != 200) {
                db()->rollback();
                return array('code'=>99,'msg'=>$response['Msg'],'error'=>json_encode($response));
            }
            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
        $is_erp = is_install('sx_erp');
        if ($is_erp) {
            $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='.session('shop_code');
            $res = requestERP($url,[]);
            if($res['Code'] == 200){
                $arr = $res['Data'];
            }
            //款项
            $url1 = trim($addr,'/').'/SX_ChildCrmApi/Sel_KuanXiangSet?Token=^******^&KXType=1&Code='.session('shop_code');
            $res1 = requestERP($url1,[]);
            print_r($res1);die;
            if($res['Code'] == 200){
                $kuan = $res1['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'=> '汇款',
                ],
            ];
        }

        $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 = date('Y-m-d H:i:s', strtotime($param['target_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['two_pin_fact'] = $param['two_pin_fact'];
        // $data['two_pin_amount'] = 0;
        $data['consultation_type'] = $param['consultation_type'];
        // $data['order_source'] = $param['order_source'];
        $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 = $data['order_sn'] ? trim($data['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' => $data['order_type'] ? $data['order_type'] : 2,
                    '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())
                );

                $this->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'];
                $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['pay_type'] = $param['order_source'];
        //实收
        $dataErp['fact'] = $param['order_fact'];
        //套系
        $dataErp['amount'] = 0;
        // 地址
        $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_type' => $data['order_type'] ? $data['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())
                );

                $this->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_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;
    }
}