<?php
/**
 * 客资接口入口
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: wzy<wangzhenya@suxuantech.cn> 2018-1-3 $
 */
namespace app\index\api;

use think\Exception;

class Customer{
    /**
     * 开单，添加消费产品，收款操作
     * 开单：新增订单，一销，二销，和总额都是0
     * 添加消费产品：总额不为0，一销二销为0
     * 收款：一销二销其中一个不为0，总额都不为0
     * @param string $param 要加密的字符串
     * $param包含下列字段:
     * diff         1:开单；2：添加消费产品；3：收款
     * create_time          订单创建时间
     * m_tel                男手机号
     * w_tel                女手机号
     * order_sn             订单号
     * order_fact           一销实收
     * order_amount         一销总额
     * two_pin_fact         二销实收
     * two_pin_amount       二销总额
     * brandclass_id        事业部id
     * customer_number      customer_number
     * consultation_type    消费类型
     * shop_code
     * staff_id             操作人id
     * staff_name           操作人名字
     * @return array
     */
    public function receivables($param){
        $target_time = $param['create_time'] ? date('Y-m-d H:i:s',strtotime($param['create_time'])) : date('Y-m-d H:i:s',time());
        $param['create_time'] = date('Y-m-d H:i:s',time());
        if($param['customer_number']) $param['customer_number'] = trim($param['customer_number']);
        if($param['diff'] == 1){//开单 一销，二销，和总额都是0
            //判断客资是否存在
            $cusInfoM = controller('index/Customer','lib')->checkCustomer(['brandclass_id'=>$param['brandclass_id'],'shop_code'=>$param['shop_code'],'customer_tel'=>$param['m_tel'],'customer_number'=>$param['customer_number'],'is_in'=>1]);
            //if(empty($cusInfoW['status'])){
            $cusInfoW = controller('index/Customer','lib')->checkCustomer(['brandclass_id'=>$param['brandclass_id'],'shop_code'=>$param['shop_code'],'customer_tel'=>$param['w_tel'],'customer_number'=>$param['customer_number'],'is_in'=>1]);
            //}
            if(empty($cusInfoM) && empty($cusInfoW)){
                return array('error'=>1,'code'=>110,'msg'=>'开单失败,没有此客资，请先创建客资','data'=>'','cusInfoM'=>json_encode($cusInfoM),'cusInfow'=>json_encode($cusInfoW));
            }
            if(empty($cusInfoM) || empty($cusInfoW)){
                $cusInfo = !empty($cusInfoM)?$cusInfoM:$cusInfoW;
            }elseif($cusInfoM['id'] == $cusInfoW['id']){
                $cusInfo = $cusInfoM;
            }elseif(!empty($cusInfoM['yjd_day']) && !empty($cusInfoW['yjd_day']) && $cusInfoM['yjd_day'] > $cusInfoW['yjd_day']){
                $cusInfo = $cusInfoM;
            }elseif(!empty($cusInfoM['c_end_day']) && !empty($cusInfoW['c_end_day']) && $cusInfoM['c_end_day'] > $cusInfoW['c_end_day']){
                $cusInfo = $cusInfoM;
            }elseif(!empty($cusInfoM['jr_day']) && !empty($cusInfoW['jr_day']) && $cusInfoM['jr_day'] > $cusInfoW['jr_day']){
                $cusInfo = $cusInfoM;
            }elseif(!empty($cusInfoM['creator_day']) && !empty($cusInfoW['creator_day']) && $cusInfoM['creator_day'] > $cusInfoW['creator_day']){
                $cusInfo = $cusInfoM;
            }else{
                $cusInfo = $cusInfoW;
            }
            if ($cusInfoM['id'] != $cusInfoW['id']) {
                $contentM = [
                    'touser'       => $cusInfoM['sales_staff_id'],
                    'template_id'  => OPENTM_CT,
                    'data'         => [
                        'first'=>[
                            'value'=>'您好，您有一笔订单冲突',
                            'color'=>'#173177'
                        ],
                        'keyword1'=>[
                            'value'=>$cusInfoM['customer_name'].'('.$cusInfoM['customer_sex'].')',
                            'color'=>'#173177'
                        ],
                        'keyword2'=>[
                            'value'=>$cusInfoM['customer_tel'],
                            'color'=>'#173177'
                        ],
                        'keyword3'=>[
                            'value'=>'订单冲突',
                            'color'=>'#173177'
                        ],
                        'keyword4'=>[
                            'value'=>$param['create_time'],
                            'color'=>'#173177'
                        ],
                        'remark'=>[
                            'value'=>'请尽快查收，谢谢',
                            'color'=>'#173177'
                        ]
                    ]
                ];
                $send_data['content'] = json_encode($contentM);
                // $res = sendMsg($send_data);
                $contentW = [
                    'touser'       => $cusInfoW['sales_staff_id'],
                    'template_id'  => OPENTM_CT,
                    'data'         => [
                        'first'=>[
                            'value'=>'您好，您有一笔订单冲突',
                            'color'=>'#173177'
                        ],
                        'keyword1'=>[
                            'value'=>$cusInfoW['customer_name'].'('.$cusInfoW['customer_sex'].')',
                            'color'=>'#173177'
                        ],
                        'keyword2'=>[
                            'value'=>$cusInfoW['customer_tel'],
                            'color'=>'#173177'
                        ],
                        'keyword3'=>[
                            'value'=>'订单冲突',
                            'color'=>'#173177'
                        ],
                        'keyword4'=>[
                            'value'=>$param['create_time'],
                            'color'=>'#173177'
                        ],
                        'remark'=>[
                            'value'=>'请尽快查收，谢谢',
                            'color'=>'#173177'
                        ]
                    ]
                ];
                $send_data['content'] = json_encode($contentW);
                // $res = sendMsg($send_data);
            }
            //判断订单是否存在
            $orderInfo = $this->checkOrder(['order_sn'=>$param['order_sn']]);
            db()->startTrans();
            if($orderInfo['error'] == 1){
                $brandclassInfo = controller('index/Customer','lib')->getBrandClassInfo($param['brandclass_id']);
                $arr = array(
                    'order_sn' => $param['order_sn'],
                    'customer_id' => (int)$cusInfo['id'],
                    'customer_name' => $cusInfo['customer_name'],
                    'order_fact' => (float)$param['order_fact'],
                    'order_amount' => (float)$param['order_amount'],
                    'two_pin_fact' => (float)$param['two_pin_fact'],
                    'two_pin_amount' => (float)$param['two_pin_amount'],
                    'target_time' => $target_time,
                    'create_time' => $param['create_time'],
                    'shop_code' => $cusInfo['shop_code'],
                    'shop_name' => $cusInfo['shop_name'],
                    'consultation_type' => $param['consultation_type'],
                    'order_type' => 2,
                    'brandclass_id'=> $param['brandclass_id'],
                    'brandclass'  => $brandclassInfo['brandclass'],
                );
                $ord = controller('index/Customer','lib')->addCustomerOrder($arr);
                if($ord){
                    $cus['id'] = $cusInfo['id'];
                    $cus['totalpay_money'] = $param['order_amount']+$param['two_pin_amount'];
                    $cus['order_number'] = $param['order_sn'];
                    $cus['fact_money'] = $param['order_fact']+$param['two_pin_fact'];
                    $cus['order_start_time'] = date('Y-m-d H:i:s',time());
                    $cus['order_type'] = 2;
                    // 线下订单 
                    //if ($cusInfo['order_type'] == 2) {
                        // 进店状态
                    if($cusInfo['is_intostore'] != 2){
                        $cus['is_intostore'] = 2;
                        if($cusInfo['is_intostore'] != 5 || !$cusInfo['syjd_day']){
                            $cus['syjd_day'] = date('Y-m-d H:i:s',time());
                        }
                    }
                    //}else{
                        // $cus['order_type'] = 2;
                    // }

                    $checkParam = [
                        'brandclass_id' => $param['brandclass_id'],
                        'fact_money'    => $cus['fact_money'],
                        'order_money'   => $cus['totalpay_money'],
                        'customer_cource'   => $cusInfo['customer_cource']
                    ];
                    $result = controller('index/Customer', 'lib')->checkOrderValid($checkParam);
                    $cus['is_success'] = $result?1:3;
                    /*if($cusInfo['is_valid'] != 1){
                        $cus['is_valid'] = 1;
                        $cus['yx_day'] = date('Y-m-d H:i:s',time());
                    }*/
                    //接待人员
                    $cus['reception_id'] = $param['reception_id'];
                    $cus['reception_name'] = $param['reception_name'];
                    if(!$cusInfo['order_number'] || !config('exclude_consultation_type') || !in_array($param['consultation_type'],config('exclude_consultation_type'))){
                        //针对于客资已经有了一个订单号了，且当前传过来的消费类型被配置成排除此消费类弄的，成单不更新客资表
                        //190107SDM更改
                        //解决：当成一单为婚纱后，又送一单为全家福时，客资订单被更新成全家福了。
                        // $cus['inIf']=0;
                        $res = controller('index/Customer','lib')->updateCustomer($cus);
                    }
                    
                    if($res){
                        // 发送微信模板消息 发2次
                        // 向上一级发信息  微信
                        if(!empty($cusInfo['sales_staff_id'])){
                            $content = [
                                'touser'       => $cusInfo['sales_staff_id'],
                                'template_id'  => OPENTM_CT,
                                'data'         => [
                                    'first'=>[
                                        'value'=>'您好，您有一笔订单冲突',
                                        'color'=>'#173177'
                                    ],
                                    'keyword1'=>[
                                        'value'=>$cusInfo['customer_name'].'('.$cusInfo['customer_sex'].')',
                                        'color'=>'#173177'
                                    ],
                                    'keyword2'=>[
                                        'value'=>$cusInfo['customer_tel'],
                                        'color'=>'#173177'
                                    ],
                                    'keyword3'=>[
                                        'value'=>'订单冲突',
                                        'color'=>'#173177'
                                    ],
                                    'keyword4'=>[
                                        'value'=>$param['create_time'],
                                        'color'=>'#173177'
                                    ],
                                    'remark'=>[
                                        'value'=>'请尽快查收，谢谢',
                                        'color'=>'#173177'
                                    ]
                                ]
                            ];
                            $send_data['content'] = json_encode($content);
                            sendMsg($send_data);
                            // 发送站内弹窗消息
                            $message['send_type']      = 1;
                            $message['send_time']      = $param['create_time'];
                            $message['send_title']     = '订单提醒';
                            $message['send_msg'] = '您有一笔客资已订单，ID：'.$cusInfo['id'].'，姓名：'.$cusInfo['customer_name'].'，请确认。';
                            $message['receive_id']     = $cusInfo['sales_staff_id'];
                            $message['receive_name']   = $cusInfo['sales_staff'];
                            $message['receive_status'] = 1;
                            $message['receive_time']   = date('Y-m-d H:i:s');
                            $message['operation_type'] = 2;
                            $message['operation']      = '';
                            $message['customer_id']    = $cusInfo['id'];

                            $timeOut = db_config('fp_timeout_'.$param['shop_code']);
                            $message['time_out']       = $timeOut ? $timeOut : 60;
                            sendSystemMessage($message);
                            //如果是转介绍客资，向登记人发消息
                            if($cusInfo['customer_type']== 2){
                                $content = [
                                    'touser'       => $cusInfo['dj_staff_id'],
                                    'template_id'  => OPENTM_CT,
                                    'data'         => [
                                        'first'=>[
                                            'value'=>'您好，您有一笔客资已订单',
                                            'color'=>'#173177'
                                        ],
                                        'keyword1'=>[
                                            'value'=>$cusInfo['customer_name'].'('.$cusInfo['customer_sex'].')',
                                            'color'=>'#173177'
                                        ],
                                        'keyword2'=>[
                                            'value'=>$cusInfo['customer_tel'],
                                            'color'=>'#173177'
                                        ],
                                        'keyword3'=>[
                                            'value'=>'转介绍客资订单',
                                            'color'=>'#173177'
                                        ],
                                        'keyword4'=>[
                                            'value'=>date('Y-m-d H:i:s'),
                                            'color'=>'#173177'
                                        ],
                                        'remark'=>[
                                            'value'=>'请尽快查看，谢谢',
                                            'color'=>'#173177'
                                        ]
                                    ]
                                ];
                                $send_data['content'] = json_encode($content);
                                sendMsg($send_data);
                            }

                            // 追踪数据
                            $track['gtType'] = 5;
                            $track['customer_id'] = $cusInfo['id'];
                            $track['customer_name'] = $cusInfo['customer_name'];
                            $track['customer_number'] = $cusInfo['customer_number'];
                            $track['sales_day'] = date('Y-m-d H:i:s');
                            $track['sales_staff'] = trim($param['staff_name']);
                            $track['sales_staff_id'] = trim($param['staff_id']);
                            $track['sales_remark'] = 'ERP转订单';
                            $track['shop_code'] = trim($param['shop_code']);
                            $url = '5a005e0038270';
                            $dataT['shop_code'] = trim($param['shop_code']);
                            $tempT = sx_call($url,$dataT);
                            if ($tempT['code'] == 200) {
                                $track['shop_name'] = $tempT['data']['shop_name'];
                            }else{
                                $track['shop_name'] = NUll;
                            }
                            // 追踪记录
                            db('c_salestrackinginfo')->insert($track);
                        }
                        $remind = getRemind($param['brandclass_id']);
                        if($cusInfo['dj_staff_id'] && in_array('tan',$remind['jd']['send_method']) && in_array('dj',$remind['jd']['send_receive'])){
                            $messageD['send_type']      = 1;
                            $messageD['send_time']      = date('Y-m-d H:i:s');
                            $messageD['send_title']     = '订单提醒';
                            $messageD['send_msg']       = '您有一笔客资已成单，请确认。';
                            $messageD['receive_id']     = $cusInfo['dj_staff_id'];
                            $messageD['receive_name']   = $cusInfo['dj_staff'];
                            $messageD['receive_status'] = 1;
                            $messageD['receive_time']   = date('Y-m-d H:i:s');
                            $messageD['operation_type'] = 2;
                            $messageD['operation']      = '';
                            $timeOut = db_config('fp_timeout_'.$cusInfo['shop_code']);
                            $messageD['time_out']       = $timeOut ? $timeOut : 60;

                            $resM = sendSystemMessage($messageD);
                        }
                        if($cusInfo['sales_staff_id'] && in_array('tan',$remind['order']['send_method']) && in_array('sales',$remind['order']['send_receive'])){
                            $messageD['send_type']      = 1;
                            $messageD['send_time']      = date('Y-m-d H:i:s');
                            $messageD['send_title']     = '订单提醒';
                            $messageD['send_msg']       = '您有一笔客资已成单，请确认。';
                            $messageD['receive_id']     = $cusInfo['sales_staff_id'];
                            $messageD['receive_name']   = $cusInfo['sales_staff'];
                            $messageD['receive_status'] = 1;
                            $messageD['receive_time']   = date('Y-m-d H:i:s');
                            $messageD['operation_type'] = 2;
                            $messageD['operation']      = '';
                            $timeOut = db_config('fp_timeout_'.$cusInfo['shop_code']);
                            $messageD['time_out']       = $timeOut ? $timeOut : 60;

                            $resM = sendSystemMessage($messageD);
                        }
                        if($cusInfo['dj_staff_id'] && in_array('tui',$remind['order']['send_method']) && in_array('dj',$remind['order']['send_receive'])){
                            $content = [
                                'touser'       => $cusInfo['dj_staff_id'],
                                'template_id'  => OPENTM_YX,
                                'data'         => [
                                    'first'=>[
                                        'value'=> '您有一笔客资已订单',
                                        'color'=> '#173177'
                                    ],
                                    'keyword1'=>[
                                        'value'=> $cusInfo['customer_name'],
                                        'color'=> '#173177'
                                    ],
                                    'keyword2'=>[
                                        'value'=> $cusInfo['sales_staff'],
                                        'color'=> '#173177'
                                    ],
                                    'keyword3'=>[
                                        'value'=> date('Y-m-d H:i:s'),
                                        'color'=> '#173177'
                                    ],
                                    'remark'=>[
                                        'value'=> 'ID:'.$cusInfo['id'].',订单号：'.$cusInfo['order_number'].',手机：'.$cusInfo['customer_tel'].',请尽快查看，谢谢',
                                        'color'=> '#173177'
                                    ],
                                ],
                            ];
                            $send_data['content'] = json_encode($content);
                            $res = sendMsg($send_data);
                        }
                        if($cusInfo['sales_staff_id'] && in_array('tui',$remind['order']['send_method']) && in_array('sales',$remind['order']['send_receive'])){
                            $content = [
                                'touser'       => $cusInfo['sales_staff_id'],
                                'template_id'  => OPENTM_YX,
                                'data'         => [
                                    'first'=>[
                                        'value'=> '您有一笔客资已订单',
                                        'color'=> '#173177'
                                    ],
                                    'keyword1'=>[
                                        'value'=> $cusInfo['customer_name'],
                                        'color'=> '#173177'
                                    ],
                                    'keyword2'=>[
                                        'value'=> $cusInfo['sales_staff'],
                                        'color'=> '#173177'
                                    ],
                                    'keyword3'=>[
                                        'value'=> date('Y-m-d H:i:s'),
                                        'color'=> '#173177'
                                    ],
                                    'remark'=>[
                                        'value'=> 'ID:'.$cusInfo['id'].',订单号：'.$cusInfo['order_number'].',手机：'.$cusInfo['customer_tel'].',请尽快查看，谢谢',
                                        'color'=> '#173177'
                                    ],
                                ],
                            ];
                            $send_data['content'] = json_encode($content);
                            $res = sendMsg($send_data);
                        }
                        db()->commit();
                        return $param;
                    }else{
                        db()->rollback();
                        return array('error'=>1,'code'=>1212,'msg'=>'开单失败,修改客资表订单信息失败','data'=>json_encode($cusInfo).'=='.json_encode($cus).'==sql=>'.db()->getLastSql().'==cusInfoM=>'.json_encode($cusInfoM).'==cusInfow=>'.json_encode($cusInfoW));
                    }
                }else{
                    db()->rollback();
                    return array('error'=>1,'code'=>110,'msg'=>'开单失败','data'=>'');
                }
            }else{
                return array('error'=>1,'code'=>210,'msg'=>'开单失败,订单已存在','data'=>'');
            }
        }elseif($param['diff'] == 2){//添加消费产品 总额不为0，一销二销为0
            $orderInfo = $this->checkOrder(['order_sn'=>$param['order_sn']]);
            if($orderInfo['error'] == 1){
                return array('code'=>201,'msg'=>'添加消费产品时,订单表查询失败','data'=>'404');
            }
            $order_valid = false;
            if ($orderInfo['order_valid']==1 && (int)$param['order_amount']) {
                $checkParam = [
                    'brandclass_id' => $param['brandclass_id'],
                    'fact_money'    => $orderInfo['earnest_money']+$orderInfo['order_fact']+$param['order_fact'],
                    'order_money'   => (int)$param['order_amount'],
                ];
                $order_valid = controller('index/Customer', 'lib')->checkOrderValid($checkParam);
            }
            //修改订单表信息
            $arr = array(
                'order_sn'       => $orderInfo['order_sn'],
                'customer_id'    => $orderInfo['customer_id'],
                'customer_name'  => $orderInfo['customer_name'],
                // 'earnest_money'  => 0,
                // 'order_fact'     => 0,
                'order_amount'   => $param['order_amount'],
                // 'two_pin_fact'   => 0,
                'two_pin_amount' => $param['two_pin_amount'],
                'update_time'    => date('Y-m-d H:i:s',strtotime($param['create_time'])),
                'shop_code'      => $orderInfo['shop_code'],
                'shop_name'      => $orderInfo['shop_name'],
            );
            // 如果订单添加套系后有效
            if ($order_valid) {
                $arr['order_valid'] = 2;
                $arr['valid_time']  = date('Y-m-d H:i:s');
            }
            
            db()->startTrans();
            try{
                $ord = controller('index/Customer','lib')->updateCustomerOrder($arr);
                //修改客资表套系金额
                $customerData = [
                    'id'=>$orderInfo['customer_id'],
                    'totalpay_money'=>$param['two_pin_amount']+$param['order_amount'],
                    'order_number'=> $orderInfo['order_sn'],
                ];
                $cusInfo = db('c_customerinfo')->where('id',$orderInfo['customer_id'])->field('is_intostore,is_valid,order_type,order_start_time,order_day,syjd_day,order_number')->find();
                // 线下订单 
                if ($cusInfo['order_type'] == 2) {
                    // 进店状态
                    if($cusInfo['is_intostore'] != 2){
                        $customerData['is_intostore'] = 2;
                        if($cusInfo['is_intostore'] != 5 || !$cusInfo['syjd_day'])
                        $customerData['syjd_day'] = $cusInfo['order_start_time']?$cusInfo['order_start_time']:date('Y-m-d H:i:s',time());
                    }
                }
                
                if($cusInfo['is_valid'] != 1){
                    $customerData['is_valid'] = 1;
                    $customerData['yx_day'] = $cusInfo['order_start_time']?$cusInfo['order_start_time']:date('Y-m-d H:i:s',time());
                }
                if($cusInfo['is_success'] == 2){
                    $customerData['is_success'] = 3;
                    $customerData['order_start_time_day'] = $cusInfo['order_start_time']?$cusInfo['order_start_time']:date('Y-m-d H:i:s',time());
                }

                // 如果订单添加套系后有效
                if ($order_valid) {
                    $customerData['is_success'] = 1;
                    if (!$cusInfo['order_day']) {
                        $customerData['order_day']  = date('Y-m-d H:i:s',time());
                    }
                    $table = isTableExist('c_customer_intostore');
                    // 更新进客表
                    if ($orderInfo['into_id'] && $table) {
                        db('c_customer_intostore')->where('id',$orderInfo['into_id'])->update(array('is_success' => 1));
                    }
                }
                if(empty($cusInfo['order_number']) || $cusInfo['order_number'] == $orderInfo['order_sn']){
                    $res = controller('index/Customer','lib')->updateCustomer($customerData);
                }


                if($res === false){
                    db()->rollback();
                    return array('error'=>1,'code'=>140,'msg'=>'添加消费产品时,客资表修改失败','data'=>'');
                }else{
                    db()->commit();
                    return $arr;
                }
            }catch(\Exception $e){
                db()->rollback();
                return array('error'=>1,'code'=>150,'msg'=>'添加消费产品时订单表更新失败','data'=>''.db()->getLastSql());
            }
        }elseif($param['diff'] == 3){
            $orderInfo = $this->checkOrder(['order_sn'=>$param['order_sn']]);
            if($orderInfo['error'] == 1){
                return array('code'=>202,'msg'=>'付款时,订单表查询失败','data'=>'404');
            }
            $table = isTableExist('c_customer_intostore');

            $cInfo = db('c_customerinfo')->where('id',$orderInfo['customer_id'])->field('id,totalpay_money,fact_money,is_success,order_number,syjd_day')->find();
            // 无效订单
            if($orderInfo['order_valid'] == 1){
                // 判断订单是否有效
                $checkParam = [
                    'brandclass_id' => $param['brandclass_id'],
                    'fact_money'    => $orderInfo['order_fact']+$param['order_fact'],
                    'order_money'   => $param['order_amount'],
                ];
                // $result = controller('index/Customer', 'lib')->checkOrderValid($checkParam);
                $result = getPercent($checkParam['fact_money'],$checkParam['order_money'],$param['brandclass_id'],'order');
                db()->startTrans();
                try {
                    // 有效
                    if ($result === true) {
                        // 更新订单表
                        $orderData = [
                            'order_sn' => $param['order_sn'],
                            'order_valid' => 2,
                            'earnest_money'=> 0,
                            'order_fact'=>$orderInfo['order_fact']+$param['order_fact'],
                            'order_amount'=>$param['order_amount'],
                            'two_pin_fact'=>$param['two_pin_fact']+$orderInfo['two_pin_fact'],
                            'two_pin_amount'=>$param['two_pin_amount'],
                            'update_time'=>date('Y-m-d H:i:s',strtotime($param['create_time'])),
                            'valid_time'=>date('Y-m-d H:i:s'),
                        ];

                        $oRes = controller('index/Customer','lib')->updateCustomerOrder($orderData);
                        // 更新进客表
                        if ($orderInfo['into_id'] && $table) {
                            db('c_customer_intostore')->where('id',$orderInfo['into_id'])->update(array('is_success' => 1));
                        }
                        action_log($param,$orderInfo,$orderInfo['customer_id'],session('staff_id'),session('staff_name'));
                        //订单流水表
                        $order = array(
                            'order_sn' => $param['order_sn'],
                            'pay_time' => date('Y-m-d',strtotime($param['create_time'])),
                            'order_valid' => 2,
                            'order_type' => $orderInfo['order_type'],
                            'order_fact' => $param['order_fact'],
                            'two_pin_fact' => $param['two_pin_fact'],
                            'create_time' => date('Y-m-d H:i:s',time())
                        );
                        // $odRes = db('c_order_detail')->insert($order);
                        controller('crm/Customer','lib')->insert_order_detail($order);
                        // 修改客资表
                        $customerData = [
                            'id'=>$orderInfo['customer_id'],
                            'totalpay_money'=>$param['order_amount']+$param['two_pin_amount'],
                            'is_success'=>1,
                            'order_number'=>$param['order_sn'],
                            'order_day' =>date('Y-m-d H:i:s'),
                            'fact_money'=>$cInfo['fact_money']+$param['order_fact']+$param['two_pin_fact'],
                        ];

                        $cusInfo = db('c_customerinfo')->where('id',$orderInfo['customer_id'])->field('is_intostore,is_valid,order_type,order_start_time,syjd_day,order_number')->find();

                        // 线下订单
                        if ($cusInfo['order_type'] == 2) {
                            if($cusInfo['is_intostore'] != 2){
                                $customerData['is_intostore'] = 2;
                                if($cusInfo['is_intostore'] != 5 || !$cusInfo['syjd_day'])
                                $customerData['syjd_day'] = $cusInfo['order_start_time']?$cusInfo['order_start_time']:date('Y-m-d H:i:s',time());
                            }
                        }
                        // 线上订单
                        else if ($cusInfo['order_type'] == 1) {
                            // 不是进店进客状态
                            if($cusInfo['is_intostore'] != 2){
                                // 设定过网付订单达成金额  进店限制
                                $percent = getPercent($orderData['order_fact'],$orderData['order_amount'],$param['brandclass_id'],'into');
                                if($percent){
                                    $customerData['is_intostore'] = 2;
                                    $customerData['syjd_day']  = $customerData['syjd_day'] ? $customerData['syjd_day'] : date('Y-m-d H:i:s',time());
                                }
                            }
                        }
                        
                        if($cusInfo['is_valid'] != 1){
                            $customerData['is_valid'] = 1;
                            $customerData['yx_day'] = $cusInfo['order_start_time']? $cusInfo['order_start_time']:date('Y-m-d H:i:s',time());
                        }
                        if(empty($cusInfo['order_number']) || $cusInfo['order_number'] == $param['order_sn']){
                            $cRes = controller('index/Customer','lib')->updateCustomer($customerData);
                        }
                    }else {
                        // 更新订单表
                        $orderData = [
                            'order_sn' => $param['order_sn'],
                            'order_valid' => 1,
                            'earnest_money'=>0,
                            'order_fact'=>$orderInfo['order_fact']+$param['order_fact'],
                            'order_amount'=>$param['order_amount'],
                            'two_pin_fact'=>$param['two_pin_fact']+$orderInfo['two_pin_fact'],
                            'two_pin_amount'=>$param['two_pin_amount'],
                            'update_time'=>date('Y-m-d H:i:s',strtotime($param['create_time'])),
                        ];

                        $oRes = controller('index/Customer','lib')->updateCustomerOrder($orderData);
                        // 更新进客表
                        if ($orderInfo['into_id'] && $table) {
                            db('c_customer_intostore')->where('id',$orderInfo['into_id'])->update(array('is_success' => 3));
                        }
                        action_log($param,$orderInfo,$orderInfo['customer_id'],session('staff_id'),session('staff_name'));
                        //订单流水表
                        $order = array(
                            'order_sn' => $param['order_sn'],
                            'pay_time' => date('Y-m-d',strtotime($param['create_time'])),
                            'order_valid' => 1,
                            'order_type' => $orderInfo['order_type'],
                            'order_fact' => $param['order_fact'],
                            'two_pin_fact' => $param['two_pin_fact'],
                            'create_time' => date('Y-m-d H:i:s',time())
                        );
                        // db('c_order_detail')->insert($order);
                        controller('crm/Customer','lib')->insert_order_detail($order);
                        // 修改客资表
                        $customerData = [
                            'id'=>$orderInfo['customer_id'],
                            'totalpay_money'=>$param['order_amount']+$param['two_pin_amount'],

                            //'is_success'=>3,
                            'order_number'=>$param['order_sn'],
                            'fact_money'=>$cInfo['fact_money']+$param['order_fact']+$param['two_pin_fact'],
                        ];
                        $cusInfo = db('c_customerinfo')->where('id',$orderInfo['customer_id'])->field('is_intostore,is_success,is_valid,order_type,brandclass_id,order_start_time,syjd_day,order_number')->find();
                        $one_order = db_config('one_customer_more_order');//同一客资允许多次订单,有过成交，就一直成交
                        $valid = checkValidOrder($orderInfo['customer_id'],$orderInfo['order_sn']);
                        if($one_order != 2 && $valid){
                            $cData['is_success'] = 1;
                        }else{
                            $customerData['is_success'] = 3;
                            // $customerData['order_start_time'] = $orderInfo['target_time'] ? $orderInfo['target_time'] : date('Y-m-d H:i:s',time());
                        }
                        // 线下订单 
                        if ($cusInfo['order_type'] == 2) {
                            // 进店状态
                            if($cusInfo['is_intostore'] != 2){
                                $customerData['is_intostore'] = 2;
                                if($cusInfo['is_intostore'] != 5 || !$cusInfo['syjd_day'])
                                $customerData['syjd_day'] = $cusInfo['order_start_time']?$cusInfo['order_start_time']:date('Y-m-d H:i:s',time());
                            }
                        }
                        // 线上订单
                        else if ($cusInfo['order_type'] == 1) {
                            // 不是进店进客状态
                            if($cusInfo['is_intostore'] != 2){
                                // 设定过网付订单达成金额  进店限制
                                $percent = getPercent($orderData['order_fact'],$orderData['order_amount'],$param['brandclass_id'],'into');
                                if($percent){
                                    $customerData['is_intostore'] = 2;
                                    $customerData['syjd_day']  = $customerData['syjd_day'] ? $customerData['syjd_day'] : date('Y-m-d H:i:s',time());
                                }
                            }
                        }
                        
                        if($cusInfo['is_valid'] != 1){
                            $customerData['is_valid'] = 1;
                            $customerData['yx_day'] = $cusInfo['order_start_time']? $cusInfo['order_start_time']:date('Y-m-d H:i:s',time());
                        }
                        if(empty($cusInfo['order_number']) || $cusInfo['order_number'] == $param['order_sn']){
                            $cRes = controller('index/Customer','lib')->updateCustomer($customerData);
                        }
                    }
                    db()->commit();
                } catch (Exception $e) {
                    db()->rollback();
                    return array('error'=>1,'code'=>102,'msg' =>'有效订单收款失败','data'=>$e->getMessage());
                }
            }
            // 有效订单
            else{
                db()->startTrans();
                // 判断订单是否有效
                $checkParam = [
                    'brandclass_id' => $param['brandclass_id'],
                    'fact_money'    => $orderInfo['order_fact']+$param['order_fact'],
                    'order_money'   => $param['order_amount'],
                ];
                // $result = controller('index/Customer', 'lib')->checkOrderValid($checkParam);
                $result = getPercent($checkParam['fact_money'],$checkParam['order_money'],$param['brandclass_id'],'order');
                try {
                    if($result === false){
                        // 更新订单表
                        $orderData = [
                            'order_sn' => $param['order_sn'],
                            'order_valid' => 1,
                            'order_fact'=>$orderInfo['order_fact']+$param['order_fact'],
                            'earnest_money'=>0,
                            'order_amount'=>$param['order_amount'],
                            'two_pin_fact'=>$param['two_pin_fact']+$orderInfo['two_pin_fact'],
                            'two_pin_amount'=>$param['two_pin_amount'],
                            'update_time'=>date('Y-m-d H:i:s',strtotime($param['create_time'])),
                            'valid_time' => null,
                        ];
                        // 更新进客表
                        if ($orderInfo['into_id'] && $table) {
                            db('c_customer_intostore')->where('id',$orderInfo['into_id'])->update(array('is_success' => 3));
                        }
                        //订单流水表
                        $order = array(
                            'order_sn' => $param['order_sn'],
                            'pay_time' => date('Y-m-d',strtotime($param['create_time'])),
                            'order_valid' => 1,
                            'order_type' => $orderInfo['order_type'],
                            'order_fact' => $param['order_fact'],
                            'two_pin_fact' => $param['two_pin_fact'],
                            'create_time' => date('Y-m-d H:i:s',time())
                        );
                        // db('c_order_detail')->insert($order);
                        //修改客资表
                        $customerData = [
                            'id'=>$orderInfo['customer_id'],
                            'totalpay_money'=>$param['order_amount']+$param['two_pin_amount'],
                            //'is_success'=>3,
                            'order_day' =>null,
                            'fact_money'=>$cInfo['fact_money']+$param['order_fact']+$param['two_pin_fact'],
                            'order_number'=>$param['order_sn'],
                        ];
                        $one_order = db_config('one_customer_more_order');//同一客资允许多次订单,有过成交，就一直成交
                        // 0314
                        $valid = checkValidOrder($orderInfo['customer_id'],$orderInfo['order_sn']);
                        if($one_order != 2 && $valid){
                            $customerData['is_success'] = 1;
                        }else{
                            $customerData['is_success'] = 3;
                            // $customerData['order_start_time'] =date('Y-m-d H:i:s',time());
                        }
                    }else{
                        // 更新订单表
                        $orderData = [
                            'order_sn' => $param['order_sn'],
                            'order_fact'=>$orderInfo['earnest_money']+$param['order_fact']+$orderInfo['order_fact'],
                            'order_amount'=>$param['order_amount'],
                            'two_pin_fact'=>$param['two_pin_fact']+$orderInfo['two_pin_fact'],
                            'two_pin_amount'=>$param['two_pin_amount'],
                            'update_time'=>date('Y-m-d H:i:s',strtotime($param['create_time'])),
                        ];
                        // 更新进客表
                        if ($orderInfo['into_id'] && $table) {
                            db('c_customer_intostore')->where('id',$orderInfo['into_id'])->update(array('is_success' => 1));
                        }
                        //订单流水表
                        $order = array(
                            'order_sn' => $param['order_sn'],
                            'pay_time' => date('Y-m-d',strtotime($param['create_time'])),
                            'order_valid' => 2,
                            'order_type' => $orderInfo['order_type'],
                            'order_fact' => $param['order_fact'],
                            'two_pin_fact' => $param['two_pin_fact'],
                            'create_time' => date('Y-m-d H:i:s',time())
                        );
                        // db('c_order_detail')->insert($order);
                        //修改客资表
                        $customerData = [
                            'id'=>$orderInfo['customer_id'],
                            'totalpay_money'=>$param['order_amount']+$param['two_pin_amount'],
                            'is_success'=>1,
                            // 'order_day' => date('Y-m-d H:i:s',time()),
                            'fact_money'=>$cInfo['fact_money']+$param['order_fact']+$param['two_pin_fact'],
                            'order_number'=>$param['order_sn'],
                        ];
                    }

                    $cusInfo = db('c_customerinfo')->where('id',$orderInfo['customer_id'])->field('is_intostore,is_valid,order_type,order_start_time,syjd_day,order_number')->find();
                    
                    // 线下订单
                    if ($cusInfo['order_type'] == 2) {
                        if($cusInfo['is_intostore'] != 2){
                            $customerData['is_intostore'] = 2;
                            if($cusInfo['is_intostore'] != 5 || !$cusInfo['syjd_day'])
                            $customerData['syjd_day'] = $cusInfo['order_start_time']?$cusInfo['order_start_time']:date('Y-m-d H:i:s',time());
                        }
                    }
                    // 线上订单
                    else if ($cusInfo['order_type'] == 1) {
                        // 不是进店进客状态
                        if($cusInfo['is_intostore'] != 2){
                            // 设定过网付订单达成金额  进店限制
                            if($cusInfo['is_intostore'] != 2){
                                $percent = getPercent($orderData['order_fact'],$orderData['order_amount'],$param['brandclass_id'],'into');
                                if($percent){
                                    $customerData['is_intostore'] = 2;
                                    $customerData['syjd_day']  = $customerData['syjd_day'] ? $customerData['syjd_day'] : date('Y-m-d H:i:s',time());
                                }
                            }
                        }
                    }

                    if($cusInfo['is_valid'] != 1){
                        $customerData['is_valid'] = 1;
                        $customerData['yx_day'] = $cusInfo['order_start_time']?$cusInfo['order_start_time']:date('Y-m-d H:i:s',time());
                    }
                    controller('index/Customer','lib')->updateCustomerOrder($orderData);

                    action_log($param,$orderInfo,$orderInfo['customer_id'],session('staff_id'),session('staff_name'));
                    controller('crm/Customer','lib')->insert_order_detail($order);
                    if(empty($cusInfo['order_number']) || $cusInfo['order_number'] == $param['order_sn']){
                        $cRes = controller('index/Customer','lib')->updateCustomer($customerData);
                    }
                    db()->commit();
                } catch (Exception $e) {
                    db()->rollback();
                    return array('error'=>1,'code'=>103,'msg' =>'有效订单收款失败','data'=>$e->getMessage());
                }
            }
            // $res = chackCustomerOrder(['customer_id'=>$orderInfo['customer_id']]);
            // 订单后 调一下erp的数据库 重新核对一下订单信息
            $cParam['order_sn'] = trim($param['order_sn']);
            checkCustomerOrder($cParam);
            return $orderData;
        }else{
            return array('error'=>1,'code'=>400,'msg'=>'参数有误','data'=>'');
        }
    }
    /**
     * 单独提供接口，供ERP进客处进行调用，如果此客资在CRM内找不到，则返回404，但并不自动创建客资
     * 针对于将老客资进行回门操作时，验证客资是否可以回门
     * 验证规则如果别人家不一样，可以在checkCustomer里进行定制规则
     * 
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function preCheckCustomer($param){
        //
        $customer_name = $param['customer_name'];
        $param['customer_number'] = $param['from_index'];
        if($param['customer_tel']){
            if(!check_tel($param['customer_tel'])){
                return array('error'=>1,'code'=>300,'msg'=>'手机格式错误','data'=>[]);
            }
        }
        if($param['mate_tel']){
            if(!check_tel($param['mate_tel'])){
                return array('error'=>1,'code'=>300,'msg'=>'手机格式错误','data'=>[]);
            }
        }
        $return = controller("Customer","lib")->checkCustomer($param);
        if($return){
            $returnData['c_from'] = $return['c_from'];
            $returnData['customer_number'] = $return['customer_number'];
        }else{
            $returnData['error'] = 1;
            $returnData['code'] = 404;
            $returnData['msg'] = '没有找到此客资，或此客资状态不正确';
        }
        return $returnData;
    }
	/**
	 * 检查该客资是否存在于客资系统中
	 * 
	 * @param  brandclass_id         事业部id
	 * @param  shop_code             
     * @param  staff_id              操作人id
     * @param  customer_number       客户编号
     * @param  customer_name         客户姓名
	 * @param  customer_tel          客户手机
	 * @param  customer_wechat       客户微信
	 * @param  customer_qq           客户QQ
     * @param  customer_sex          客户性别
     * @param  customer_birthday     客户生日
     * @param  consultation_type_id  消费类型id
     * @param  consultation_type     消费类型
     * @param  customer_area_id      客户分区id
     * @param  customer_area         客户分区
     * @param  customer_cource_id    客户来源id
     * @param  customer_cource       客户来源
     * @param  customer_intention_id 客户意向id
     * @param  customer_intention    客户意向
     * @param  customer_orderaddress 接单点
     * @param  customer_address      客户地址
     * @param  yp_day                预拍日期
     * @param  marry_day             结婚日期
     * @param  mate_name             配偶姓名
     * @param  mate_tel              配偶手机
     * @param  mate_wechat           配偶微信
     * @param  mate_qq               配偶QQ
     * @param  mate_sex              配偶性别
     * @param  mate_birthday         配偶生日
     * @param  ready_baby_day        预产期
     * @param  baby_birthday         宝宝生日
     * @param  baby_address          宝宝出生地
     * @param  customer_remark       客户备注
     *
	 * @return array
	 * @author lilong<lilong@suxuantech.cn>
	 */
	public function checkCustomer($param){
        $customer_name = $param['customer_name'];
        $param['customer_number'] = $param['from_index'];
        if($param['customer_tel']){
            if(!check_tel($param['customer_tel'])){
                return array('error'=>1,'code'=>300,'msg'=>'手机格式错误','data'=>[]);
            }
        }
		$return = controller("Customer","lib")->checkCustomer($param);
		// 客资不存在，录入到客资里
        $date = date('Y-m-d H:i:s');
        if (!$return) {
            $staffInfo = getStaffInfoById(intval($param['staff_id']));
            // print_r($staffInfo);
            // exit;
            $data = [
                'brandclass_id'        => (int)$param['brandclass_id'],
                'brandclass'           => $staffInfo['brandclass'],
                'shop_code'            => $staffInfo['shop_code'],
                'shop_name'            => $staffInfo['shop_name'],
                'add_shop_code'        => $staffInfo['shop_code'],
                'add_shop_name'        => $staffInfo['shop_name'],
                'customer_name'        => $customer_name,
                'customer_number'      => time().generate_code(),
                'customer_tel'         => $param['customer_tel'],
                'customer_wechat'      => $param['customer_wechat'],
                'customer_qq'          => $param['customer_qq'],
                'customer_sex'         => $param['customer_sex'],
                'consultation_type_id' => (int)$param['consultation_type_id'],
                'consultation_type'    => $param['consultation_type'],
                'customer_area_id'     => (int)$param['customer_area_id'],
                'customer_area'        => $param['customer_area'],
                'customer_birthday'    => $param['customer_birthday'] ? date('Y-m-d H:i:s', strtotime($param['customer_birthday'])) : NULL,
                'customer_cource_id'   => $param['customer_cource'] ? (int)$param['customer_cource_id'] : 1,
                'customer_cource'      => $param['customer_cource'] ? $param['customer_cource'] : '自然入客',
                'customer_intention_id'=> (int)$param['customer_intention_id'],
                'customer_intention'   => $param['customer_intention'],
                'customer_orderaddress'=> $param['customer_orderaddress'],
                'customer_address'     => $param['customer_address'],
                'yp_day'               => $param['yp_day'] ? date('Y-m-d H:i:s', strtotime($param['yp_day'])) : NULL,
                'marry_day'            => $param['marry_day'] ? date('Y-m-d H:i:s', strtotime($param['marry_day'])) : NULL,
                'mate_name'            => $param['mate_name'],
                'mate_tel'             => $param['mate_tel'],
                'mate_wechat'          => $param['mate_wechat'],
                'mate_qq'              => $param['mate_qq'],
                'mate_sex'             => $param['mate_sex'],
                'mate_birthday'        => $param['mate_birthday']?date('Y-m-d H:i:s',strtotime($param['mate_birthday'])):NULL,
                'customer_remark'      => $param['customer_remark'],
                'ready_baby_day'       => $param['ready_baby_day']?date('Y-m-d H:i:s',strtotime($param['ready_baby_day'])):NULL,
                'baby_birthday'        => $param['baby_birthday']?date('Y-m-d H:i:s',strtotime($param['baby_birthday'])):NULL,
                'baby_address'         => $param['baby_address'] ? $param['baby_address'] : '',
                'c_from'                 => 2,
                'creator_day'          => $date,
                'create_time'          => $date,
                'dj_day'               => $date,
                'dj_staff'             => $staffInfo['staffname'],
                'dj_staff_id'          => $param['staff_id'],
                'dj_staff_number'      => $staffInfo['staffnumber'],
                'tel_staff_id'         => $param['staff_id'],
                'tel_staff'            => $staffInfo['staffname'],
                'tel_time'             => $date,
                'is_first_tel'         => 1,
                'wechat_staff_id'      => $param['customer_wechat'] ? $param['staff_id'] : '',
                'wechat_staff'         => $param['customer_wechat'] ? $staffInfo['staffname'] : '',
                'wechat_time'          => $param['customer_wechat'] ? $date : NULL,
                'is_first_wechat'      => $param['customer_wechat'] ? 1 : '',
                'qq_staff_id'          => $param['customer_qq'] ? $param['staff_id'] : '',
                'qq_staff'             => $param['customer_qq'] ? $staffInfo['staffname'] : '',
                'qq_time'              => $param['customer_qq'] ? $date : NULL,
                'is_first_qq'          => $param['customer_qq'] ? 1 : '',
                'is_valid'             => 1,
                'yx_day'               => $date,
                'is_intostore'         => 2,
                'syjd_day'             => $date,
            ];
            // print_r($param);die;
            db()->startTrans();
            try {
                $res = db('c_customerinfo')->insertGetId($data);
                $contact = [];
                if($data['customer_tel']){
                    array_push($contact,$data['customer_tel']);
                }
                if($data['customer_wechat']){
                    array_push($contact,$data['customer_wechat']);
                }
                if($data['customer_qq']){
                    array_push($contact,$data['customer_qq']);
                }
                $contact=array_unique($contact);
                $contactList = [];
                foreach($contact as $k => $v){
                    $contactList[$k]['c_id']=$res;
                    $contactList[$k]['contact']=$v;
                    $contactList[$k]['brandclass']=$data['brandclass'];
                }
                db('c_customer_contact')->insertAll($contactList);
                $data['id']     = $res;
                $data['status'] = 1;
                $return = $data;
                db()->commit();
            } catch (Exception $e) {
                $return = array('error'=>1,'code'=>201,'msg'=>'操作失败，请重试！');
                db()->rollback();
            }
        }else{
            $arr = [];
            if($return['is_valid'] != 1){
                $arr['is_valid'] = 1;
                $arr['yx_day'] = $date;
            }
            if($return['is_intostore'] != 2){
                $arr['is_intostore'] = 2;
                $arr['syjd_day'] = $return['syjd_day']?$return['syjd_day']:$date;
            }
            if(!empty($arr)){
                db()->startTrans();
                try {
                    db('c_customerinfo')->where('id',$return['id'])->update($arr);
                    //记追踪记录
                    $params['gtType'] = 4;
                    $params['customer_id'] = $return['id'];
                    $params['customer_name'] = $return['customer_name'];
                    $params['customer_number'] = $return['customer_number'];
                    if($param['reBack'] == 2){
                        $params['sales_remark'] = 'ERP操作：回门';
                    }else{
                        $params['sales_remark'] = 'ERP操作：进店';
                    }
                    $staff = getStaffInfoById($param['staff_id']);
                    $params['sales_day'] = date('Y-m-d H:i:s',time());
                    $params['sales_staff'] = $staff['staffname'];
                    $params['sales_staff_id'] = $param['staff_id'];
                    $params['sales_staff_number'] = $staff['staffnumber'];
                    if($param['shop_code'] == $staff['shop_code']){
                        $params['shop_name'] = $staff['shop_name'];
                    }else{
                        $shop = controller('crm/Customer','lib')->get_shop(['shop_code'=>$param['shop_code']]);
                        $params['shop_name'] = $shop[0]['shop_name'];
                    }
                    $params['shop_code'] = $param['shop_code'];
                    db('CSalestrackinginfo')->insert($params);
                    cache('getCustomerTrackInfos'.$return['id'],null);
                    getSalesTracking($return['id']);//获取最近三次追踪记录同步更新到客资表
                    db()->commit();
                } catch (Exception $e) {
                    $return = array('error'=>1,'code'=>202,'msg'=>'操作失败，请重试！');
                    db()->rollback();
                }
            }
        }
        if ($param['is_in'] == 1) {
            $returnData = $return;
        }else{
            $returnData['c_from'] = $return['c_from'];
            $returnData['customer_number'] = $return['customer_number'];
            $returnData['customer_channel'] = $return['customer_channel'];
        }
		return $returnData;
	}
	/**
	 * 检查该订单是否存在于客资系统中
	 * 
	 * @param  customer_id
	 * @param  order_sn
	 *
	 * @return boolean
	 * @author lilong<lilong@suxuantech.cn>
	 */
	public function checkOrder($param){
		$res = controller("Customer","lib")->checkOrder($param);
		if (!$res) {
			$return = array('error'=>1,'code'=>201,'msg'=>'不存在该订单信息！');
		}else{
			$return = $res;
		}
        // var_dump($return);
		return $return;
	}
	/**
	 * 客资状态修改（进店进客，进店非进客，未进店，流失）
	 * 
	 * @param  code             1:进店进客；2：进店非进客；3：未进店(爽约)；4：流失
	 * @param  create_time      创建时间
	 * @param  lose_reason      流失原因
	 * @param  customer_number  客资编号
	 * @param  retail_sales     门市人员
	 * @param  m_tel            男士手机号
	 * @param  w_tel            女士手机号
     *reception_id
     *reception_name
	 * @param  brandclass_id    事业部id
	 * @param  shop_code        shop_code
     * @param  syjd_day         erp标记实际进店时间
     * @param  yjd_day          crm预计进店时间
	 *
	 * @return boolean
	 * @author lilong<lilong@suxuantech.cn>
	 */
    public function changeCustomerStatus($param){
        $param['create_time'] = date('Y-m-d H:i:s',strtotime($param['create_time']));
        // 
        $param['yjd_day'] = date('Y-m-d H:i:s',strtotime($param['yjd_day']));
        $param['syjd_day']= $param['syjd_day'] ? date('Y-m-d H:i:s',strtotime($param['syjd_day'])) : date('Y-m-d H:i:s');

        $return = [];
        switch ($param['code']) {
            case '1':
                $data['is_intostore'] = 2;
                $data['syjd_day']     = $param['syjd_day'];
                break;
            case '2':
                $data['is_intostore'] = 3;
                $data['syjd_day']     = $param['syjd_day'];
                break;
            case '3':
                $data['is_intostore'] = 1;
                break;
            case '4':
                $data['erp_loss']       = 2;
                // 5：进店未成交（流失）,
                $data['is_intostore']   = 5;
                $data['syjd_day']     = $param['syjd_day'];//1213添加，进店流失，要标记进店时间
                $param['lose_reason'] = $param['lose_reason']?$param['lose_reason']:'ERP进店流失（无流失原因）';
                $data['erp_loss_reason']= $param['lose_reason'];
                $data['erp_loss_time']  = $param['create_time'];
                break;
        }
        $data['update_time'] = date('Y-m-d H:i:s');
        // 接待人员-取门市
        if($param['reception_name']){
            $data['reception_name'] = trim($param['reception_name']);
            $staff = controller('crm/Customer','lib')->get_staff_list(['staffname'=>trim($param['reception_name'])]);
            $data['reception_id']   = $staff[0]['id'];
        }
        // 判断条件
        if ($param['customer_number']) {
            $where['customer_number'] = $param['customer_number'];
            $cInfo = db('c_customerinfo')->where($where)->field('id,customer_name,customer_number,is_intostore,sales_staff,sales_staff_id,yjd_day,syjd_day,dj_staff,dj_staff_id')->find();
            // if ($cInfo['yjd_day'] == $param['yjd_day']) {
                
            // }
            // $where['id'] = $cInfo['id'];
        }else{
            // 排重客资
            $brandclass_id = (int)$param['brandclass_id'];
            $brandclassInfo = controller('index/Customer','lib')->getBrandClassInfo($brandclass_id);
            $iData['brandclass_id']= $brandclass_id;
            $iData['brandclass']   = $brandclassInfo['brandclass'];
            $iData['contact_type'] = 1;
            $iData['contact_w']    = $param['w_tel'];
            $iData['contact_m']    = $param['m_tel'];

            $res = $this->getCustomerInfomation($iData);
            if (empty($res['customer_number'])) {
                $return = array('error'=>1,'code'=>202,'msg'=>'没有找到该客资，请重试！');
                return $return;
            }else{
                $where['customer_number'] = $res['customer_number'];
                $cInfo = db('c_customerinfo')->where($where)->field('id,customer_name,customer_number,is_intostore,sales_staff,sales_staff_id,syjd_day,dj_staff,dj_staff_id')->find();
                // $where['id'] = $cInfo['id'];
            }
        }
        // 发送站内弹窗消息
        $messageD['send_type']      = 1;
        $messageD['send_time']      = $param['create_time'];
        $messageD['send_title']     = '标记提醒';

        $remind = getRemind($param['brandclass_id']);

        // 客资进店
        if ($param['code'] == 1 ) {
            $messageD['send_title']     = '进店提醒';
            $messageD['send_msg'] = '您有一笔客资已经标记进店，ID：'.$cInfo['id'].'，姓名：'.$cInfo['customer_name'].'。';
        }elseif($param['code'] == 2){
            $messageD['send_title']     = '进店提醒';
            $messageD['send_msg'] = '您有一笔客资已经标记进店非进客，ID：'.$cInfo['id'].'，姓名：'.$cInfo['customer_name'].'。【非进客】';
        }
        // 流失
        else if ($param['code'] == 4) {
            $messageD['send_title']     = '流失提醒';
            $messageD['send_msg'] = '您有一笔客资已标记进店流失，ID：'.$cInfo['id'].'，姓名：'.$cInfo['customer_name'].'。';
        }


        $messageD['receive_status'] = 1;
        $messageD['receive_time']   = date('Y-m-d H:i:s');
        $messageD['operation_type'] = 2;
        $messageD['operation']      = '';
        $messageD['customer_id']    = $cInfo['id'];

        $timeOut = db_config('fp_timeout_'.$param['shop_code']);
        $messageD['time_out']       = $timeOut ? $timeOut : 60;

        if($cInfo['dj_staff_id'] && in_array('tan',$remind['jd']['send_method']) && in_array('dj',$remind['jd']['send_receive'])){
            $messageD['receive_id']     = $cInfo['dj_staff_id'];
            $messageD['receive_name']   = $cInfo['dj_staff'];
            sendSystemMessage($messageD);
        }
        if($cInfo['sales_staff_id'] && in_array('tan',$remind['jd']['send_method']) && in_array('sales',$remind['jd']['send_receive'])){
            $messageD['receive_id']     = $cInfo['sales_staff_id'];
            $messageD['receive_name']   = $cInfo['sales_staff'];
            sendSystemMessage($messageD);
        }
        if($cInfo['dj_staff_id'] && in_array('tui',$remind['jd']['send_method']) && in_array('dj',$remind['jd']['send_receive'])){
            $content = [
                'touser'       => $cInfo['dj_staff_id'],
                'template_id'  => OPENTM_MFP,
                'data'         => [
                    'first'=>[
                        'value'=> '系统消息',
                        'color'=> '#173177'
                    ],
                    'keyword1'=>[
                        'value'=> $messageD['send_msg'],
                        'color'=> '#173177'
                    ],
                    'keyword2'=>[
                        'value'=> date('Y-m-d H:i:s'),
                        'color'=> '#173177'
                    ],
                    'remark'=>[
                        'value'=> '请确认，谢谢',
                        'color'=> '#173177'
                    ],
                ],
            ];
            $send_data['content'] = json_encode($content);
            $res = sendMsg($send_data);
        }
        if($cInfo['sales_staff_id'] && in_array('tui',$remind['jd']['send_method']) && in_array('sales',$remind['jd']['send_receive'])){
            $content = [
                'touser'       => $cInfo['sales_staff_id'],
                'template_id'  => OPENTM_MFP,
                'data'         => [
                    'first'=>[
                        'value'=> '系统消息',
                        'color'=> '#173177'
                    ],
                    'keyword1'=>[
                        'value'=> $messageD['send_msg'],
                        'color'=> '#173177'
                    ],
                    'keyword2'=>[
                        'value'=> date('Y-m-d H:i:s'),
                        'color'=> '#173177'
                    ],
                    'remark'=>[
                        'value'=> '请确认，谢谢',
                        'color'=> '#173177'
                    ],
                ],
            ];
            $send_data['content'] = json_encode($content);
            $res = sendMsg($send_data);
        }


        // 追踪数据
        $track['gtType'] = 5;
        $track['customer_id'] = $cInfo['id'];
        $track['customer_name'] = $cInfo['customer_name'];
        $track['customer_number'] = $cInfo['customer_number'];
        $track['sales_day'] = date('Y-m-d H:i:s');
        $track['sales_staff'] = trim($param['staff_name']);
        $track['sales_staff_id'] = trim($param['staff_id']);
        $track['sales_remark'] = $param['lose_reason'] ? trim($param['lose_reason']) : NULL;
        $track['shop_code'] = trim($param['shop_code']);
        $url = '5a005e0038270';
        $dataT['shop_code'] = trim($param['shop_code']);
        $tempT = sx_call($url,$dataT);
        if ($tempT['code'] == 200) {
            $track['shop_name'] = $tempT['data']['shop_name'];
        }else{
            $track['shop_name'] = NUll;
        }
        
        if($cInfo['syjd_day']){
            //如果之前已经设了进店日期，
            //后面不能再改进店日期了，比如标流失了，然后第二天标非进店进客
            //写错了怎么办？
            //不能管写错的情况，因为如果邀了两笔，第一笔成交了，第二笔如果标流失了，会把进店时间更新掉的，还是不更新进店了
            //有问题再查日志吧。
            unset($data['syjd_day']);
        }
        // var_dump($track);exit;
        // 开启事务
        db()->startTrans();
        try {
            db('c_customerinfo')->where($where)->update($data);
            $staff_id = $param['staff_id'];
            $staffInfo = getStaffInfoById($staff_id);
            history_log($data, [], $where['id'], $staff_id, $staffInfo['staffname']);

            // 追踪记录
            db('c_salestrackinginfo')->insert($track);
            db()->commit();
            $return = $data;
        } catch (\Exception $e) {
            $return = array('error'=>1,'code'=>201,'msg'=>'修改失败，请重试！','error'=>$e->getMessage());
            db()->rollback();
        }

        return $return;
    }
    /**
     * 门市创建新订单
     * 
     * @param  brandclass_id         事业部id
     * @param  shop_code             shop_code
     * @param  staff_id              员工id
     * @param  staff_name            员工姓名
     * @param  order_sn              订单编号 
     * @param  create_time           创建时间 (y-m-d H:i:s)
     * @param  consultation_type     消费类型
     * @param  consultation_type_id  消费类型 id
     * @param  customer_cource       客户来源
     * @param  customer_cource_id    客户来源 id
     * @param  customer_area         客户分区
     * @param  customer_area_id      客户分区 id
     * @param  marry_day             结婚日期
     * @param  baby_birthday         宝宝生日
     * @param  wname                 女士姓名
     * @param  wphone                女士手机
     * @param  mname                 男士姓名
     * @param  mphone                男士手机
     * @param  wwechat               女士微信
     * @param  mwechat               男士微信
     * @param  wbirthday             女士生日
     * @param  mbirthday             男士生日
     * @param  introducer_name       介绍人姓名
     * @param  introducer_tel        介绍人电话
     * @param  province              省
     * @param  city                  市
     * @param  county                区/县
     * @param  customer_address      address
     * @param  customer_number       客资编号
     *
     * @return string           customer_number
     * @author lilong<lilong@suxuantech.cn>
     */
    public function createOrder($param){
        $remind = getRemind($param['brandclass_id']);
        $target_time = date('Y-m-d H:i:s',strtotime($param['create_time']));
        $param['target_time'] = $target_time;
        $param['create_time'] = date('Y-m-d H:i:s',time());
        $cData['is_success'] = 3;
        $brandclass_id = (int)$param['brandclass_id'];
        $brandclassInfo= controller('index/Customer','lib')->getBrandClassInfo($brandclass_id);
        $brandclass    = $brandclassInfo['brandclass'];
        // 如果存在客资编号
        if ($param['customer_number']) {
            $res = db('c_customerinfo')
                ->where('customer_number', $param['customer_number'])
                ->field('id,customer_number,customer_name,is_valid,is_success,customer_cource,customer_cource_id,customer_orderaddress,customer_orderaddress_id,marry_day,customer_name,customer_sex,customer_tel,customer_wechat,customer_birthday,mate_name,mate_sex,mate_tel,mate_wechat,mate_birthday,introducer_name,introducer_number,introducer_tel,province,province_id,city,city_id,county,county_id,customer_address,customer_channel_id,customer_channel,sales_staff,sales_staff_id,sales_staff_number,dj_day,yjd_action_day,c_star_day,last_trackday,order_start_time,order_type,syjd_day,order_number,customer_type,dj_staff_id,dj_staff')
                ->find();
            // 更新客资表
            $cData['province'] = $param['province'];
            $cData['city']     = $param['city'];
            $cData['county']   = $param['county'];
            $cData['customer_address'] = $param['customer_address'];

            // 客资订单信息
            $cData['order_number'] = $param['order_sn'];
            $cData['order_start_time'] = $target_time;

            // 有效状态
            if ($res['is_valid'] != 1 && $res['is_valid'] != 3) {
                $cData['is_valid'] = 1;
                $cData['yx_day'] = $param['create_time'];
            }
            $param['order_type'] = 2;
            // $param['order_type'] = $res['order_type']?$res['order_type']:2;
            // 线下订单 
            // if ($param['order_type'] == 2) {
                // 进店状态
                if ($res['is_intostore'] != 2) {
                    $cData['is_intostore'] = 2;
                    if($res['is_intostore'] != 5 || !$res['syjd_day'])
                    $cData['syjd_day'] = $target_time;//$param['create_time'];
                }
            // }
            $cData['order_type'] = $param['order_type'];

            // 消费类型
            // if ($res['consultation_type_id'] != $param['consultation_type_id'] && $param['consultation_type_id']) {
            //     $cData['consultation_type_id']= $param['consultation_type_id'];
            //     $cData['consultation_type']   = $param['consultation_type'];
            // }
            // 客户分区
            if ($res['customer_area_id'] != $param['customer_area_id'] && $param['customer_area_id']) {
                $cData['customer_area_id']= $param['customer_area_id'];
                $cData['customer_area']   = $param['customer_area'];
            }
            //reception_id
            $cData['reception_id']   = intval($param['reception_id']);
            $cData['reception_name'] = trim($param['reception_name']);
            if(!$res['order_number'] || !config('exclude_consultation_type') || !in_array($param['consultation_type'],config('exclude_consultation_type'))){
                //针对于客资已经有了一个订单号了，且当前传过来的消费类型被配置成排除此消费类弄的，成单不更新客资表
                //190107SDM更改
                //解决：当成一单为婚纱后，又送一单为全家福时，客资订单被更新成全家福了。
                db('c_customerinfo')->where('id', $res['id'])->update($cData);
            }

            // 创建订单
            $oData['order_sn']          = $param['order_sn'];
            $oData['customer_id']       = $res['id'];
            $oData['customer_name']     = $param['wname'];
            $oData['consultation_type'] = $param['consultation_type'];
            $oData['target_time']       = $target_time;
            $oData['create_time']       = $param['create_time'];
            $oData['shop_code']         = $res['shop_code'];
            $oData['shop_name']         = $res['shop_name'];
            $oData['order_type']        = $param['order_type'];
            $oData['brandclass_id']     = $param['brandclass_id'];
            $oData['brandclass']        = $brandclassInfo['brandclass'];
            db('c_customer_order')->insert($oData);
            // 发送站内弹窗消息
            $message['send_type']      = 1;
            $message['send_time']      = $param['create_time'];
            $message['send_title']     = '订单提醒';
            $message['send_msg'] = '您有一笔客资已订单，ID：'.$res['id'].'，姓名：'.$res['customer_name'];
            if($res['customer_tel']){
                $message['send_msg'] .= '，手机：'.$res['customer_tel'];
            }elseif($res['mate_tel']){
                $message['send_msg'] .= '，手机：'.$res['mate_tel'];
            }
            $message['send_msg'] .='，请确认。';

            $message['receive_status'] = 1;
            $message['receive_time']   = date('Y-m-d H:i:s');
            $message['operation_type'] = 2;
            $message['operation']      = '';
            $message['customer_id']    = $res['id'];

            $timeOut = db_config('fp_timeout_'.$param['shop_code']);
            $message['time_out']       = $timeOut ? $timeOut : 60;

            if($res['dj_staff_id'] && in_array('tan',$remind['order']['send_method']) && in_array('dj',$remind['order']['send_receive'])){
                $message['receive_id']     = $res['dj_staff_id'];
                $message['receive_name']   = $res['dj_staff'];
                sendSystemMessage($message);
            }
            if($res['sales_staff_id'] && in_array('tan',$remind['order']['send_method']) && in_array('sales',$remind['order']['send_receive'])){
                $message['receive_id']     = $res['sales_staff_id'];
                $message['receive_name']   = $res['sales_staff'];
                sendSystemMessage($message);
            }

            //如果是转介绍客资，向登记人发消息
            if($res['customer_type']== 2 || in_array('tui',$remind['order']['send_method']) && in_array('dj',$remind['order']['send_receive'])){
                $content = [
                    'touser'       => $res['dj_staff_id'],
                    'template_id'  => OPENTM_YX,
                    'data'         => [
                        'first'=>[
                            'value'=> '您有一笔客资已订单',
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $res['customer_name'],
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $res['sales_staff'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> date('Y-m-d H:i:s'),
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> 'ID:'.$res['id'].',订单号：'.$res['order_number'].',手机：'.$res['customer_tel'].',请尽快查看，谢谢',
                            'color'=> '#173177'
                        ],
                    ]
                ];
                $send_data['content'] = json_encode($content);
                sendMsg($send_data);
            }
            if($res['sales_staff_id'] && in_array('tui',$remind['order']['send_method']) && in_array('sales',$remind['order']['send_receive'])){
                $content = [
                    'touser'       => $res['sales_staff_id'],
                    'template_id'  => OPENTM_YX,
                    'data'         => [
                        'first'=>[
                            'value'=> '您有一笔客资已订单',
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $res['customer_name'],
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $res['sales_staff'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> date('Y-m-d H:i:s'),
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> 'ID:'.$res['id'].',订单号：'.$res['order_number'].',手机：'.$res['customer_tel'].',请尽快查看，谢谢',
                            'color'=> '#173177'
                        ],
                    ]
                ];
                $send_data['content'] = json_encode($content);
                sendMsg($send_data);
            }

            // 返回客资编号
            $returnData['customer_number'] = $res['customer_number'];
            return $returnData;
        }

        // c_sysconfig  erp_order_1  1：默认； 2：录入时间(录入手机号时间)； 3：之后一次追踪时间
        $erp_order_type = db_config('erp_order_'.$param['brandclass_id']);
        $param['brandclass'] = $brandclass;
        if ($erp_order_type == 2) {
            $param['erp_order_type'] = 2;
            $res = controller("Customer", "lib")->createOrderByType($param);
            $returnData['customer_number'] = $res;
            return $returnData;
        }else if ($erp_order_type == 3) {
            $param['erp_order_type'] = 3;
            $res = controller("Customer", "lib")->createOrderByType($param);
            $returnData['customer_number'] = $res;
            return $returnData;
        }else if ($erp_order_type == 4) {
            $param['erp_order_type'] = 4;
            $res = controller("Customer", "lib")->createOrderByType($param);
            $returnData['customer_number'] = $res;
            return $returnData;
        }

        $iData['brandclass_id']= $brandclass_id;
        $iData['brandclass']   = $brandclass;
        $iData['contact_type'] = 1;
        $iData['contact_w']    = $param['wphone'];
        $iData['contact_m']    = $param['mphone'];
        
        $res = $this->getCustomerInfomation($iData);
        

        // var_dump($res);exit;
        // 返回空创建客资及订单
        if (empty($res['customer_number'])) {
            $res = controller("Customer", "lib")->createCustomer($param);
            // 创建订单
            $oData['order_sn']          = $param['order_sn'];
            $oData['customer_id']       = $res['id'];
            $oData['customer_name']     = $param['wname'];
            $oData['consultation_type'] = $param['consultation_type'];
            $oData['target_time']       = $target_time;
            $oData['create_time']       = $param['create_time'];
            $oData['shop_code']         = $res['shop_code'];
            $oData['shop_name']         = $res['shop_name'];
            $oData['order_type']        = 2;
            $oData['brandclass_id']     = $param['brandclass_id'];
            $oData['brandclass']        = $brandclassInfo['brandclass'];
            db('c_customer_order')->insert($oData);
            // 发送站内弹窗消息
            $message['send_type']      = 1;
            $message['send_time']      = $param['create_time'];
            $message['send_title']     = '订单提醒';
            $message['send_msg'] = '您有一笔客资已订单，ID：'.$res['id'].'，姓名：'.$res['customer_name'];
            if($res['customer_tel']){
                $message['send_msg'] .= '，手机：'.$res['customer_tel'];
            }elseif($res['mate_tel']){
                $message['send_msg'] .= '，手机：'.$res['mate_tel'];
            }
            $message['send_msg'] .='，请确认。';
            $message['receive_status'] = 1;
            $message['receive_time']   = date('Y-m-d H:i:s');
            $message['operation_type'] = 2;
            $message['operation']      = '';
            $message['customer_id']    = $res['id'];

            $timeOut = db_config('fp_timeout_'.$param['shop_code']);
            $message['time_out']       = $timeOut ? $timeOut : 60;

            if(in_array('tan',$remind['order']['send_method']) && in_array('dj',$remind['order']['send_receive'])){
                $message['receive_id']     = $res['dj_staff_id'];
                $message['receive_name']   = $res['dj_staff'];
                sendSystemMessage($message);
            }
            if($res['sales_staff_id'] && in_array('tan',$remind['order']['send_method']) && in_array('sales',$remind['order']['send_receive'])){
                $message['receive_id']     = $res['sales_staff_id'];
                $message['receive_name']   = $res['sales_staff'];
                sendSystemMessage($message);
            }
            //如果是转介绍客资，向登记人发消息
            if($res['customer_type']== 2 || in_array('tui',$remind['order']['send_method']) && in_array('dj',$remind['order']['send_receive'])){
                $content = [
                    'touser'       => $res['dj_staff_id'],
                    'template_id'  => OPENTM_YX,
                    'data'         => [
                        'first'=>[
                            'value'=> '您有一笔客资已订单',
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $res['customer_name'],
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $res['sales_staff'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> date('Y-m-d H:i:s'),
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> 'ID:'.$res['id'].',订单号：'.$res['order_number'].'，手机：'.$res['customer_tel'].'，请尽快查看，谢谢',
                            'color'=> '#173177'
                        ],
                    ]
                ];
                $send_data['content'] = json_encode($content);
                sendMsg($send_data);
            }
            if($res['sales_staff_id'] && in_array('tui',$remind['order']['send_method']) && in_array('sales',$remind['order']['send_receive'])){
                $content = [
                    'touser'       => $res['sales_staff_id'],
                    'template_id'  => OPENTM_YX,
                    'data'         => [
                        'first'=>[
                            'value'=> '您有一笔客资已订单',
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $res['customer_name'],
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $res['sales_staff'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> date('Y-m-d H:i:s'),
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> 'ID:'.$res['id'].',订单号：'.$res['order_number'].'，手机：'.$res['customer_tel'].'，请尽快查看，谢谢',
                            'color'=> '#173177'
                        ],
                    ]
                ];
                $send_data['content'] = json_encode($content);
                sendMsg($send_data);
            }

            // 返回客资编号
            $returnData['customer_number'] = $res['customer_number'];
            return $returnData;
        }else{
            // 返回客资编号
            $returnData['customer_number'] = $res['customer_number'];

            // 更新客资表
            $cData['order_number'] = $param['order_sn'];
            $cData['order_start_time'] = $target_time;


            if ($res['is_valid'] != 1 && $res['is_valid'] != 3) {
                $cData['is_valid'] = 1;
                $cData['yx_day'] = $param['create_time'];
            }
            if ($res['is_intostore'] != 2) {
                $cData['is_intostore'] = 2;
                if($res['is_intostore'] != 5 || !$res['syjd_day'])
                $cData['syjd_day'] = $param['target_time'];
            }
            
            // 女士信息为客资信息
            if ($res['customer_tel'] == $param['wphone']) {
                // 客资信息
                if ($res['customer_sex'] != '女') {
                    $cData['customer_sex']   = '女';
                }                
                if ($res['customer_name'] != $param['wname'] && $param['wname']) {
                    $cData['customer_name']  = $param['wname'];
                }
                if ($res['customer_wechat'] != $param['wwechat'] && $param['wwechat']) {
                    $cData['customer_wechat']  = $param['wwechat'];
                }
                // 配偶信息
                if ($res['mate_sex'] != '男') {
                    $cData['mate_sex'] = '男';
                }                
                if ($res['mate_name'] != $param['mname'] && $param['mname']) {
                    $cData['mate_name']  = $param['mname'];
                }
                if ($res['mate_wechat'] != $param['mwechat'] && $param['mwechat']) {
                    $cData['mate_wechat']  = $param['mwechat'];
                }
            }
            // 男士信息为客资信息
            else if ($res['customer_tel'] == $param['mphone']) {
                // 客资信息
                if ($res['customer_sex'] != '男') {
                    $cData['customer_sex']   = '男';
                }                
                if ($res['customer_name'] != $param['mname'] && $param['mname']) {
                    $cData['customer_name']  = $param['mname'];
                }
                if ($res['customer_wechat'] != $param['mwechat'] && $param['mwechat']) {
                    $cData['customer_wechat']  = $param['mwechat'];
                }
                // 配偶信息
                if ($res['mate_sex'] != '女') {
                    $cData['mate_sex'] = '女';
                }                
                if ($res['mate_name'] != $param['wname'] && $param['wname']) {
                    $cData['mate_name']  = $param['wname'];
                }
                if ($res['mate_wechat'] != $param['wwechat'] && $param['wwechat']) {
                    $cData['mate_wechat']  = $param['wwechat'];
                }
            }
            // 消费类型
            // if ($res['consultation_type_id'] != $param['consultation_type_id'] && $param['consultation_type_id']) {
            //     $cData['consultation_type_id']= $param['consultation_type_id'];
            //     $cData['consultation_type']   = $param['consultation_type'];
            // }
            // 客户分区
            if ($res['customer_area_id'] != $param['customer_area_id'] && $param['customer_area_id']) {
                $cData['customer_area_id']= $param['customer_area_id'];
                $cData['customer_area']   = $param['customer_area'];
            }
            $cData['reception_id']   = $param['reception_id'];
            $cData['reception_name'] = trim($param['reception_name']);
            $cData['order_type']     = 2;
            // $cData['order_type']     = $res['order_type'] ? $res['order_type'] : 2;
            if(!$res['order_number'] || !config('exclude_consultation_type') || !in_array($param['consultation_type'],config('exclude_consultation_type'))){
                //针对于客资已经有了一个订单号了，且当前传过来的消费类型被配置成排除此消费类弄的，成单不更新客资表
                //190107SDM更改
                //解决：当成一单为婚纱后，又送一单为全家福时，客资订单被更新成全家福了。
                db('c_customerinfo')->where('id', $res['id'])->update($cData);
            }
            //db('c_customerinfo')->where('id', $res['id'])->update($cData);

            // 判断订单是否存在，并创建订单
            $arr = array(
                'order_sn'=>$param['order_sn'],
            );
            $resO = $this->checkOrder($arr);
            if($resO['error'] == 1){
                // 创建订单
                $oData['order_sn']           = $param['order_sn'];
                $oData['customer_id']        = $res['id'];
                $oData['customer_name']      = $cData['customer_name'] ? $cData['customer_name'] : $res['customer_name'];
                $oData['customer_channel']   = $res['customer_channel'];
                $oData['customer_channel_id']= $res['customer_channel_id'];
                $oData['consultation_type']  = $param['consultation_type'];
                $oData['target_time']        = $target_time;
                $oData['create_time']        = $param['create_time'];
                $oData['shop_code']          = $res['shop_code'];
                $oData['shop_name']          = $res['shop_name'];
                $oData['order_type']         = 2;
                // $oData['order_type']         = $res['order_type'] ? $res['order_type'] : 2;
                $oData['brandclass_id']      = $param['brandclass_id'];
                $oData['brandclass']         = $brandclassInfo['brandclass'];
                db('c_customer_order')->insert($oData);
                //如果是转介绍客资，向登记人发消息
                if($res['customer_type']== 2|| in_array('tui',$remind['order']['send_method']) && in_array('dj',$remind['order']['send_receive'])){
                    $content = [
                        'touser'       => $res['dj_staff_id'],
                        'template_id'  => OPENTM_YX,
                        'data'         => [
                            'first'=>[
                                'value'=> '您有一笔客资已订单',
                                'color'=> '#173177'
                            ],
                            'keyword1'=>[
                                'value'=> $res['customer_name'],
                                'color'=> '#173177'
                            ],
                            'keyword2'=>[
                                'value'=> $res['sales_staff'],
                                'color'=> '#173177'
                            ],
                            'keyword3'=>[
                                'value'=> date('Y-m-d H:i:s'),
                                'color'=> '#173177'
                            ],
                            'remark'=>[
                                'value'=> 'ID:'.$res['id'].',订单号：'.$res['order_number'].'，手机：'.$res['customer_tel'].'，请尽快查看，谢谢',
                                'color'=> '#173177'
                            ],
                        ]
                    ];
                    $send_data['content'] = json_encode($content);
                    sendMsg($send_data);
                }
                if($res['sales_staff_id'] && in_array('tui',$remind['order']['send_method']) && in_array('sales',$remind['order']['send_receive'])){
                    $content = [
                        'touser'       => $res['sales_staff_id'],
                        'template_id'  => OPENTM_YX,
                        'data'         => [
                            'first'=>[
                                'value'=> '您有一笔客资已订单',
                                'color'=> '#173177'
                            ],
                            'keyword1'=>[
                                'value'=> $res['customer_name'],
                                'color'=> '#173177'
                            ],
                            'keyword2'=>[
                                'value'=> $res['sales_staff'],
                                'color'=> '#173177'
                            ],
                            'keyword3'=>[
                                'value'=> date('Y-m-d H:i:s'),
                                'color'=> '#173177'
                            ],
                            'remark'=>[
                                'value'=> 'ID:'.$res['id'].',订单号：'.$res['order_number'].'，手机：'.$res['customer_tel'].'，请尽快查看，谢谢',
                                'color'=> '#173177'
                            ],
                        ]
                    ];
                    $send_data['content'] = json_encode($content);
                    sendMsg($send_data);
                }

            }
            // 发送站内弹窗消息
            $message['send_type']      = 1;
            $message['send_time']      = $param['create_time'];
            $message['send_title']     = '订单提醒';
            $message['send_msg'] = '您有一笔客资已订单，ID：'.$res['id'].'，姓名：'.$cData['customer_name'];
            if($cData['customer_tel']){
                $message['send_msg'] .= '，手机：'.$cData['customer_tel'];
            }elseif($cData['mate_tel']){
                $message['send_msg'] .= '，手机：'.$cData['mate_tel'];
            }
            $message['send_msg'] .='，请确认。';

            $message['receive_status'] = 1;
            $message['receive_time']   = date('Y-m-d H:i:s');
            $message['operation_type'] = 2;
            $message['operation']      = '';
            $message['customer_id']    = $res['id'];

            $timeOut = db_config('fp_timeout_'.$param['shop_code']);
            $message['time_out']       = $timeOut ? $timeOut : 60;
            if(in_array('tan',$remind['order']['send_method']) && in_array('dj',$remind['order']['send_receive'])){
                $message['receive_id']     = $res['dj_staff_id'];
                $message['receive_name']   = $res['dj_staff'];
                sendSystemMessage($message);
            }
            if($res['sales_staff_id'] && in_array('tan',$remind['order']['send_method']) && in_array('sales',$remind['order']['send_receive'])){
                $message['receive_id']     = $res['sales_staff_id'];
                $message['receive_name']   = $res['sales_staff'];
                sendSystemMessage($message);
            }
            // 追踪数据
            $track['gtType'] = 5;
            $track['customer_id'] = $res['id'];
            $track['customer_name'] = $res['customer_name'];
            $track['customer_number'] = $res['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = trim($param['staff_name']);
            $track['sales_staff_id'] = trim($param['staff_id']);
            $track['sales_remark'] = 'ERP创建订单';
            $track['shop_code'] = trim($param['shop_code']);
            $url = '5a005e0038270';
            $dataT['shop_code'] = trim($param['shop_code']);
            $tempT = sx_call($url,$dataT);
            if ($tempT['code'] == 200) {
                $track['shop_name'] = $tempT['data']['shop_name'];
            }else{
                $track['shop_name'] = NUll;
            }
            // 追踪记录
            db('c_salestrackinginfo')->insert($track);
            // 如果存在第二个追踪人
            if ($res['asid']) {
                // 发送站内弹窗消息
                $messageD['send_type']      = 1;
                $messageD['send_time']      = $param['create_time'];
                $messageD['send_title']     = '订单提醒';
                $messageD['send_msg']       = '您有一笔订单冲突，ID：'.$res['id'].'，姓名：'.$res['customer_name'];
                if($res['customer_tel']){
                    $message['send_msg'] .= '，手机：'.$res['customer_tel'];
                }elseif($res['mate_tel']){
                    $message['send_msg'] .= '，手机：'.$res['mate_tel'];
                }
                $message['send_msg'] .='，请确认。';
                $messageD['receive_id']     = $res['sales_staff_id'];
                $messageD['receive_name']   = $res['sales_staff'];
                $messageD['receive_status'] = 1;
                $messageD['receive_time']   = $param['create_time'];
                $messageD['operation_type'] = 2;
                $messageD['operation']      = '';
                $messageD['customer_id']    = $res['id'];
                $timeOut = db_config('fp_timeout_'.$res['shop_code']);
                $messageD['time_out']       = $timeOut ? $timeOut : 60;
                sendSystemMessage($messageD);

                $messageD['send_type']      = 1;
                $messageD['send_time']      = $param['create_time'];
                $messageD['send_title']     = '订单提醒';
                $messageD['send_msg']       = '您有一笔订单冲突，ID：'.$res['acid'].'，姓名：'.$res['acname'];
                if($res['customer_tel']){
                    $message['send_msg'] .= '，手机：'.$res['customer_tel'];
                }elseif($res['mate_tel']){
                    $message['send_msg'] .= '，手机：'.$res['mate_tel'];
                }
                $message['send_msg'] .='，请确认。';
                $messageD['receive_id']     = $res['asid'];
                $messageD['receive_name']   = $res['asname'];
                $messageD['receive_status'] = 1;
                $messageD['receive_time']   = $param['create_time'];
                $messageD['operation_type'] = 2;
                $messageD['operation']      = '';
                $messageD['customer_id']    = $res['acid'];
                $timeOut = db_config('fp_timeout_'.$res['shop_code']);
                $messageD['time_out']       = $timeOut ? $timeOut : 60;
                sendSystemMessage($messageD);

                // 发送微信模板消息
                $contentM = [
                    'touser'       => $res['sales_staff_id'],
                    'template_id'  => OPENTM_CT,
                    'data'         => [
                        'first'=>[
                            'value'=>'您好，您有一笔订单冲突',
                            'color'=>'#173177'
                        ],
                        'keyword1'=>[
                            'value'=>$res['customer_name'].'('.$res['customer_sex'].')',
                            'color'=>'#173177'
                        ],
                        'keyword2'=>[
                            'value'=>$res['customer_tel'],
                            'color'=>'#173177'
                        ],
                        'keyword3'=>[
                            'value'=>'订单冲突',
                            'color'=>'#173177'
                        ],
                        'keyword4'=>[
                            'value'=>$param['create_time'],
                            'color'=>'#173177'
                        ],
                        'remark'=>[
                            'value'=>'请尽快查收，谢谢',
                            'color'=>'#173177'
                        ]
                    ]
                ];
                $send_data['content'] = json_encode($contentM);
                sendMsg($send_data);
                $contentW = [
                    'touser'       => $res['asid'],
                    'template_id'  => OPENTM_CT,
                    'data'         => [
                        'first'=>[
                            'value'=>'您好，您有一笔订单冲突',
                            'color'=>'#173177'
                        ],
                        'keyword1'=>[
                            'value'=>$res['acname'].'('.$res['acsex'].')',
                            'color'=>'#173177'
                        ],
                        'keyword2'=>[
                            'value'=>$res['actel'],
                            'color'=>'#173177'
                        ],
                        'keyword3'=>[
                            'value'=>'订单冲突',
                            'color'=>'#173177'
                        ],
                        'keyword4'=>[
                            'value'=>$param['create_time'],
                            'color'=>'#173177'
                        ],
                        'remark'=>[
                            'value'=>'请尽快查收，谢谢',
                            'color'=>'#173177'
                        ]
                    ]
                ];
                $send_data['content'] = json_encode($contentW);
                $res = sendMsg($send_data);
            }
            return $returnData;
        }
    }
    /*
     * 根据手机号查询此客资的节点
     * */
    public function getInfoByTel($param){
        $where = '';
        if($param['customer_tel']){
            $where['customer_tel'] = trim($param['customer_tel']);
        }
        if($param['customer_qq']){
            $where['customer_qq'] = trim($param['customer_qq']);
        }
        if($param['customer_wechat']){
            $where['customer_wechat'] = trim($param['customer_wechat']);
        }
        if($param['mate_tel']){
            $where['mate_tel'] = trim($param['mate_tel']);
        }
        if($param['brandclass_id']){
            $where['brandclass_id'] = trim($param['brandclass_id']);
        }
        if($param['shop_code']){
            $where['shop_code'] = trim($param['shop_code']);
        }

        $info = db('c_customerinfo')->where($where)->field('id,customer_name,customer_number,customer_tel,mate_tel,customer_qq,customer_wechat,dj_day,dj_staff,fp_day,fp_staff,jr_day,sales_staff,c_star_day,c_end_day,last_trackday,yx_day,yjd_day,syjd_day,order_start_time,order_day,order_number,consulation_shop,customer_intention,customer_type,introducer_type,introducer_name,introducer_tel')->select();
        if(empty($info)){
            return  array('error'=>1,'code'=>500,'msg'=>'无此客资！');
        }else{
            foreach($info as $k=>$v){
                $info[$k]['track_log'] = db('c_salestrackinginfo')->where('customer_id',$v['id'])->order('sales_day asc')->field('sales_staff,sales_day,sales_remark,step_name')->select();
            }
            return $info;
        }
    }
    /**
     * 门市删除订单
     * 
     * @param  staff_id              员工id
     * @param  staff_name            员工姓名
     * @param  order_sn              订单编号 
     *
     * @return boolen
     * @author lilong<lilong@suxuantech.cn>
     */
    public function delOrder($param){
        // 查看订单是否存在
        if (!$param['order_sn']) {
            $returnData=['code'=> 400,'msg' => '参数，订单号不存在'];
            return $returnData;
        }
        if (!$param['staff_id']) {
            $returnData=['code'=> 401,'msg' => '参数，员工id不存在'];
            return $returnData;
        }
        if (!$param['staff_name']) {
            $returnData=['code'=> 402,'msg' => '参数，员工姓名不存在'];
            return $returnData;
        }

        $order_sn = $param['order_sn'];
        $haveOrder = db('c_customer_order')->where('order_sn', $order_sn)->count();
        if (!$haveOrder) {
            $returnData=['code'=> 201,'msg' => '订单不存在'];
        }else{
            /*
            // 如果 进客 表存在 判断 这个订单的进客 对应几个订单，如果只有一个，那么进客表的订单状态修改为‘未定单’，如果对应多个那就取除了这个订单之外的最后一个订单的状态
            $table = isTableExist('c_customer_intostore');
            if ($table) {
                $into_id = db('c_customer_order')->where('order_sn', $order_sn)->value('into_id');
                // 如果有进客记录  eric 0429
                if ($into_id) {
                    $into_order = db('c_customer_order')->where('into_id', $into_id)->select();
                    // 如果进客存在多个订单
                    if (count($into_order)>1) {
                        # code...
                    }else{
                        
                    }
                }
            }
            // 这个订单的客资对应几个订单，如果只有一个，那么客资表的订单状态修改为‘未定单’，如果对应多个订单状态及订单有效时间？？？？
            */

            // 不考虑上面的情况，简单处理  一个进客对应一个订单， 订单删除了，客资对应的其他订单也不回来，在历史订单里查询
            // 查询订单所属的客资
            $hasCustomer = db('c_customerinfo')
                ->where('order_number', $order_sn)
                ->field('id,is_success,order_start_time,order_number,fact_money,totalpay_money')
                ->find();

            db()->startTrans();
            try {
                // 如果 进客 表存在 判断 这个订单的进客 
                $table = isTableExist('c_customer_intostore');
                if ($table) {
                    $into_id = db('c_customer_order')->where('order_sn', $order_sn)->value('into_id');
                    // 如果有进客记录  eric 0429
                    if ($into_id) {
                        $intoData['is_success'] = 2;
                        db('c_customer_intostore')->where('id', $into_id)->update($intoData);
                    }
                }
                // 删除订单及明细
                db('c_customer_order')->where('order_sn', $order_sn)->delete();
                db('c_order_detail')->where('order_sn', $order_sn)->delete();
                // 客资存在，去掉客资里的订单信息
                if ($hasCustomer) {
                    $cData['is_success']       = 2;
                    $cData['order_start_time'] = null;
                    $cData['order_day']        = null;
                    $cData['order_number']     = '';
                    $cData['fact_money']       = 0;
                    $cData['totalpay_money']   = 0;
                    db('c_customerinfo')->where('order_number',$order_sn)->update($cData);
                }
                db()->commit();
                $returnData=['code'=> 200,'msg' => '删除成功'];
            } catch (Exception $e) {
                db()->rollback();
                $returnData=['code'=> 202,'msg' => '操作失败'];
            }
        }

        // 记录日志
        $data = '订单编号：;<br />订单时间：;<br />付款金额：;<br />套系金额：;';

        $oldData = '订单编号：'.$hasCustomer['order_number'].';<br />订单时间：'.$hasCustomer['order_start_time'].';<br />付款金额：'.$hasCustomer['fact_money'].';<br />套系金额：'.$hasCustomer['totalpay_money'].';';
        $customerId = $hasCustomer['id'];
        $staffId  = $param['staff_id'];
        $staffName= $param['staff_name'];
        $module='';
        $controller = '';
        $action='customerInfo';

        history_log($data,$oldData,$customerId,$staffId,$staffName,$module,$controller,$action);
        // 删除订单后，重新处理一下客资
        $cParam['cid'] = $hasCustomer['id'];
        dealCustomerOrder($cParam);
        return $returnData;
    }
    /*
     * 退单 ( ERP 作废单 )
     * @param customer_number   客资编号
     * @param order_sn          订单编号
     * @param unvialid_reason   作废原因
     * @param type              1：本单作废； 2：取消作废订单
     * */
    public function refund($param){
        $number = trim($param['customer_number']);
        // $param['type'] = 1;
        // 本单作废
        if ($param['type'] == 1) {
            $info = db('c_customerinfo')->where('customer_number',$number)->field('id,order_number')->find();
            if(empty($info)){
                return array('code'=>100,'msg'=>'客资编号有误,未找到此客资');
            }
            $order = db('c_customer_order')->where('order_sn',$info['order_number'])->find();
            db()->startTrans();
            try{
                // 如果 进客 表存在 判断 这个订单的进客 
                $table = isTableExist('c_customer_intostore');
                if ($table) {
                    // 如果有进客记录  eric 0429
                    if ($order['into_id']) {
                        $intoData['is_success'] = 2;
                        db('c_customer_intostore')->where('id', $order['into_id'])->update($intoData);
                    }
                }

                $cinfo = [
                    'is_success' => 2,
                    //'order_day' = null,
                    //'order_number' = '',
                    //'totalpay_money' = 0,
                    //'fact_money' = 0,
                ];
                if($order){
                    // refund  1：正常；2：作废
                    $o_arr['refund'] = 2;
                    $o_arr['unvalid_time']  = date('Y-m-d H:i:s');
                    $o_arr['unvalid_reason']= $param['unvalid_reason'];
                    db('c_customer_order')->where('customer_id',$info['id'])->where('order_sn',$info['order_number'])->update($o_arr);
                    $cinfo['order_day'] = null;
                    $cinfo['order_number'] = null;
                    $cinfo['totalpay_money'] = 0;
                    $cinfo['fact_money'] = 0;
                }
                
                db('c_customerinfo')->where('customer_number',$number)->update($cinfo);
                $logData = [
                    'create_time'=>date('Y-m-d H:i:s'),
                    'customer_id'=>$info['id'],
                    'data'=>'ERP订单作废：'.$info['order_number'].'；作废原因：'.$param['unvalid_reason'],
                    'module'=>'index',
                    'controller'=>'Customer',
                    'action'=>'refund',
                ];
                common_log($logData,'action_log');
                db()->commit();
                // 作废订单后，重新处理一下客资
                $cParam['cid'] = $info['id'];
                dealCustomerOrder($cParam);
                // var_dump($res);exit;
                return array('code'=>200,'msg'=>'操作成功','data'=>$number);
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>105,'msg'=>'操作失败','error'=>$e->getMessage());
            }
        }
        // 取消作废操作
        else if ($param['type'] == 2) {
            $info = db('c_customerinfo')->where('customer_number',$number)->field('id,order_number,order_day,totalpay_money,fact_money')->find();
            if(empty($info)){
                return array('code'=>100,'msg'=>'客资编号有误,未找到此客资');
            }
            $order = db('c_customer_order')->where('order_sn',$info['order_number'])->find();
            // refund  1：正常；2：作废
            $o_arr['refund'] = 1;
            $o_arr['unvalid_time']  = null;
            //$o_arr['unvalid_reason']= '';

            db()->startTrans();
            try{
                if($order){
                    $cinfo['order_day'] = $order['target_time'];
                    $cinfo['order_number'] = $order['order_sn'];
                    $cinfo['totalpay_money'] = $order['two_pin_amount']+$order['order_amount'];
                    $cinfo['fact_money'] = $order['order_fact']+$order['two_pin_fact'];
                }else{
                    $cinfo['order_day'] = $info['order_day'];
                    $cinfo['order_number'] = $info['order_number'];
                    $cinfo['totalpay_money'] = $info['totalpay_money'];
                    $cinfo['fact_money'] = $info['fact_money'];
                }
                db('c_customer_order')->where('customer_id',$info['id'])->where('order_sn',$info['order_number'])->update($o_arr);

                db('c_customerinfo')->where('customer_number',$number)->update($cinfo);
                $logData = [
                    'create_time'=>date('Y-m-d H:i:s'),
                    'customer_id'=>$info['id'],
                    'data'=>'ERP订单取消作废：'.$info['order_number'],
                    'module'=>'index',
                    'controller'=>'Customer',
                    'action'=>'refund',
                ];
                common_log($logData,'action_log');
                db()->commit();
                // 作废订单后，重新处理一下客资
                $cParam['cid'] = $info['id'];
                dealCustomerOrder($cParam);
                return array('code'=>200,'msg'=>'操作成功','data'=>$number);
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>105,'msg'=>'操作失败','error'=>$e->getMessage());
            }
        }else{
            return array('code'=>106,'msg'=>'类型错误','error'=>json_encode($param));
        }
    }
    //获取员工A客量和毛客资量接口
    public function getStaffAllCustomer($param){
        if($param['brandclass_id']){
            $where['brandclass_id'] = intval($param['brandclass_id']);
        }
        if($param['shop_code']){
            $where['shop_code'] = intval($param['shop_code']);
        }
        if($param['department_id']){
            $where['department_id'] = intval($param['department_id']);
        }
        if($param['staff_id']){
            $where['id'] = intval($param['staff_id']);
        }
        if(empty($param['brandclass_id']) && empty($param['shop_code']) && empty($param['department_id']) && empty($param['staff_id'])){
            return array('code'=>300,'msg'=>'参数有误');
        }
        if($param['start']){
            $start = $param['start'] ? date('Y-m-d H:i:s',strtotime($param['start'])) : date('Y-m-d');
        }
        if($param['end']){
            $end = $param['end'] ? date('Y-m-d H:i:s',strtotime($param['end'])) : date('Y-m-d');
        }
        //获取所有员工
        $staffs = controller('crm/Customer','lib')->get_staff_list($where);
        foreach($staffs as $k=>$v){
            $staffs[$k]['aNum'] = db('c_customerinfo')->where('dj_staff_id',$v['id'])->where('dj_day','between',[$start,$end])->where('sign_name','like','%a%')->count();
            $staffs[$k]['allNum'] = db('c_customerinfo')->where('dj_staff_id',$v['id'])->where('dj_day','between',[$start,$end])->count();
        }
        if(!empty($staffs)){
            return $staffs;
        }else{
            return array('code'=>100,'msg'=>'未获取到数据');
        }
    }
    //获取客资详情和追踪记录
    public function getCustomerInfo($param){
        $cusNumber = trim($param['customer_number']);
        if(!$cusNumber){
            return array('code'=>300,'msg'=>'未获取到客资编号','data'=>'');
        }
        $cus = db('c_customerinfo')->where('customer_number',$cusNumber)->find();
        if(!empty($info)){
            return $cus;
        }else{
            return array('code'=>100,'msg'=>'未查询到数据','data'=>'');
        }
    }
    //获取追踪记录
    public function getSalesLog($param){
        $cusNumber = trim($param['customer_number']);
        if(!$cusNumber){
            return array('code'=>300,'msg'=>'未获取到客资编号','data'=>'');
        }
        $id = db('c_customerinfo')->where('customer_number',$cusNumber)->value('id');
        //追踪记录
        $log = db('c_salestrackinginfo')->where('customer_id',$id)->select();
        if(!empty($log)){
            return $log;
        }else{
            return array('code'=>100,'msg'=>'未查询到数据','data'=>'');
        }
    }
    //获取客资列表
    public function getCustomerList($param){
        $where['is_status'] = 1;
        $start = $param['start'] ? date('Y-m-d',strtotime(trim($param['start']))) : date('Y-m-d');
        $end = $param['end'] ? date('Y-m-d',strtotime(trim($param['end']))) : date('Y-m-d 23:59:59');
        if($param['search']){
            $search = '%'.trim($param['search']).'%';
            $sql = "customer_name like :customer_name or customer_tel like :customer_tel or customer_qq like :customer_qq or customer_wechat like :customer_wechat or mate_tel like :mate_tel or mate_qq like :mate_qq or mate_wechat like :mate_wechat or customer_number like :customer_number or order_number like :order_number";
            $arr['customer_name']    = $search;
            $arr['customer_tel'] = $search;
            $arr['customer_qq']    = $search;
            $arr['customer_wechat']    = $search;
            $arr['mate_tel']    = $search;
            $arr['mate_qq']    = $search;
            $arr['mate_wechat']    = $search;
            $arr['customer_number']    = $search;
            $arr['order_number']    = $search;
        }else{
            return array('code'=>300,'msg'=>'未获取到请求参数','data'=>'');
        }
        $info = db('c_customerinfo')->where($where)->where($sql,$arr)->where('dj_day','between time',[$start,$end])->order('id desc')->select();
        if(!empty($info)){
            return $info;
        }else{
            return array('code'=>100,'msg'=>'未查询到数据','data'=>'');
        }
    }
    /**
     * 根据联系方式，查询客资信息
     * 
     * @param  customer_number       客资编号
     * @param  brandclass_id         事业部ID
     * @param  brandclass            事业部
     * @param  contact_type          联系方式类型(1：手机；2：微信；3：qq)
     * @param  contact_w             联系方式_女士
     * @param  contact_m             联系方式_男士
     *
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getCustomerInfomation($param){
        $customer_number = $param['customer_number'];
        // 如果有客资编号
        if ($customer_number) {
            $returnData = db('c_customerinfo')
                ->where('customer_number', $customer_number)
                ->field('id,customer_number,customer_cource,customer_cource_id,customer_orderaddress,customer_orderaddress_id,marry_day,customer_name,customer_sex,customer_tel,customer_wechat,customer_birthday,mate_name,mate_sex,mate_tel,mate_wechat,mate_birthday,introducer_name,introducer_tel,introducer_number,customer_address,sales_staff,sales_staff_id,dj_day,c_star_day,last_trackday,customer_channel,customer_channel_id,syjd_day,is_intostore,order_number,customer_type,dj_staff_id,dj_staff,order_type')
                ->find();
            return $returnData;
        }
        // 如果没有客资编号
        else{
            // 根据女士手机号查询客资表，如果已经订单，那么重复录入，来源属于erp；如果没有订单，且超过有效期，重复录入，来源属于erp；如果没有订单，且没有超过有效期，不重复录入，来源属于crm

            // 根据男士手机号查询客资表，如果已经订单，那么重复录入，来源属于erp；如果没有订单，且超过有效期，重复录入，来源属于erp；如果没有订单，且没有超过有效期，不重复录入，来源属于crm
        	
            // 如果男女手机号查出两条不同客资，如果一个有效，一个无效，返回有效；都有效或者都无效,谁先预约进店算谁的，如果都没有预约，看最近三天有追踪记录，谁先追踪，算谁的；最近三天没有追踪记录，谁最后追踪算谁的

            $contact_type = (int)$param['contact_type'];
            if ( $contact_type > 3 ) {
                return array('code'=>100,'msg'=>'contact_type错误','error'=>'contact_type：'.$contact_type);
            }
            // 男士手机，女士手机都不存在 
            if (!$param['contact_w'] && !$param['contact_m']) {
                return array('code'=>101,'msg'=>'联系方式不存在','error'=>$param['contact_w'].'/'.$param['contact_m']);
            }

            $pattern   = '/\s/';
            $contact_m = strip_tags($param['contact_m']);
            $contact_w = strip_tags($param['contact_w']);
            $contact_m = preg_replace($pattern, '', $contact_m);
            $contact_w = preg_replace($pattern, '', $contact_w);

            // 手机
            if ($contact_type == 1) {
                if ($contact_m) {
                    if(!check_tel($contact_m)){
                        return array('code'=>102,'msg'=>'男士手机号格式错误','error'=>$contact_m);
                    }
                }
                if ($contact_w) {
                    if(!check_tel($contact_w)){
                        return array('code'=>103,'msg'=>'女士手机号格式错误','error'=>$contact_w);
                    }
                }
            }

            $brandclass_id = (int)$param['brandclass_id'];
            $brandclass    = trim($param['brandclass']);

            // c_sysconfig  erp_order_1  1：默认； 2：录入时间(录入手机号时间)； 3：之后一次追踪时间
            $erp_order_type = db_config('erp_order_'.$param['brandclass_id']);
            
            // $gParam['wphone'] = $contact_w;
            // $gParam['mphone'] = $contact_m;
            if ($erp_order_type == 2) {
                $gParam['time'] = 'tel_time';
                $gParam['order']= 'asc';
                // $res = controller("Customer", "lib")->getCustomerNumber($gParam);
                // $returnData = db('c_customerinfo')->where('customer_number',$res)->field('id,customer_number,customer_name,is_valid,is_success,customer_cource,customer_cource_id,customer_orderaddress,customer_orderaddress_id,marry_day,customer_name,customer_sex,customer_tel,customer_wechat,customer_birthday,mate_name,mate_sex,mate_tel,mate_wechat,mate_birthday,introducer_name,introducer_number,introducer_tel,province,province_id,city,city_id,county,county_id,customer_address,customer_channel_id,customer_channel,sales_staff,sales_staff_id,sales_staff_number,dj_day,yjd_action_day,c_star_day,last_trackday,order_start_time,c_from,syjd_day,is_intostore,order_number,dj_staff')->find();
                // return $returnData;
            }else if ($erp_order_type == 3) {
                $gParam['time'] = 'c_star_day';
                $gParam['order']= 'asc';
                // $res = controller("Customer", "lib")->getCustomerNumber($gParam);
                // $returnData['customer_number'] = $res;
                // $returnData = db('c_customerinfo')->where('customer_number',$res)->field('id,customer_number,customer_name,is_valid,is_success,customer_cource,customer_cource_id,customer_orderaddress,customer_orderaddress_id,marry_day,customer_name,customer_sex,customer_tel,customer_wechat,customer_birthday,mate_name,mate_sex,mate_tel,mate_wechat,mate_birthday,introducer_name,introducer_number,introducer_tel,province,province_id,city,city_id,county,county_id,customer_address,customer_channel_id,customer_channel,sales_staff,sales_staff_id,sales_staff_number,dj_day,yjd_action_day,c_star_day,last_trackday,order_start_time,c_from,syjd_day,is_intostore,order_number,dj_staff')->find();
                // return $returnData;
            }else if ($erp_order_type == 4) {
                $gParam['time'] = 'last_trackday';
                $gParam['order']= 'desc';
                // $res = controller("Customer", "lib")->getCustomerNumber($gParam);
                // $returnData['customer_number'] = $res;
                // $returnData = db('c_customerinfo')->where('customer_number',$res)->field('id,customer_number,customer_name,is_valid,is_success,customer_cource,customer_cource_id,customer_orderaddress,customer_orderaddress_id,marry_day,customer_name,customer_sex,customer_tel,customer_wechat,customer_birthday,mate_name,mate_sex,mate_tel,mate_wechat,mate_birthday,introducer_name,introducer_number,introducer_tel,province,province_id,city,city_id,county,county_id,customer_address,customer_channel_id,customer_channel,sales_staff,sales_staff_id,sales_staff_number,dj_day,yjd_action_day,c_star_day,last_trackday,order_start_time,c_from,syjd_day,is_intostore,order_number,dj_staff')->find();
                // return $returnData;
            }
            if ($gParam) {
                $contacts ='';
                if($contact_w){
                    $contacts .= $contacts?($contacts.',\''.$contact_w.'\''):('\''.$contact_w.'\'');
                }
                if($contact_m){
                    $contacts .= $contacts?($contacts.',\''.$contact_m.'\''):('\''.$contact_m.'\'');
                }

                $returnData = db('c_customerinfo')->field('id,customer_number,customer_name,is_valid,is_success,customer_cource,customer_cource_id,customer_orderaddress,customer_orderaddress_id,marry_day,customer_name,customer_sex,customer_tel,customer_wechat,customer_birthday,mate_name,mate_sex,mate_tel,mate_wechat,mate_birthday,introducer_name,introducer_number,introducer_tel,province,province_id,city,city_id,county,county_id,customer_address,customer_channel_id,customer_channel,sales_staff,sales_staff_id,sales_staff_number,dj_day,yjd_action_day,c_star_day,last_trackday,order_start_time,c_from,syjd_day,is_intostore,order_number,dj_staff')
                ->where('id in select (select cid from c_customer_contact where contact in ('.$contacts.') )')
                ->order($gParam['time'].' '.$gParam['order'])
                ->find();
                return $returnData;
            }


            // 如果两个手机号都存在
            if ($contact_w && $contact_m) {
                // 女士信息
                $isRepeatW['contact']      = $contact_w;
                $isRepeatW['brandclass_id']= $brandclass_id;
                $isRepeatW['brandclass']   = $brandclass;
                $resw = controller("index/Customer", "lib")->isRepeatCustomer($isRepeatW);
                // 男士信息
                $isRepeatM['contact']      = $contact_m;
                $isRepeatM['brandclass_id']= $brandclass_id;
                $isRepeatM['brandclass']   = $brandclass;
                $resm = controller("index/Customer", "lib")->isRepeatCustomer($isRepeatM);
                // var_dump($resm);
                // var_dump($resw);
                // exit;
                // 两个都不存在
                if (!$resw && !$resm) {
                    return array('customer_number' => '','customer_channel'=>'');
                }
                // 两个都存在
                else if ($resw && $resm) {
                    // 两个信息为同一个客资
                    if ($resw['id'] == $resm['id']) {
                        return $resw;
                    }
                    // 转订单时使用，另外一个客资的信息
                    $resm['asid']  = $resw['sales_staff_id'];
                    $resm['asname']= $resw['sales_staff'];
                    $resm['acid']  = $resw['id'];
                    $resm['acname']= $resw['customer_name'];
                    $resm['acsex'] = $resw['customer_sex'];
                    $resm['actel'] = $resw['customer_tel'];
                    
                    $resw['asid']    = $resm['sales_staff_id'];
                    $resw['asnumber']= $resm['sales_staff_number'];
                    $resw['acid']  = $resm['id'];
                    $resw['acname']= $resm['customer_name'];
                    $resw['acsex'] = $resm['customer_sex'];
                    $resw['actel'] = $resm['customer_tel'];

                    // 只有一个客资订单了，返回订单客资
                    if ($resw['is_success'] !=2 || $resw['is_success'] !=2) {
                        return $resw['is_success']!=2 ? $resw : $resm;
                    }

                    // 如果女士订单比男士订单早，返回女士订单
                    if ($resw['order_start_time'] || $resm['order_start_time']){ 
                        if ($resw['order_start_time'] > $resm['order_start_time']) {
                            return $resw;
                        }else{
                            return $resm;
                        }
                    }

                    // 都没有邀约记录，返回最后一次追踪过的客资信息
                    if( !$resw['yjd_action_day'] && !$resm['yjd_action_day'] ){
                        // 如果都没有，返回空，算新客资
                        if (!$resw['last_trackday'] && !$resm['last_trackday']) {
                            return array('customer_number' => '');
                        }else{
                            return $resw['last_trackday'] < $resm['last_trackday'] ? $resm : $resw;
                        }
                    }
                    // 都有邀约记录，返回邀约时间在30内的客资信息
                    else{
                        $tAgo = date('Y-m-d H:i:s',strtotime('-30 days'));
                        // var_dump($tAgo);
                        // var_dump($resw['yjd_action_day']);
                        // var_dump($resm['yjd_action_day']);
                        // exit;
                        // 女士信息的邀约时间  男士信息的邀约时间  都在 30天内 谁先邀约算谁的
                        if ($resw['yjd_action_day']>$tAgo && $resm['yjd_action_day']>$tAgo) {
                            // echo '1';
                            return $resw['yjd_action_day'] > $resm['yjd_action_day'] ? $resm : $resw ;
                        }
                        // 女士信息邀约时间在30天内，男士信息邀约时间超过30天
                        if ($resw['yjd_action_day']>$tAgo && $resm['yjd_action_day']<$tAgo) {
                            // echo '2';
                            return $resw;
                        }
                        // 男士信息邀约时间在30天内，女士信息邀约时间超过30天
                        if ($resm['yjd_action_day']>$tAgo && $resw['yjd_action_day']<$tAgo) {
                            // echo '3';
                            return $resm;
                        }
                        // 女士信息邀约时间超过30天，男士信息邀约时间超过30天
                        if ($resw['yjd_action_day']<$tAgo && $resm['yjd_action_day']<$tAgo) {
                            // echo '4';
                            // 返回最后一次追踪过的客资信息 如果都没有，返回空，算新客资
                            if (!$resw['last_trackday'] && !$resm['last_trackday']) {
                                return array('customer_number' => '');
                            }else{
                                return $resw['last_trackday'] < $resm['last_trackday'] ? $resm : $resw;
                            }
                        }
                    }
                }
                // 至少有一个存在
                else if ($resw && !$resm) {
                    return $resw;
                }else if (!$resw && $resm) {
                    return $resm;
                }
                // return $returnData;
            }
            // 只存在一个 联系方式
            else{
                if ($contact_w) {
                    // 女士信息
                    $isRepeatW['contact']      = $contact_w;
                    $isRepeatW['brandclass_id']= $brandclass_id;
                    $isRepeatW['brandclass']   = $brandclass;
                    $returnData = controller("index/Customer", "lib")->isRepeatCustomer($isRepeatW);
                }else{
                    // 男士信息
                    $isRepeatM['contact']      = $contact_m;
                    $isRepeatM['brandclass_id']= $brandclass_id;
                    $isRepeatM['brandclass']   = $brandclass;
                    $returnData = controller("index/Customer", "lib")->isRepeatCustomer($isRepeatM);
                }
                // 
                if ($returnData) {
                    return $returnData;
                }else{
                    return array('customer_number' => '','customer_channel'=>'');
                }
            }
        }
        // return $returnData;
    }
    /**
     * erp提报转介绍客资
     * 
     * @param  info                  客资信息(客资姓名-客资电话*客资姓名-客资电话)
     * @param  introducer_name       介绍人姓名
     * @param  introducer_ordernum   介绍人单号
     * @param  introducer_number     介绍人客资编号
     * @param  introducer_tel        介绍人电话
     * @param  dj_staff_id           提报人ID
     * @param  dj_staff              提报人
     * @param  brandclass_id         事业部id
     * @param  brandclass            事业部
     * @param  shop_code             客资接入店shop_code
     * @param  shop_name             客资接入店shop_name
     * @param  consultation_type_id  消费类型_id
     * @param  consultation_type     消费类型
     * 
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    public function erpAddCustomer($param){

        $dj_staff_id = (int)$param['dj_staff_id'];
        $staffInfo = getStaffInfoById($dj_staff_id);

        // 客户来源 门市提报：指名； 非门市：非营业
        if ($staffInfo['main_work_type'] == MS_WORK_TYPE) {
            $customer_cource_id= 5;
            $customer_cource   = '门市指名转介绍';
        }else{
            $customer_cource_id= 6;
            $customer_cource   = '非营业部转介绍';
        }

        $info = trim($param['info']);
        unset($param['info']);

        $info = explode('*',$info);
        $customerList = [];
        $eid = '-'.generate_code().$dj_staff_id;
        $eid = (int)$eid;
        $today = date('Y-m-d H:i:s');
        foreach ($info as $key => $value) {
            if (!$value) {
                continue;
            }
            $cInfo = explode('-',$value);
            
            $isRepeat = controller('crm/Customer','lib')->isRepeat($param['brandclass'],$cInfo[1]);
            if ($isRepeat['code']==200) {
                $customerList[$key]['eid']            = $eid;
                $customerList[$key]['customer_name']  = $cInfo[0];
                $customerList[$key]['customer_tel']   = $cInfo[1];
                $customerList[$key]['customer_number']= str_shuffle(time().generate_code());
                // 登记人相关
                $customerList[$key]['dj_staff']           = trim($param['dj_staff']);
                $customerList[$key]['tel_staff']          = trim($param['dj_staff']);
                $customerList[$key]['dj_staff_id']        = $dj_staff_id;
                $customerList[$key]['tel_staff_id']       = $dj_staff_id;
                $customerList[$key]['dj_staff_number']    = $staffInfo['staffnumber'];
                $customerList[$key]['add_shop_code']      = $staffInfo['shop_code'];
                $customerList[$key]['add_shop_name']      = $staffInfo['shop_name'];
                $customerList[$key]['customer_channel']   = $staffInfo['department_name'];
                $customerList[$key]['customer_channel_id']= $staffInfo['department_id'];
                $customerList[$key]['shop_code']          = $param['shop_code'];
                $customerList[$key]['shop_name']          = $param['shop_name'];
                $customerList[$key]['brandclass']         = $param['brandclass'];
                $customerList[$key]['brandclass_id']      = $param['brandclass_id'];
                // 介绍人相关
                $customerList[$key]['customer_type']      = 2;
                $customerList[$key]['introducer_type']    = 1;
                $customerList[$key]['introducer_name']    = $param['introducer_name'];
                $customerList[$key]['introducer_ordernum']= $param['introducer_ordernum'];
                $customerList[$key]['introducer_number']  = $param['introducer_number'];
                $customerList[$key]['introducer_tel']     = $param['introducer_tel'];
                // 消费类型
                $customerList[$key]['consultation_type_id']= $param['consultation_type_id'];
                $customerList[$key]['consultation_type']   = $param['consultation_type'];
                // 客户来源
                $customerList[$key]['customer_cource_id']  = $customer_cource_id;
                $customerList[$key]['customer_cource']     = $customer_cource;
                // 获取方式
                // $customerList[$key]['access_model_id']     = 
                // $customerList[$key]['access_model']        = 
                // 时间
                $customerList[$key]['yx_day']      = $today;
                $customerList[$key]['creator_day'] = $today;
                $customerList[$key]['create_time'] = $today;
                $customerList[$key]['dj_day']      = $today;
                $customerList[$key]['tel_time']    = $today;
                $customerList[$key]['is_first_tel']= 1;
            }else{
                $repeat[] = $cInfo[1];
            }
        }
        // exit;
        db()->startTrans();
        try {
            // 写入客资表
            db('c_customerinfo')->insertAll($customerList);
            // 写入联系方式表
            $cids = db('c_customerinfo')->master()->where('eid',$eid)->field('id,customer_tel,brandclass')->select();
            $contactList = [];
            foreach ($cids as $key => $value) {
                $contactList[$key]['c_id']      = $value['id'];
                $contactList[$key]['contact']   = trim($value['customer_tel']);
                $contactList[$key]['brandclass']= trim($value['brandclass']);
            }
            db('c_customer_contact')->insertAll($contactList);
            // 删除客资表中的-eid 
            db('c_customerinfo')->where('eid',$eid)->update(array('eid'=>NULL));

            // 是否开启筛客（不筛客），是否开启自动分配（开分配） push到自动分配队列
            $is_sk = controller('crm/Customer','lib')->is_sk($param['shop_code']);
            $sysconfig = db_config('fp_switch_'.$param['shop_code']);

            if ($is_sk!=1 && $sysconfig==1) {
                foreach ($contactList as $key => $value) {
                    $listName_fp = 'fpCustomerList';
                    $message_fp['receive']  = '-1';
                    $message_fp['body']     = $value['c_id'];
                    $message_fp['staff_id'] = $dj_staff_id;
                    $message_fp['shop_code']= trim($param['shop_code']);
                    push_list($listName_fp, $message_fp);
                }
            }
            db()->commit();
        } catch (\Exception $e) {
            db()->rollback();
            return array('msg' => '提报失败', 'code' => 100,'error'=>$e->getMessage());
        }
        // exit;
        // 查询这个介绍人介绍了几个客资
        if ($param['introducer_ordernum']) {
            $returnData['num'] = db('c_customerinfo')->master()->where('introducer_ordernum',$param['introducer_ordernum'])->count('id');
        }else{
            $returnData['num'] = 0;
        }
        $returnData['repeat'] = $repeat;
        unset($param);
        unset($staffInfo);
        unset($customerList);
        unset($contactList);
        return $returnData;
    }
    /**
     * erp右键标记之后，crm记录一次追踪记录
     * 
     * @param  customer_number       客资编号
     * @param  staff_name            操作人姓名
     * @param  shop_code             操作店
     * @param  shop_name             操作店
     * @param  sign_name             标记名称
     * @param  sign_time             操作时间
     */
    public function erpAddTrackinfo($param){
        $customer_number = trim($param['customer_number']);
        if (!$customer_number) {
            return array('error'=>1,'code'=>100,'msg'=>'操作失败，缺少参数：客资编号','data'=>$customer_number);
        }

        $cInfo = db('c_customerinfo')->where('customer_number',$customer_number)->field('id,customer_name,customer_number,customer_intention,customer_tel,consultation_type')->find();
        if (!$cInfo) {
            return array('error'=>1,'code'=>101,'msg'=>'客资不存在','data'=>$customer_number);
        }

        // 调mc接口
        $url = '5aec138a7bae9';
        $data['shop_code'] = $param['shop_code'];
        $data['key_words'] = $param['staff_name'];
        $res = sx_call($url,$data);

        if ($res['code'] == 200) {
            $param['sales_staff_id']    = $res['data'][0]['id'];
            $param['sales_staff_number']= $res['data'][0]['staffnumber'];
        }else{
            $param['sales_staff_id']    = '';
            $param['sales_staff_number']= '';
        }
        // 沟通方式(电话/微信/QQ/其他/门店),
        $sData['gtType']            = 5;
        $sData['customer_id']       = $cInfo['id'];
        $sData['customer_name']     = $cInfo['customer_name'];
        $sData['customer_number']   = $cInfo['customer_number'];
        $sData['sales_day']         = date('Y-m-d H:i:s');
        $sData['sales_staff']       = $param['staff_name'];
        $sData['sales_staff_id']    = $param['sales_staff_id'];
        $sData['sales_staff_number']= $param['sales_staff_number'];
        $sData['customer_intention']= $cInfo['customer_intention'];
        $sData['customer_tel']      = $cInfo['customer_tel'];
        $sData['sales_remark']      = trim( strip_tags($param['sign_name']).'('.date('Y-m-d', strtotime($param['sign_time'])).')' );
        $sData['consultation_type'] = $cInfo['consultation_type'];
        $sData['shop_name']         = $param['shop_name'];
        $sData['shop_code']         = $param['shop_code'];

        // var_dump($sData);exit;
        try {
            db('c_salestrackinginfo')->insert($sData);
            return array('code'=>200,'msg'=>'操作成功','data'=>$cInfo['customer_number']);
        } catch (\Exception $e) {
            return array('error'=>1,'code'=>102,'msg'=>'操作失败，请重试！','data'=>$e->getMessage());
        }
    }
    /*
     * 临时用  用于erp通知crm成单
     * $param  客资编号 customer_number
     * $param  单号     order_sn
     * $param  套系     total_money
     * $param  实收     fact_money
     * $param  订单时间  order_day
     * $param  门市     reception_name
     * $param  付款方式  pay_type
     * return  200 成功
     * */
    public function erpCallCrmCreateOrder($param){
        $cData['customer_number'] = trim($param['customer_number']);
        if(empty($cData['customer_number'])){
            return array('error'=>1,'code'=>101,'msg'=>'客资编号为空，无法定位客资');
        }

        if($param['reception_name']){
            $cData['reception_name'] = trim($param['reception_name']);
            $stroInfo = controller('crm/Customer','lib')->get_staff_list(['staffname'=>trim($param['reception_name'])]);
            if(!empty($stroInfo)){
                $cData['reception_id'] = $stroInfo[0]['id'];
            }else{
                $cData['reception_id'] = 0;
            }
        }
        $time = date('Y-m-d H:i:s');
        $cData['order_day'] = $param['order_day'] ? date('Y-m-d H:i:s',strtotime($param['order_day'])) : $time;
        $cData['order_number'] = trim($param['order_sn']);
        $cData['order_type'] = 2;
        $cData['totalpay_money'] = $param['total_money'] ? $param['total_money'] : 0;
        $cData['fact_money'] = $param['fact_money'] ? $param['fact_money'] : 0;

        $res = db('c_customerinfo')
            ->where('customer_number', trim($param['customer_number']))
            ->field('id,customer_number,customer_name,is_valid,is_success,is_intostore,syjd_day,customer_cource,customer_cource_id,customer_orderaddress,customer_orderaddress_id,marry_day,customer_name,customer_sex,customer_tel,customer_wechat,customer_birthday,mate_name,mate_sex,mate_tel,mate_wechat,mate_birthday,introducer_name,introducer_number,introducer_tel,province,province_id,city,city_id,county,county_id,customer_address,customer_channel_id,customer_channel,sales_staff,sales_staff_id,sales_staff_number,dj_day,yjd_action_day,c_star_day,last_trackday,order_start_time,brandclass,brandclass_id,order_number,shop_code,shop_name')
            ->order('id desc')
            ->find();

        if(empty($res)){
            return array('error'=>1,'code'=>102,'msg'=>'未通过客资编号法定位到客资');
        }
        /*//可以转多次订单的，
        if($res['order_number']){
            return array('error'=>1,'code'=>103,'msg'=>'此客资已经转过单');
        }*/
        $orderinfo = db('c_customer_order')->where('order_sn',$cData['order_number'])->find();
        if(!empty($orderinfo)){
            return array('error'=>1,'code'=>104,'msg'=>'此订单号已经存在');
        }
        // 客资订单信息
        $cData['order_start_time'] = $time;

        // 有效状态
        if ($res['is_valid'] != 1 && $res['is_valid'] != 3) {
            $cData['is_valid'] = 1;
            $cData['yx_day'] = $time;
        }
        // 进店状态
        if ($res['is_intostore'] != 2) {
            $cData['is_intostore'] = 2;
            if($res['is_intostore'] != 5 || !$res['syjd_day'])
            $cData['syjd_day'] = $time;
        }

        // 创建订单
        $oData['order_sn']          = $cData['order_number'];
        $oData['customer_id']       = $res['id'];
        $oData['customer_name']     = $res['customer_name'];
        $oData['consultation_type'] = $res['consultation_type'];
        $oData['target_time']       = $cData['order_day'];
        $oData['create_time']       = $time;
        $oData['order_fact']       = $cData['fact_money'];
        $oData['order_amount']       = $cData['totalpay_money'];
        $oData['shop_code']         = $res['shop_code'];
        $oData['shop_name']         = $res['shop_name'];
        $oData['order_type']        = 2;
        $oData['order_source']        = trim($param['pay_type']);
        $oData['brandclass_id']     = $res['brandclass_id'];
        $oData['brandclass']        = $res['brandclass'];
        $checkParam = [
            'brandclass_id' => $res['brandclass_id'],
            'fact_money'    => $param['fact_money'],
            'order_money'   => $param['total_money'],
        ];
        $result = controller('index/Customer', 'lib')->checkOrderValid($checkParam);
        //订单流水表
        $order = array(
            'order_sn' => $cData['order_number'],
            'pay_time' => date('Y-m-d',strtotime($param['order_day'])),
            'order_type' => 2,
            'order_fact' => $param['fact_money'],
            'two_pin_fact' => 0,
            'create_time' => $time,
            'pay_type'=>1
        );
        if($result){
            $oData['order_valid'] = 2;
            $order['order_valid'] = 2;
            $cData['is_success'] = 1;
        }else{
            $oData['order_valid'] = 1;
            $order['order_valid'] = 1;
            $cData['is_success'] = 3;
        }

        // 追踪数据
        $track['gtType'] = 5;
        $track['customer_id'] = $res['id'];
        $track['customer_name'] = $res['customer_name'];
        $track['customer_number'] = $res['customer_number'];
        $track['sales_day'] = date('Y-m-d H:i:s');
        $track['sales_staff'] = trim($res['sales_staff']);
        $track['sales_staff_id'] = trim($res['sales_staff_id']);
        $track['sales_remark'] = '临时ERP转订单';
        $track['shop_code'] = trim($res['shop_code']);
        db()->startTrans();
        try{
            db('c_customerinfo')->where('id', $res['id'])->update($cData);
            db('c_customer_order')->insert($oData);
            db('c_order_detail')->insert($order);
            db('c_salestrackinginfo')->insert($track);
            db()->commit();
            // 返回客资编号
            return array('code'=>200,'msg'=>'转订单成功','data'=>$res['customer_number']);
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>105,'msg'=>'转订单失败','data'=>$e->getMessage());
        }
    }
    /*
     * 预约进店 客资查询接口
     * @param brandclass_id   事业部ID
     * @param shop_codes      shop_codes（逗号分隔）
     * @param staff_ids       员工id（逗号分隔）
     * @param start           开始时间
     * @param end             结束时间
     * */
    public function getYjdCustomer($param) {
        $where['is_status'] = 1;
        if ((int)$param['brandclass_id']) {
            $where['is_status'] = (int)$param['brandclass_id'];
        }
        if ($param['shop_codes']) {
            $where['consulation_shop_code'] = ['in', $param['shop_codes']];
        }
        if ($param['staff_ids']) {
            $where['reception_id'] = ['in', $param['staff_ids']];
        }
        if ($param['start']) {
            $where['yjd_day'] = ['>', date('Y-m-d H:i:s', strtotime($param['start']) ) ];
        }
        if ($param['end']) {
            $where['yjd_day'] = ['<', date('Y-m-d H:i:s', strtotime($param['start']) ) ];
        }
        // var_dump($where);exit;

        $info = db('c_customerinfo')->where($where)->where('yjd_day', 'not null')->where('yjd_action_day', 'not null')
            ->field('id,customer_number,customer_name,customer_tel,customer_wechat,customer_qq,customer_birthday,mate_name,mate_tel,mate_wechat,mate_qq,mate_birthday,marry_day,province_id,province,city_id,city,county_id,county,customer_address,consultation_type_id,consultation_type,customer_cource_id,customer_cource,customer_channel_id,customer_channel,customer_intention_id,customer_intention,customer_orderaddress_id,customer_orderaddress,customer_area_id,customer_area,customer_remark,dj_staff,add_shop_name,sales_staff,shop_name,reception_name,consulation_shop,dj_day,yjd_action_day,yjd_day,syjd_day,is_intostore,is_success,order_start_time,order_day,order_number,fact_money,totalpay_money,brandclass_id')
            ->select();
        
        foreach ($info as $key => $value) {
            if ($value['is_intostore']) {
                $info[$key]['is_intostore'] = getIsIntostore($value['is_intostore']);
            }
            if ($value['is_success']) {
                $info[$key]['is_success'] = getIsSuccess($value['is_success']);
            }
        }
        $returnData['code'] = 200;
        $returnData['msg']  = 'success';
        $returnData['data'] = $info;
        unset($where,$info);
        return $returnData;
    }

    /*
     * 查询所有渠道名称接口
     * @param brandclass_id   事业部ID
     * @param shop_codes      shop_codes（逗号分隔）
     * @param staff_ids       员工id（逗号分隔）
     * */
    public function getAllChannel(){
        $where = [];
        // $where['brandclass_id'] = (int)$param['brandclass_id'];
        // $where['shop_code'] = (int)$param['shop_code'];
        $allChannel = db('s_channel')
            ->where($where)
            ->field('channel_class_name,channel_info_name,channel_name')
            ->order('channel_class_id asc,channel_info_id asc,order_sort asc')
            ->group('channel_name')
            ->select();
        return $allChannel;
    }
    /*
     * 分配接待人
     * @param id     进店表id  必填
     * @param consulation_shop_code        选填
     * @param consulation_shop  意向店面  选填
     * @param reception_id   必填
     * @param reception_name 选填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function allotReception($param){
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        if(empty($param['reception_id'])){
            return array('error'=>1,'code'=>101,'msg'=>'未获取到接待人id');
        }else{
            $data['reception_id'] = $param['reception_id'];
        }
        if(empty($param['reception_name'])){
            $staffinfo = getStaffInfoById($param['reception_id']);
            $reception_name = $staffinfo['staffname'];
        }

        $into = db('c_customer_intostore')->where('id',$param['id'])->find();

        $data['reception_name'] = $param['reception_name'] ? trim($param['reception_name']) : $reception_name;

        $data['consulation_shop_code'] = $param['consulation_shop_code']?trim($param['consulation_shop_code']) : ($into['consulation_shop_code']?$into['consulation_shop_code']:NULL);
        $data['consulation_shop'] = $param['consulation_shop']?trim($param['consulation_shop']) : ($into['consulation_shop_name'] ? $into['consulation_shop_name'] : NULL);

        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_tel,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code,reception_id,reception_name')->find();
        if(empty($info)){
            return array('error'=>1,'code'=>102,'msg'=>'未通过客资编号获取到客资信息');
        }
        $intostore = [
            'consulation_shop_code'=>$data['consulation_shop_code'],
            'consulation_shop_name'=>$data['consulation_shop_name'],
            'reception_id'=>$param['reception_id'],
            'reception_name'=>$data['reception_name'],
            'operate_id'=>$param['staff_id'],
            'operate_name'=>$param['staff_name'],
            'update_time'=>date('Y-m-d H:i:s'),
            'fp_rec_time'=>date('Y-m-d H:i:s'),
        ];

        db()->startTrans();
        try{
            db('c_customerinfo')->where('id',$into['cid'])->update($data);
            db('c_customer_intostore')->where('id',$param['id'])->update($intostore);
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $info['id'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = trim($info['sales_staff']);
            $track['sales_staff_id'] = trim($info['sales_staff_id']);
            $track['sales_remark'] = '客资标记';
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);

            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>$info['reception_name'] ? $info['reception_name'] : '',
                'data'=>'ERP分配接待人：'.$param['reception_name'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'allotReception',
            ];
            common_log($logData,'action_log');
            db()->commit();
            return $info;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>105,'msg'=>'分配接待人失败,原因：'.$e->getMessage());
        }
    }
    /*
     * 门市标记
     * @param id 进店id
     * @param op_signinfo   必填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function customerSign($param){
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->find();


        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code')->find();

        if(empty($info)){
            return array('error'=>1,'code'=>102,'msg'=>'未通过客资编号获取到客资信息');
        }
        db()->startTrans();
        try{
            db('c_customer_intostore')->where('id',$param['id'])->update(['op_signinfo'=>trim($param['op_signinfo']),'op_signday'=>date('Y-m-d H:i:s')]);
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $info['id'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = trim($info['sales_staff']);
            $track['sales_staff_id'] = trim($info['sales_staff_id']);
            $track['sales_remark'] = '客资标记：'.$param['op_signinfo'];
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>$into['op_signinfo'],
                'data'=>'客资标记：'.$param['op_signinfo'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'customerSign',
            ];
            common_log($logData,'action_log');
            db()->commit();
            return $info;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>105,'msg'=>'客资标记失败,原因：'.$e->getMessage());
        }
    }
    /*
      * 客资编辑
      * id   进店id
      * @staff_id
      * @staff_name             操作人
      * @param customer_name                选填
      * @param customer_tel                 选填
      * @param customer_sex                 选填
      * @param customer_wechat              选填
      * @param customer_qq                  选填
      * @param intostore_note  进店备注     选填
      * @param customer_birthday  客户生日  选填
      * @param consulation_shop_code        选填
      * @param consulation_shop_name  意向店面  选填
      * @param mate_name                    选填
      * @param mate_tel                     选填
      * @param mate_sex                     选填
      * @param mate_wechat                  选填
      * @param mate_qq                      选填
      * @param marry_day        结婚日期    选填
      * @param yp_day           预排日期    选填
      * @param customer_area_id             选填
      * @param customer_area   客户分区     选填
      * @param customer_cource_id           选填
      * @param customer_cource 客户来源     选填
      * */
    public function customerEdit($param){
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $field = 'id,';
        $update = [];
        $new_data = '';
        if($param['customer_name']){
            $field .= 'customer_name,';
            $update['customer_name'] = trim($param['customer_name']);
            $new_data .= '客资姓名：'.trim($param['customer_name']).'<br>';
        }
        if($param['customer_tel']){
            $field .= 'customer_tel,';
            $update['customer_tel'] = trim($param['customer_tel']);
            $new_data .= '客资手机：'.trim($param['customer_tel']).'<br>';
        }
        if($param['customer_sex']){
            $field .= 'customer_sex,';
            $update['customer_sex'] = trim($param['customer_sex']);
             $new_data .= '客资性别：'.trim($param['customer_sex']).'<br>';
        }
        if($param['customer_wechat']){
            $field .= 'customer_wechat,';
            $update['customer_wechat'] = trim($param['customer_wechat']);
             $new_data .= '客资微信：'.trim($param['customer_wechat']).'<br>';
        }
        if($param['customer_qq']){
            $field .= 'customer_qq,';
            $update['customer_qq'] = trim($param['customer_qq']);
            $new_data .= '客资qq：'.trim($param['customer_qq']).'<br>';
        }
        if($param['intostore_note']){
            $field .= 'intostore_note,';
            $update['intostore_note'] = trim($param['intostore_note']);
             $new_data .= '进店备注：'.trim($param['intostore_note']).'<br>';
        }
        if($param['customer_birthday']){
            $field .= 'customer_birthday,';
            $update['customer_birthday'] = date('Y-m-d',strtotime(trim($param['customer_birthday'])));
             $new_data .= '客资手机：'.trim($param['customer_tel']).'<br>';
        }
        if($param['mate_name']){
            $field .= 'mate_name,';
            $update['mate_name'] = trim($param['mate_name']);
             $new_data .= '配偶姓名：'.trim($param['mate_name']).'<br>';
        }
        if($param['mate_sex']){
            $field .= 'mate_sex,';
            $update['mate_sex'] = trim($param['mate_sex']);
            $new_data .= '配偶性别：'.trim($param['mate_sex_sex']).'<br>';
        }
        if($param['mate_tel']){
            $field .= 'mate_tel,';
            $update['mate_tel'] = trim($param['mate_tel']);
            $new_data .= '配偶手机：'.trim($param['mate_tel']).'<br>';
        }
        if($param['mate_wechat']){
            $field .= 'mate_wechat,';
            $update['mate_wechat'] = trim($param['mate_wechat']);
             $new_data .= '配偶微信：'.trim($param['mate_sex_wechat']).'<br>';
        }
        if($param['mate_qq']){
            $field .= 'mate_qq,';
            $update['mate_qq'] = trim($param['mate_qq']);
             $new_data .= '配偶qq：'.trim($param['mate_sex_qq']).'<br>';
        }
        if($param['mate_birthday']){
            $field .= 'mate_birthday,';
            $update['mate_birthday'] = date('Y-m-d',strtotime(trim($param['mate_birthday'])));
             $new_data .= '配偶生日：'.trim($param['mate_birthday']).'<br>';
        }
        if($param['marry_day']){
            $field .= 'marry_day,';
            $update['marry_day'] = trim($param['marry_day']);
            $update['marry_day'] = date('Y-m-d',strtotime(trim($param['marry_day'])));
             $new_data .= '结婚日期：'.date('Y-m-d',strtotime(trim($param['marry_day'])));
        }
        if($param['yp_day']){
            $field .= 'yp_day,';
            $update['yp_day'] = date('Y-m-d',strtotime(trim($param['yp_day'])));
             $new_data .= '预拍日期：'.date('Y-m-d',strtotime(trim($param['yp_day'])));
        }
        if($param['customer_area_id']){
            $field .= 'customer_area_id,';
            $update['customer_area_id'] = intval($param['customer_area_id']);
        }
        if($param['customer_area']){
            $field .= 'customer_area,';
            $update['customer_area'] = trim($param['customer_area']);
             $new_data .= '客资分区：'.trim($param['customer_area']).'<br>';
        }
        if($param['customer_cource_id']){
            $field .= 'customer_cource_id,';
            $update['customer_cource_id'] = intval($param['customer_cource_id']);
        }
        if($param['customer_cource']){
            $field .= 'customer_cource,';
            $update['customer_cource'] = trim($param['customer_cource']);
             $new_data .= '客资来源：'.trim($param['customer_cource']).'<br>';
        }

        $field = rtrim($field,',');
        $into = db('c_customer_intostore')->where('id',$param['id'])->find();
        $info = db('c_customerinfo')->where('id',$into['cid'])->field($field)->find();
        if(empty($info)){
            return array('error'=>1,'code'=>102,'msg'=>'未通过客资ID获取到客资信息');
        }
        $old_data = '';
        if($info['customer_name']){
            $old_data .= '客资姓名：'.trim($info['customer_name']).'<br>';
        }
        if($info['customer_tel']){
            $new_data .= '客资手机：'.trim($info['customer_tel']).'<br>';
        }
        if($info['customer_sex']){
            $old_data .= '客资性别：'.trim($info['customer_sex']).'<br>';
        }
        if($info['customer_wechat']){
            $old_data .= '客资微信：'.trim($info['customer_wechat']).'<br>';
        }
        if($info['customer_qq']){
            $old_data .= '客资qq：'.trim($info['customer_qq']).'<br>';
        }
        if($info['intostore_note']){
            $old_data .= '进店备注：'.trim($info['intostore_note']).'<br>';
        }
        if($info['customer_birthday']){
            $old_data .= '客资手机：'.trim($info['customer_tel']).'<br>';
        }
        if($info['mate_name']){
            $old_data .= '配偶姓名：'.trim($info['mate_name']).'<br>';
        }
        if($info['mate_sex']){
            $old_data .= '配偶性别：'.trim($info['mate_sex_sex']).'<br>';
        }
        if($info['mate_tel']){
            $old_data .= '配偶手机：'.trim($info['mate_tel']).'<br>';
        }
        if($info['mate_wechat']){
            $old_data .= '配偶微信：'.trim($info['mate_sex_wechat']).'<br>';
        }
        if($info['mate_qq']){;
            $update['mate_qq'] = trim($info['mate_qq']);
            $old_data .= '配偶qq：'.trim($info['mate_sex_qq']).'<br>';
        }
        if($info['mate_birthday']){
            $old_data .= '配偶生日：'.trim($info['mate_birthday']).'<br>';
        }
        if($info['marry_day']){
            $old_data .= '结婚日期：'.date('Y-m-d',strtotime(trim($info['marry_day'])));
        }
        if($info['yp_day']){
            $old_data .= '预拍日期：'.date('Y-m-d',strtotime(trim($info['yp_day'])));
        }
        if($info['customer_area']){
            $old_data .= '客资分区：'.trim($info['customer_area']).'<br>';
        }
        if($info['customer_cource']){
            $old_data .= '客资来源：'.trim($info['customer_cource']).'<br>';
        }
        db()->startTrans();
        try{
            db('c_customerinfo')->where('id',$into['cid'])->update($update);
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $info['id'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = trim($info['sales_staff']);
            $track['sales_staff_id'] = trim($info['sales_staff_id']);
            $track['sales_remark'] = '客资编辑';
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>$old_data,
                'data'=>$new_data,
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'customerEdit',
            ];
            common_log($logData,'action_log');
            db()->commit();
            return $info;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>105,'msg'=>'客资编辑失败,原因：'.$e->getMessage());
        }
    }
    /*
     * 领取礼品
     * @param id 进店id
     * @param giftinfo   礼品情况  必填
     * @param costs      礼品成本  选填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function gift($param){
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code')->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $inData = [];
        if($param['giftinfo']){
            $inData['giftinfo'] = trim($param['giftinfo']);
        }
        if($param['costs']){
            $inData['costs'] = trim($param['costs']);
        }
        $inData['update_time'] = date('Y-m-d H:i:s');
        db()->startTrans();
        try{
            db('c_customer_intostore')->where('id',$param['id'])->update($inData);
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $into['cid'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = ($param['staff_name']);
            $track['sales_staff_id'] = ($param['staff_id']);
            $track['sales_remark'] = '领取礼品:'.$param['giftinfo'];
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'领取礼品:'.$param['giftinfo'].';成本:'.$param['costs'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'gift',
            ];
            common_log($logData,'action_log');
            db()->commit();
            return $info;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>105,'msg'=>'领取礼品失败','data'=>$e->getMessage());
        }
    }
    /*
     * 流失
     * @param id 进店id
     * @param loss_reason   流失原因  必填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function loss($param){
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code,is_success')->find();
        if(empty($into)){
            return array('error'=>1,'code'=>102,'msg'=>'未通过进店ID获取到数据');
        }
        if($into['is_success'] == 1 || $into['is_success'] == 3){
            return array('error'=>1,'code'=>103,'msg'=>'已成单客资不能标记流失');
        }
        $inData = [];
        if($param['loss_reason']){
            $inData['loss_reason'] = $param['loss_reason'] ? trim($param['loss_reason']) : NULL;
        }
        $inData['sys_loss'] = 2;
        $inData['update_time'] = date('Y-m-d H:i:s');
        db()->startTrans();
        try{
            db('c_customer_intostore')->where('id',$param['id'])->update($inData);
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $into['cid'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = ($param['staff_name']);
            $track['sales_staff_id'] = ($param['staff_id']);
            $track['sales_remark'] = 'ERP标记流失'.$param['loss_reason'];
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'ERP标记流失:'.$param['loss_reason'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'loss',
            ];
            common_log($logData,'action_log');
            db()->commit();
            return $info;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>105,'msg'=>'标记流失失败','data'=>$e->getMessage());
        }
    }
    /*
     * 进客 进店非进客
     * @param id 进店id
     * @param is_intostore   进店  必填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function intostore($param){
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code,is_success,is_intostore,syjd_day')->find();
        if(empty($into)){
            return array('error'=>1,'code'=>102,'msg'=>'未通过进店ID获取到数据');
        }
        if($info['is_success'] == 1 || $info['is_success'] == 3){
            return array('error'=>1,'code'=>103,'msg'=>'已成单客资不能标记');
        }
        $inData = [];
        $cData = [];
        if($param['is_intostore'] == 5){
            $inData['loss_reason'] = trim($inData['loss_reason']);
            $inData['loss_time'] = date('Y-m-d H:i:s');
            $cData['is_intostore'] = $param['is_intostore'];
            $cData['syjd_day'] = date('Y-m-d H:i:s');
        }
        if($into['is_intostore'] < 5 && $param['is_intostore'] > 1){
            $cData['is_intostore'] = $param['is_intostore'];
            $cData['syjd_day'] = date('Y-m-d H:i:s');
            $inData['is_intostore'] = $param['is_intostore'];
            $inData['syjd_day'] = date('Y-m-d H:i:s');
        }
        $inData['update_time'] = date('Y-m-d H:i:s');
        db()->startTrans();
        try{
            db('c_customerinfo')->where('id',$into['cid'])->update($cData);
            db('c_customer_intostore')->where('id',$param['id'])->update($inData);
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $into['cid'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = ($param['staff_name']);
            $track['sales_staff_id'] = ($param['staff_id']);
            $track['sales_remark'] = '标记进客/非进客:'.$param['intostore'];
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'标记进客/非进客:'.$param['is_intostore'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'intostore',
            ];
            common_log($logData,'action_log');
            db()->commit();
            return $info;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>105,'msg'=>'标记失败','data'=>$e->getMessage());
        }
    }
    /*
     * 删除进店
     * @param id 进店id
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function deleteInto($param){
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code')->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $inData = [];
        $inData['status'] = 99;

        $inData['update_time'] = date('Y-m-d H:i:s');
        db()->startTrans();
        try{
            db('c_customer_intostore')->where('id',$param['id'])->update($inData);
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $into['cid'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = ($param['staff_name']);
            $track['sales_staff_id'] = ($param['staff_id']);
            $track['sales_remark'] = '删除进店';
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'删除进店',
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'deleteInto',
            ];
            common_log($logData,'action_log');
            db()->commit();
            return $info;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>105,'msg'=>'删除进店失败','data'=>$e->getMessage());
        }
    }
    /*
     * 回门
     * @param id 进店id                必填
     * @param reception_id             选填
     * @param reception_name   接待人  选填
     * @param consulation_shop_code   意向店面  选填
     * @param consulation_shop_name   意向店面  选填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function returnDoor($param){
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }

        if(date('Ymd',strtotime($into['yjd_day'])) >= date('Ymd')){
            return array('error'=>1,'code'=>102,'msg'=>'预约在今天或之后，不可回门');
        }
        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code')->find();
        if(empty($into)){
            return array('error'=>1,'code'=>103,'msg'=>'未通过进店ID获取到数据');
        }
        $inData = [];
        $cData = [];
        if($param['reception_id']){
            $inData['reception_id'] = intval($param['reception_id']);
        }
        if($param['reception_name']){
            $inData['reception_name'] = trim($param['reception_name']);
        }
        if($param['fp_rec_time']){
            $inData['fp_rec_time'] = ($param['fp_rec_time']);
        }
        if($into['consulation_shop_code']){
            $inData['consulation_shop_code'] = $param['consulation_shop_code'] ? trim($param['consulation_shop_code']) : trim($into['consulation_shop_code']);
            $cData['consulation_shop_code'] = $param['consulation_shop_code'] ? trim($param['consulation_shop_code']) : trim($into['consulation_shop_code']);
        }
        if($into['consulation_shop_name']){
            $inData['consulation_shop_name'] = trim($into['consulation_shop_name']);
            $cData['consulation_shop'] = trim($into['consulation_shop_name']);
        }
        if($into['operate_id']){
            $inData['operate_id'] = intval($param['staff_id']);
        }
        if($into['operate_name']){
            $inData['operate_name'] = trim($param['staff_name']);
        }
        if($into['op_signinfo']){
            $inData['op_signinfo'] = trim($param['op_signinfo']);
        }
        if($into['op_signday']){
            $inData['op_signday'] = trim($param['op_signday']);
        }
        if($into['giftinfo']){
            $inData['giftinfo'] = trim($param['giftinfo']);
        }
        if($into['costs']){
            $inData['costs'] = trim($param['costs']);
        }
        $inData['cid'] = $into['cid'];
        $inData['yjd_day'] = $param['yjd_day'] ? date('Y-m-d H:i:s',strtotime($param['yjd_day'])) : date('Y-m-d H:i:s');
        $inData['create_time'] = date('Y-m-d H:i:s');
        $inData['is_intostore'] = 2;
        $inData['reback'] = 2;


        $cData['yjd_day'] = $param['yjd_day'] ? date('Y-m-d H:i:s',strtotime($param['yjd_day'])) : date('Y-m-d H:i:s');
        $cData['yjd_action_day'] = date('Y-m-d H:i:s');
        db()->startTrans();
        try{
            db('c_customer_intostore')->where('id',$param['id'])->update($inData);
            db('c_customerinfo')->where('id',$into['cid'])->update($cData);
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $into['cid'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = ($param['staff_name']);
            $track['sales_staff_id'] = ($param['staff_id']);
            $track['sales_remark'] = '回门';
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'回门',
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'returnDoor',
            ];
            common_log($logData,'action_log');
            db()->commit();
            return  $info;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>109,'msg'=>'回门失败','data'=>$e->getMessage());
        }
    }
    /*
     * 客资列表
     * @param search_time    查询时间方式      选填
     * @param content    精确查询内容      选填
     * @param start    end    开始结束时间     选填
     * @param flag          查询标记     选填
     * @param reception_id   接待人id  选填
     * @param customer_intention_id   客户意向  选填
     * @param consulation_shop_code   意向店面  选填
     * @param consultation_type_id   消费类型  选填
     * @param customer_cource_id   客户来源  选填
     * @param dj_staff_id   客户来源  选填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function customerList($param){
        $where = [];
        if($param['search_time']){
            $param['search_time'] = 'i.'.$param['search_time'];
        }else{
            $param['search_time'] = 'i.yjd_day';
        }
        if($param['start']){
            $start = date('Y-m-d',strtotime($param['start']));
        }else{
            $start = date('Y-m-d');
        }
        if($param['end']){
            $end = date('Y-m-d 23:59:59',strtotime($param['end']));
        }else{
            $end = date('Y-m-d 23:59:59');
        }
        if($param['dj_staff_id']){
            $where['c.dj_staff_id'] = intval($param['dj_staff_id']);
        }
        if($param['reception_id']){
            $where['i.reception_id'] = intval($param['reception_id']);
        }
        if($param['consultation_type_id']){
            $where['c.consultation_type_id'] = intval($param['consultation_type_id']);
        }
        if($param['customer_cource_id']){
            $where['c.customer_cource_id'] = intval($param['customer_cource_id']);
        }
        if($param['customer_intention_id']){
            $where['c.customer_intention_id'] = intval($param['customer_intention_id']);
        }
        if($param['consulation_shop_code']){
            // $where['c.consulation_shop_code'] = trim($param['consulation_shop_code']);
            $where['i.consulation_shop_code'] = ['in',explode(',',$param['consulation_shop_code'])];
        }
        $sql = ' i.status = 1 ';
        if($param['flag'] == 1){
            $sql .= ' and (i.is_intostore=1 or i.is_intostore=4) ';
        }elseif($param['flag'] == 2){
            $sql .= ' and (i.is_success=1 or i.is_success=3) ';
        }elseif($param['flag'] == 3){
            $sql .= ' and (i.sys_loss=2  or i.is_intostore=5)';
        }
        if($param['content']){
            unset($where,$sql);
            $content = trim($param['content']);
            $sql = " c.customer_name like '%".$content."%' or c.customer_tel like '%".$content."%' or c.customer_number like '%".$content."%' ";
            $info = db('c_customer_intostore i')->join('c_customerinfo c','c.id=i.cid','LEFT')
                ->where($sql)
                ->field('i.*,c.*,i.id as id')
                ->order('i.yjd_day desc')
                ->select();
        }else{
            $info = db('c_customer_intostore i')->join('c_customerinfo c','c.id=i.cid','LEFT')
                ->where($sql)
                ->where($where)
                ->where($param['search_time'],'between',[$start,$end])
                ->field('i.*,c.*,i.id as id')
                ->order($param['search_time'].' desc')
                ->select();
        }
        return $info;
    }
    /*
      * 检查客资信息
      * @param customer_tel    男士手机号      选填
      * @param mate_tel        女生手机号      选填
      * @param branclass   事业部
      * @param staff_id   操作人id
      * @param staff_name 操作人
      * */
    public function checkCustomerRepeat($param){
        if(!$param['brandclass']){
            return array('error'=>1,'code'=>101,'msg'=>'未找到事业部');
        }
        if($param['customer_tel'] && $param['mate_tel']){
            $repeat = controller('crm/Customer','lib')->isRepeat($param['brandclass'],$param['customer_tel'],0,0,$param['mate_tel']);
            if($repeat['code'] != 200){
                $info = controller('index/Customer','lib')->checkCustomer($repeat['data']);
                return $info;
            }else{
                return array('code'=>200,'msg'=>'未重复客资');
            }
        }
        if($param['customer_tel']){
            $repeat = controller('crm/Customer','lib')->isRepeat($param['brandclass'],$param['customer_tel']);
            if($repeat['code'] != 200){
                $info = controller('index/Customer','lib')->checkCustomer($repeat['data']);
                return $info;
            }else{
                return array('code'=>200,'msg'=>'未重复客资');
            }
        }

        if($param['mate_tel']){
            $repeat = controller('crm/Customer','lib')->isRepeat($param['brandclass'],0,0,0,$param['mate_tel']);
            if($repeat['code'] != 200){
                $info = controller('index/Customer','lib')->checkCustomer($repeat['data']);
                return $info;
            }else{
                return array('code'=>200,'msg'=>'未重复客资');
            }
        }
    }
    /*
     * 新增客资
     * @param  brandclass_id         事业部id
     * @param  shop_code             shop_code
     * @param  staff_id              员工id
     * @param  staff_name            员工姓名
     * @param  create_time           创建时间 (y-m-d H:i:s)
     * @param  consultation_type     消费类型
     * @param  consultation_type_id  消费类型 id
     * @param  customer_cource       客户来源
     * @param  customer_cource_id    客户来源 id
     * @param  customer_area         客户分区
     * @param  customer_area_id      客户分区 id
     * @param  marry_day             结婚日期
     * @param  baby_birthday         宝宝生日
     * @param  wname                 女士姓名
     * @param  wphone                女士手机
     * @param  mname                 男士姓名
     * @param  mphone                男士手机
     * @param  wwechat               女士微信
     * @param  mwechat               男士微信
     * @param  wbirthday             女士生日
     * @param  mbirthday             男士生日
     * @param  introducer_name       介绍人姓名
     * @param  introducer_tel        介绍人电话
     * @param  province              省
     * @param  city                  市
     * @param  county                区/县
     * @param  customer_address      address
      * */
    public function createCustomer($param){
        $date = date('Y-m-d H:i:s');
        $staffInfo = getStaffInfoById($param['staff_id']);
        $create_time = $param['create_time'] ? date('Y-m-d H:i:s',strtotime($param['create_time'])) : $date;
        if (!$param['staff_name']) {
            $param['staff_name'] = $staffInfo['staffname'];
        }
        $data = [
            'brandclass_id'        => (int)$param['brandclass_id'],
            'brandclass'           => $staffInfo['brandclass'],
            'shop_code'            => $staffInfo['shop_code'],
            'shop_name'            => $staffInfo['shop_name'],
            'add_shop_code'        => $staffInfo['shop_code'],
            'add_shop_name'        => $staffInfo['shop_name'],
            'customer_number'      => str_shuffle(time().generate_code()),
            'customer_name'        => $param['wname'],
            'customer_tel'         => $param['wphone'],
            'customer_wechat'      => $param['wwechat'],
            'customer_sex'         => '女',
            'mate_name'            => $param['mname'],
            'mate_tel'             => $param['mphone'],
            'mate_wechat'          => $param['mwechat'],
            'mate_sex'             => '男',
            'marry_day'            => $param['marry_day'] ? date('Y-m-d H:i:s', strtotime($param['marry_day'])) : NULL,
            'ready_baby_day'       => $param['ready_baby_day']?date('Y-m-d H:i:s',strtotime($param['ready_baby_day'])):NULL,
            'consultation_type_id' => (int)$param['consultation_type_id'],
            'consultation_type'    => $param['consultation_type'],
            'customer_area_id'     => (int)$param['customer_area_id'],
            'customer_area'        => $param['customer_area'],
            'customer_cource_id'   => (int)$param['customer_cource_id'],
            'customer_cource'      => $param['customer_cource'],
            'c_from'               => 2,
            'is_intostore'         => 2,
            'syjd_day'             => $param['target_time']?$param['target_time']:$create_time,
            'creator_day'          => $create_time,
            'create_time'          => $create_time,
            'dj_day'               => $create_time,
            'dj_staff'             => $param['staff_name'],
            'dj_staff_id'          => $param['staff_id'],
            'dj_staff_number'      => $staffInfo['staffnumber'],
            'is_fp'                => 1,
            // 'sales_staff'          => $param['staff_name'],
            // 'sales_staff_id'       => $param['staff_id'],
            // 'sales_staff_number'   => $staffInfo['staffnumber'],
            'tel_staff_id'         => $param['staff_id'],
            'tel_staff'            => $staffInfo['staffname'],
            'tel_time'             => $create_time,
            'is_first_tel'         => 1,
            'wechat_staff_id'      => $param['mwechat'] ? $param['staff_id'] : '',
            'wechat_staff'         => $param['mwechat'] ? $param['staffname'] : '',
            'wechat_time'          => $param['mwechat'] ? $create_time : NULL,
            'is_first_wechat'      => $param['mwechat'] ? 1 : '',
            'customer_type'        => 1,
            'consulation_shop_code'=> $staffInfo['shop_code'],
            'consulation_shop'     => $staffInfo['shop_name'],
            'reception_id'         => $param['reception_id'] ? $param['reception_id'] : NULL,
            'reception_name'       => $param['reception_name'] ? $param['reception_name'] : NULL,
            'order_start_time'     => $param['target_time']?$param['target_time']:$create_time,
            'is_valid'             => 1,
            'yx_day'               => $param['target_time']?$param['target_time']:$create_time,
            'introducer_name'      => $param['introducer_name'],
            'introducer_tel'       => $param['introducer_tel'],
            'customer_birthday'    => $param['wbirthday'] ? date('Y-m-d H:i:s', strtotime($param['wbirthday'])) : NULL,
            'mate_birthday'        => $param['mbirthday'] ? date('Y-m-d H:i:s', strtotime($param['mbirthday'])) : NULL,
        ];

        //这条客资所有联系方式
        $contact=array();
        $contactList=array();
        if($data['customer_tel']){
            array_push($contact,$data['customer_tel']);
        }
        if($data['customer_wechat']){
            array_push($contact,$data['customer_wechat']);
        }
        if($data['mate_wechat']){
            array_push($contact,$data['mate_wechat']);
        }
        if($data['mate_tel']){
            array_push($contact,$data['mate_tel']);
        }
        $contact=array_unique($contact);

        db()->startTrans();
        try{
            $res = db('c_customerinfo')->insertGetId($data);
            foreach($contact as $k => $v){
                $contactList[$k]['c_id']=$res;
                $contactList[$k]['contact']=$v;
                $contactList[$k]['brandclass']=$data['brandclass'];
            }
            db('c_customer_contact')->insertAll($contactList);
            if($res){
                if($data['customer_tel']){
                    history_log(['customer_tel'=>$data['customer_tel']],[],$res,$data['dj_staff_id'],$data['dj_staff'],'crm','Customer','editCustomerTel');
                }
                //操作进店表
                $into = [
                    'cid'=>$res,
                    'syjd_day'=>$create_time,
                    'consulation_shop_code'=>$staffInfo['shop_code'] ? $staffInfo['shop_code'] : NULL,
                    'consulation_shop_name'=>$staffInfo['shop_name'] ? $staffInfo['shop_name'] : NULL,
                    'reception_id'         => $param['reception_id'] ? $param['reception_id'] : NULL,
                    'reception_name'       => $param['reception_name'] ? $param['reception_name'] : NULL,
                    'fp_rec_time'       => $create_time,
                    'operate_id'       => $param['staff_id'],
                    'operate_name'       => $param['staff_name'],
                    'is_intostore'       => 2,
                    'create_time'       => $create_time,
                ];
            }
            db('c_customer_intostore')->insert($into);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$res,
                'old_data'=>'',
                'data'=>'ERP创建客资编号：'.$date['customer_number'].',手机号:女号:'.$param['wphone'].';男号：'.$param['mphone'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'createCustomer',
            ];
            common_log($logData,'action_log');
            db()->commit();
            return $date;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>202,'msg'=>'创建客资失败','data'=>$e->getMessage());
        }
    }
    /*
      * 转单
      * @param id           进店表id      必填
      * @param order_sn        单号      必填
      * @param target_time   转单时间    选填
      * @param consulation_shop_code       选填
      * @param consulation_shop_name   意向店面    选填
      * @param reception_id                 选填
      * @param reception_name   接待人    选填
      * @param staff_id   操作人id
      * @param staff_name 操作人
      * */
    public function createNewOrder($param){
        $date = date('Y-m-d H:i:s');
        $target_time = $param['target_time'] ? date('Y-m-d H:i:s',strtotime($param['target_time'])) : $date;
        if(empty($param['order_sn'])){
            return array('error'=>1,'code'=>99,'msg'=>'未获取到订单号');
        }
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }

        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code,is_success,order_number,consulation_shop_code,consulation_shop,brandclass_id,brandclass,customer_orderaddress,customer_channel_id,customer_channel,consultation_type')->find();
        if(empty($into)){
            return array('error'=>1,'code'=>103,'msg'=>'未通过进店ID获取到客资数据');
        }

        $intostore = [
            'cid'=>$into['cid'],
            'syjd_day'=>$date,
            'consulation_shop_code'=>$param['consulation_shop_code'] ? $param['consulation_shop_code'] : ($info['consulation_shop_code'] ? $info['consulation_shop_code'] : NULL),
            'consulation_shop_name'=>$param['consulation_shop_name'] ? $param['consulation_shop_name'] :($info['consulation_shop_name']?$info['consulation_shop']:NULL),
            'reception_id'=>$param['reception_id'] ? $param['reception_id'] : ($info['reception_id']?$info['reception_id']:NULL),
            'reception_name'=>$param['reception_name'] ? $param['reception_name'] : ($info['reception_name']?$info['reception_name']:NULL),
            'operate_id'=>$param['staff_id'],
            'operate_name'=>$param['staff_name'],
            'is_intostore'=>2,
            'is_success'=>3,
            'update_time'=>$date,
        ];
        $order = [
            'order_sn' =>$param['order_sn'],
            'customer_id'=>$into['cid'],
            'customer_name'=>$info['customer_name'],
            'customer_channel_id'=>$info['customer_channel_id'],
            'customer_channel'=>$info['customer_channel'],
            'consultation_type'=>$info['consultation_type'],
            'create_time'=>$date,
            'customer_orderaddress'=>$info['customer_orderaddress'],
            'shop_code'=>$info['shop_code'],
            'shop_name'=>$info['shop_name'],
            'order_note'=>$param['order_note'],
            'target_time'=>$target_time,
            'brandclass_id'=>$info['brandclass_id'],
            'brandclass'=>$info['brandclass'],
            'into_id'=>$into['id']
        ];
        $cData = [
            'order_number'=>$param['order_sn'],
            'order_start_time'=>$date,
            'is_success'=>3,
        ];
        db()->startTrans();
        try{
            db('c_customerinfo')->where('id',$into['cid'])->update($cData);
            db('c_customer_order')->insert($order);
            db('c_customer_intostore')->where('id',$param['id'])->update($intostore);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$into['cid'],
                'old_data'=>'',
                'data'=>'ERP转单：'.$param['order_sn'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'createNewCustomer',
            ];
            common_log($logData,'action_log');
            db()->commit();
            return $info;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>109,'msg'=>'转单失败','data'=>$e->getMessage());
        }
    }
    /**
     * 根据客资ID 查询客资基本信息
     * 
     * @param  cid             客资id
     * 
     * @return array['id']               客资ID
     * @return array['customer_name']    客资姓名
     * @return array['customer_tel']     客资手机号
     * @return array['customer_wechat']  客资微信
     * @return array['mate_name']        配偶姓名
     * @return array['mate_tel']         配偶手机
     * @return array['mate_wechat']      配偶微信
     * @return array['province']         省
     * @return array['city']             市
     * @return array['county']           区
     * @return array['customer_address'] 详细地址
     * @return array['consultation_type']消费类型
     * @return array['customer_channel'] 渠道名称
     * @return array['is_valid']         是否有效（1有效 2待定 3无效 4驳回 5反驳回）
     * @return array['yx_day']           有效时间
     * @return array['is_intostore']     是否进店（1未进店 2进店进客 3进店非进客 4邀约未进店（爽约） 5 进店未成交（流失））
     * @return array['syjd_day']         进店时间
     * @return array['dj_staff']         登记人姓名
     * @return array['add_shop_name']    登记人所属店面
     * @return array['sales_staff']      追踪人姓名
     * @return array['shop_name']        追踪人所属店面
     * @return array['branclass']        归属事业部
     *
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getCusInfoById($param){
        $cid = (int)$paramp['cid'];

        if(!$cid){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到客资ID');
        }
        $column = 'id,customer_name,customer_tel,customer_wechat,mate_name,mate_tel,mate_wechat,province,city,county,customer_address,consultation_type,customer_channel,is_valid,yx_day,is_intostore,syjd_day,dj_staff,add_shop_name,sales_staff,shop_name,branclass';
        $cusInfo = db('c_customerinfo')->where('id',$id)->field($column)->find();

        if (!$cusInfo) {
            return array('error'=>1,'code'=>101,'msg'=>'未查询到客资信息，请确认。');
        }else{
            if ($cusInfo['is_status']!=1) {
                return array('error'=>1,'code'=>101,'msg'=>'未查询到客资信息，请确认。');
            }else{
                return array('code'=>200,'msg'=>'查询成功','data'=>$cusInfo);
            }
        }
    }
}

