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

use think\Exception;

class Child{

    /**
     * 根据联系方式，查询客资信息
     * 
     * @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('crm_c_customerinfo')
                ->where('customer_number', $customer_number)
                ->field('id,customer_number,baby_name,baby_sex,baby_birthday,customer_name,customer_tel,customer_wechat,customer_qq,customer_birthday,mate_name,mate_tel,mate_wechat,mate_qq,mate_birthday,marry_day,ready_baby_day,province,city,county,baby_address,customer_address,consultation_type,consultation_type_id,customer_cource,customer_cource_id,customer_intention,customer_intention_id,customer_orderaddress,customer_orderaddress_id,yjd_day,yp_day,introducer_name,introducer_ordernum,introducer_number,introducer_tel,sales_staff,sales_staff_id,sales_staff_number,dj_day,c_star_day,last_trackday,yjd_action_day,order_start_time，dj_staff_id,customer_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) {
                //     $res = check_tel($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']);

            $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("index/Child", "lib")->getCustomerNumber($gParam);
                if (!$res) {
                    return array('customer_number' => '');
                }
                $returnData = db('crm_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,dj_staff_id,customer_type')->find();
                return $returnData;
            }else if ($erp_order_type == 3) {
                $gParam['time'] = 'c_star_day';
                $gParam['order']= 'asc';
                $res = controller("index/Child", "lib")->getCustomerNumber($gParam);
                if (!$res) {
                    return array('customer_number' => '');
                }
                $returnData['customer_number'] = $res;
                $returnData = db('crm_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,dj_staff_id,customer_type')->find();
                return $returnData;
            }else if ($erp_order_type == 4) {
                $gParam['time'] = 'last_trackday';
                $gParam['order']= 'desc';
                $res = controller("index/Child", "lib")->getCustomerNumber($gParam);
                if (!$res) {
                    return array('customer_number' => '');
                }
                $returnData['customer_number'] = $res;
                $returnData = db('crm_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,dj_staff_id,customer_type')->find();
                return $returnData;
            }

            // 如果两个手机号都存在
            if ($contact_w && $contact_m) {
                // 母亲信息
                $isRepeatW['contact']      = $contact_w;
                $isRepeatW['brandclass_id']= $brandclass_id;
                $isRepeatW['brandclass']   = $brandclass;
                $resw = controller("index/Child", "lib")->isRepeatCustomer($isRepeatW);
                // 父亲信息
                $isRepeatM['contact']      = $contact_m;
                $isRepeatM['brandclass_id']= $brandclass_id;
                $isRepeatM['brandclass']   = $brandclass;
                $resm = controller("index/Child", "lib")->isRepeatCustomer($isRepeatM);
                // var_dump($resm);
                // var_dump($resw);
                // exit;
                // 两个都不存在
                if (!$resw && !$resm) {
                    return array('customer_number' => '');
                }
                // 两个都存在
                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/Child", "lib")->isRepeatCustomer($isRepeatW);
                }else{
                    // 父亲信息
                    $isRepeatM['contact']      = $contact_m;
                    $isRepeatM['brandclass_id']= $brandclass_id;
                    $isRepeatM['brandclass']   = $brandclass;
                    $returnData = controller("index/Child", "lib")->isRepeatCustomer($isRepeatM);
                }
                // 
                if ($returnData) {
                    return $returnData;
                }else{
                    return array('customer_number' => '');
                }   
            }
        }
        // return $returnData;
    }

    /**
     * 进客登记
     * 
     * @param  customer_number           客户编号
     * @param  brandclass_id             事业部id
     * @param  shop_code                 
     * @param  shop_name                 
     * @param  staff_id                  操作人id
     * @param  staff_name                操作人 new
     * @param  baby_name                 宝宝姓名
     * @param  baby_sex                  宝宝性别
     * @param  baby_birthday             宝宝生日
     * @param  baby_address              宝宝出生地
     * @param  customer_name             母亲姓名
     * @param  customer_tel              母亲手机
     * @param  customer_wechat           母亲微信
     * @param  customer_qq               母亲QQ
     * @param  customer_birthday         母亲生日
     * @param  mate_name                 父亲姓名
     * @param  mate_tel                  父亲手机
     * @param  mate_wechat               父亲微信
     * @param  mate_qq                   父亲QQ
     * @param  mate_birthday             父亲生日
     * @param  ready_baby_day            预产期
     * @param  marry_day                 结婚日期
     * @param  yp_day                    预拍日期
     * @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_orderaddress_id  接单点
     * @param  province                  省
     * @param  city                      市
     * @param  county                    区/县
     * @param  customer_address          客户地址
     * @param  customer_remark           客户备注
     *
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    public function createCustomer($param){
        // 客资编号
        $customer_number = $param['customer_number'];
        // 如果客资编号存在 根据传值修改客资信息
        if ($customer_number) {
            $res = $this->erpEditCustomer($param);
            return $res;
        }

        $customer_name = $param['customer_name'];
        // if(!check_tel($param['customer_tel'])){
        //     return array('error'=>1,'code'=>300,'msg'=>'手机格式错误','data'=>[]);
        // }

        $return = controller("index/Child","lib")->checkCustomer($param);
        // var_dump($return);
        // exit;
        // 客资不存在，录入到客资里
        $date = date('Y-m-d H:i:s');
        if (!$return) {
            $staffInfo = getStaffInfoById(intval($param['staff_id']));
            // print_r($staffInfo);
            // exit;
            $data = [
                'baby_name'            => trim($param['baby_name']),
                'baby_sex'             => trim($param['baby_sex']),
                'brandclass_id'        => (int)$param['brandclass_id'],
                'brandclass'           => $staffInfo['brandclass'],
                'shop_code'            => $param['shop_code'],
                'shop_name'            => $staffInfo['shop_name'],
                'add_shop_code'        => $param['shop_code'],
                'add_shop_name'        => $staffInfo['shop_name'],
                'customer_name'        => $customer_name,
                'customer_number'      => str_shuffle(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'   => 1,
                '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,
                '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'             => $param['staff_name'],
                'dj_staff_id'          => $param['staff_id'],
                'dj_staff_number'      => $staffInfo['staffnumber'],
                'tel_staff_id'         => $param['staff_id'],
                'tel_staff'            => $param['staff_name'],
                'tel_time'             => $date,
                'is_first_tel'         => 1,
                'wechat_staff_id'      => $param['customer_wechat'] ? $param['staff_id'] : '',
                'wechat_staff'         => $param['customer_wechat'] ? $param['staff_name'] : '',
                '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'] ? $param['staff_name'] : '',
                '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,
                'customer_remark'      => $param['customer_remark'] ? trim($param['customer_remark']) : NULL,
                'email'                => $param['email'] ? trim($param['email']) : NULL,
                'customer_address'     => $param['customer_address'] ? trim($param['customer_address']) : NULL,
            ];
            db()->startTrans();
            try {
                $res = db('crm_c_customerinfo')->insertGetId($data);
                $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'] = $date;
            }
            if(!empty($arr)){
                db()->startTrans();
                try {
                    db('crm_c_customerinfo')->where('id',$return['id'])->update($arr);
                    db()->commit();
                } catch (Exception $e) {
                    $return = array('error'=>1,'code'=>202,'msg'=>'操作失败，请重试！');
                    db()->rollback();
                }
            }
        }
        if ($param['is_in'] == 1) {
            $returnData = $return;
        }else{
            $returnData['customer_number'] = $return['customer_number'];
        }
        return $returnData;
    }

    /**
     *  修改客资信息
     * 
     * @param  customer_number           客户编号
     * @param  brandclass_id             事业部id
     * @param  shop_code                 
     * @param  shop_name                 
     * @param  staff_id                  操作人id
     * @param  staff_name                操作人 new
     * @param  baby_name                 宝宝姓名
     * @param  baby_sex                  宝宝性别
     * @param  baby_birthday             宝宝生日
     * @param  baby_address              宝宝出生地
     * @param  customer_name             母亲姓名
     * @param  customer_tel              母亲手机
     * @param  customer_wechat           母亲微信
     * @param  customer_qq               母亲QQ
     * @param  customer_birthday         母亲生日
     * @param  mate_name                 父亲姓名
     * @param  mate_tel                  父亲手机
     * @param  mate_wechat               父亲微信
     * @param  mate_qq                   父亲QQ
     * @param  mate_birthday             父亲生日
     * @param  ready_baby_day            预产期
     * @param  marry_day                 结婚日期
     * @param  yp_day                    预拍日期
     * @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_orderaddress_id  接单点
     * @param  province                  省
     * @param  city                      市
     * @param  county                    区/县
     * @param  customer_address          客户地址
     * @param  customer_remark           客户备注
     *
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    
    public function erpEditCustomer($param){
        // 如果存在客资编号
        if ( trim($param['customer_number']) ) {
            $cInfo = db('crm_c_customerinfo')
                ->where('customer_number', $param['customer_number'])
                ->field('id,customer_number,consultation_type,consultation_type_id,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,baby_name,baby_sex')
                ->find();
            if (!$cInfo) {
                return array('code'=>202,'msg'=>'客资不存在');
            }
            // 更新客资表 地区
            if ( trim($param['province']) && trim($param['province']) != $cInfo['province'] ) {
                $cData['province'] = trim($param['province']);
                $cData['province_id'] = db('crm_s_address')->where('name', $param['province'])->value('id');
            }
            if ( trim($param['city']) && trim($param['city']) != $cInfo['city'] ) {
                $cData['city'] = trim($param['city']);
                $cData['city_id'] = db('crm_s_address')->where('name', $param['city'])->value('id');
            }
            if ( trim($param['county']) && trim($param['county']) != $cInfo['county'] ) {
                $cData['county'] = trim($param['county']);
                $cData['county_id'] = db('crm_s_address')->where('name', $param['county'])->value('id');
            }
            if ( $param['customer_address'] && $param['customer_address'] != $cInfo['customer_address'] ) {
                $cData['customer_address'] = strip_tags($param['customer_address']);
            }
            // 消费类型
            if ($cInfo['consultation_type_id'] != (int)$param['consultation_type_id'] && (int)$param['consultation_type_id']) {
                $cData['consultation_type_id']= (int)$param['consultation_type_id'];
                $cData['consultation_type']   = $param['consultation_type'];
            }
            // 客户分区
            if ($cInfo['customer_area_id'] != (int)$param['customer_area_id'] && (int)$param['customer_area_id']) {
                $cData['customer_area_id']= (int)$param['customer_area_id'];
                $cData['customer_area']   = $param['customer_area'];
            }
            // 接单点
            if ($cInfo['customer_orderaddress_id'] != (int)$param['customer_orderaddress_id'] && (int)$param['customer_orderaddress_id']) {
                $cData['customer_orderaddress_id']= (int)$param['customer_orderaddress_id'];
                $cData['customer_orderaddress']   = $param['customer_orderaddress'];
            }
            // 结婚日期
            if ( $param['marry_day'] && $cInfo['marry_day'] != date('Y-m-d',strtotime($param['marry_day']))) {
                $cData['marry_day'] = date('Y-m-d',strtotime($param['marry_day']));
            }
            // 介绍人
            if ( $param['introducer_name'] && $cInfo['introducer_name'] != $param['introducer_name'] ) {
                $cData['introducer_name'] = trim($param['introducer_name']);
            }
            if ( $param['introducer_tel'] && $cInfo['introducer_tel'] != $param['introducer_tel'] ) {
                $cData['introducer_tel'] = trim($param['introducer_tel']);
            }
            if ( $param['introducer_number'] && $cInfo['introducer_number'] != $param['introducer_number'] ) {
                $cData['introducer_number'] = trim($param['introducer_number']);
            }
            if ( $param['introducer_ordernum'] && $cInfo['introducer_ordernum'] != $param['introducer_ordernum'] ) {
                $cData['introducer_ordernum'] = trim($param['introducer_ordernum']);
            }
            // erp传过来的母亲手机号
            if ( $param['wphone'] && $cInfo['erp_wphone'] != $param['wphone'] ) {
                $cData['erp_wphone'] = $param['wphone'];
            }
            // erp传过来的父亲手机号
            if ( $param['mphone'] && $cInfo['erp_mphone'] != $param['mphone'] ) {
                $cData['erp_mphone'] = $param['mphone'];
            }
            // 客资性别为男
            if ($cInfo['customer_sex'] == '男') {
                // 客资信息
                if ($param['mname'] && $param['mname'] != $cInfo['customer_name']) {
                    $cData['customer_name'] = $param['mname'];
                }
                if ($param['mwechat'] && $param['mwechat'] != $cInfo['customer_wechat']) {
                    $cData['customer_wechat'] = $param['mwechat'];
                }
                if ($param['mbirthday'] && $param['mbirthday'] != $cInfo['customer_birthday']) {
                    $cData['customer_birthday'] = $param['mbirthday'];
                }

                // 配偶信息
                if ($param['wname'] && $param['wname'] != $cInfo['mate_name']) {
                    $cData['mate_name'] = $param['wname'];
                }
                if ($param['wwechat'] && $param['wwechat'] != $cInfo['customer_wechat']) {
                    $cData['mate_wechat'] = $param['wwechat'];
                }
                if ($param['wbirthday'] && $param['wbirthday'] != $cInfo['customer_birthday']) {
                    $cData['mate_birthday'] = $param['wbirthday'];
                }
                if ($param['wname'] || $param['wwechat'] || $param['wphone'] || $param['wbirthday']) {
                    $cData['mate_sex'] = '女';
                }
            }else{
                if ($param['wname'] || $param['wwechat'] || $param['wphone'] || $param['wbirthday']) {
                    $cData['customer_sex'] = '女';
                }
                if ($param['mname'] || $param['mwechat'] || $param['mphone'] || $param['mbirthday']) {
                    $cData['mate_sex'] = '男';
                }
                if ($param['wname'] && $param['wname'] != $cInfo['customer_name']) {
                    $cData['customer_name'] = $param['wname'];
                }
                if ($param['wwechat'] && $param['wwechat'] != $cInfo['customer_wechat']) {
                    $cData['customer_wechat'] = $param['wwechat'];
                }
                if ($param['wbirthday'] && $param['wbirthday'] != $cInfo['customer_birthday']) {
                    $cData['customer_birthday'] = $param['wbirthday'];
                }

                if ($param['mname'] && $param['mname'] != $cInfo['mate_name']) {
                    $cData['mate_name'] = $param['mname'];
                }
                if ($param['mwechat'] && $param['mwechat'] != $cInfo['mate_wechat']) {
                    $cData['mate_wechat'] = $param['mwechat'];
                }
                if ($param['mbirthday'] && $param['mbirthday'] != $cInfo['mate_birthday']) {
                    $cData['mate_birthday'] = $param['mbirthday'];
                }
            }

            // 如果母亲手机号存在 且和  客资、配偶 手机号不一样
            if ($param['wphone'] && $param['wphone'] != $cInfo['customer_tel'] && $param['wphone'] != $cInfo['mate_tel']) {
                $cData['mate_tel'] = $param['wphone'];
            }else if ($param['mphone'] && $param['mphone'] != $cInfo['customer_tel'] && $param['mphone'] != $cInfo['mate_tel']) {
                $cData['mate_tel'] = $param['wphone'];
            }
            //宝宝信息
            if($param['baby_name'] && $param['baby_name'] != $cInfo['baby_name']){
                $cData['baby_name'] = $param['baby_name'];
            }
            if($param['baby_sex'] && $param['baby_sex'] != $cInfo['baby_sex']){
                $cData['baby_sex'] = $param['baby_sex'];
            }
            $cData['update_time'] = date('Y-m-d H:i:s');
            db('crm_c_customerinfo')->where('id', $cInfo['id'])->update($cData);
            // 记录日志
            history_log($cData,$cInfo,$cInfo['id'],$param['staff_id'],$param['staff_name'],'index','customer','erpEditCustomer');
            // 返回客资编号
            $returnData['customer_number'] = $cInfo['customer_number'];
            return $returnData;
        }else{
            return array('code'=>201,'msg'=>'请输入客资编号。');
        }
    }

    /**
     * 客资状态修改（进店进客，进店非进客，未进店，流失）
     * 
     * @param  code             1:进店进客；2：进店非进客；3：未进店；4：流失
     * @param  create_time      进店时间/标记时间
     * @param  lose_reason      流失原因
     * @param  customer_number  客资编号
     * @param  retail_sales     门市人员
     * @param  m_tel            父亲手机号
     * @param  w_tel            母亲手机号
     *
     * @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']));
        $return = [];

        switch ($param['code']) {
            case '1':
                $data['is_intostore'] = 2;
                $data['syjd_day']     = $param['create_time'];
                break;
            case '2':
                $data['is_intostore'] = 3;
                $data['syjd_day']     = $param['create_time'];
                break;
            case '3':
                $data['is_intostore'] = 1;
                break;
            case '4':
                $data['erp_loss']       = 2;
                $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['customer_number']) {
            $where['customer_number'] = $param['customer_number'];
            $cInfo = db('crm_c_customerinfo')->where($where)->field('id,customer_name,is_intostore,sales_staff,sales_staff_id')->find();
            // 如果客资没有进店 标记流失时，标记进店
            if ($cInfo['is_intostore'] == 1) {
                $data['is_intostore'] = 2;
                $data['syjd_day']     = $param['create_time'];
            }
            // $where['id'] = $cInfo['id'];
        }else{
            // 排重客资
            $brandclass_id = (int)$param['brandclass_id'];
            $brandclassInfo = $this->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('crm_c_customerinfo')->where($where)->field('id,customer_name,is_intostore,sales_staff,sales_staff_id')->find();
                // 如果客资没有进店 标记流失时，标记进店
                if ($cInfo['is_intostore'] == 1) {
                    $data['is_intostore'] = 2;
                    $data['syjd_day']     = $param['create_time'];
                }
                // $where['id'] = $cInfo['id'];
            }            
        }
        // 发送站内弹窗消息
        $messageD['send_type']      = 1;
        $messageD['send_time']      = $param['create_time'];
        $messageD['send_title']     = '标记提醒';

        // 客资进店
        if ($param['code'] == 1 || $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_id']     = $cInfo['sales_staff_id'];
        $messageD['receive_name']   = $cInfo['sales_staff'];
        $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;
        sendSystemMessage($messageD);

        // 开启事务
        db()->startTrans();
        try {
            db('crm_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()->commit();
            $return = $data;
        } catch (Exception $e) {
            $return = array('error'=>1,'code'=>201,'msg'=>'修改失败，请重试！');
            db()->rollback();
        }

        return $return;
    }

    /**
     * 开单，添加消费产品，收款操作
     * 开单：新增订单，一销，二销，和总额都是0
     * 添加消费产品：总额不为0，一销二销为0
     * 收款：一销二销其中一个不为0，总额都不为0
     * @param string $param 要加密的字符串
     * $param 包含下列字段:
     * diff         1:开单；2：添加消费产品；3：收款
     * create_time          订单创建时间
     * m_tel                男手机号
     * w_tel                女手机号
     * order_sn             订单号
     * order_valid          订单有效状态（1：无效；2：有效）
     * order_fact           一销实收
     * order_amount         一销总额
     * two_pin_fact         二销实收
     * two_pin_amount       二销总额
     * customer_number      customer_number
     * consultation_type    消费类型
     * brandclass_id        事业部id
     * brandclass
     * shop_name
     * shop_code
     * @return array
     */
    public function receivables($param){
        // 开单
        if($param['diff'] == 1) {
            $res = $this->createOrder($param);
            return $res;
        }
        // 添加消费项目
        else if ($param['diff'] == 2) {
            $res = $this->addOrderTotal($param);
            return $res;
        }
        // 收款
        else if ($param['diff'] == 3) {
            $res = $this->cashMoney($param);
            return $res;
        }
        // 错误的 diff code
        else{
            return array('error'=>1,'code'=>100,'msg'=>'参数有误','data'=>'');
        }
    }

    /**
     * 门市创建新订单
     * 
     * @param  customer_number           客户编号
     * @param  brandclass_id             事业部id
     * @param  shop_code                 
     * @param  shop_name                 
     * @param  staff_id                  操作人id
     * @param  staff_name                操作人 new
     * @param  order_sn                  订单编号 
     * @param  create_time               创建时间 (y-m-d H:i:s)
     * @param  baby_name                 宝宝姓名
     * @param  baby_sex                  宝宝性别
     * @param  baby_birthday             宝宝生日
     * @param  baby_address              宝宝出生地(医院)
     * @param  customer_name             母亲姓名
     * @param  customer_tel              母亲手机
     * @param  customer_wechat           母亲微信
     * @param  customer_qq               母亲QQ        ??
     * @param  customer_birthday         母亲生日
     * @param  mate_name                 父亲姓名
     * @param  mate_tel                  父亲手机
     * @param  mate_wechat               父亲微信
     * @param  mate_qq                   父亲QQ        ??
     * @param  mate_birthday             父亲生日
     * @param  ready_baby_day            预产期
     * @param  marry_day                 结婚日期
     * @param  yp_day                    预拍日期
     * @param  home_phone                座机
     * @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_orderaddress_id  接单点
     * @param  province                  省
     * @param  city                      市
     * @param  county                    区/县
     * @param  customer_address          客户地址
     * @param  customer_remark           客户备注
     *
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    
    public function createOrder($param){

        $target_time = date('Y-m-d H:i:s',strtotime($param['create_time']));
        $param['create_time'] = date('Y-m-d H:i:s',time());

        $brandclass_id = (int)$param['brandclass_id'];
        $brandclassInfo= controller('index/Child','lib')->getBrandClassInfo($brandclass_id);
        $brandclass    = $brandclassInfo['brandclass'];
        // 如果存在客资编号
        if ($param['customer_number']) {
            $res = db('crm_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,baby_name,baby_sex,dj_staff_id,customer_type')
                ->find();
            // 更新客资表 地区
            if (trim($param['province'])) {
                $cData['province'] = trim($param['province']);
                $cData['province_id'] = db('crm_s_address')->where('name', $param['province'])->value('id');
            }
            if (trim($param['city'])) {
                $cData['city'] = trim($param['city']);
                $cData['city_id'] = db('crm_s_address')->where('name', $param['city'])->value('id');
            }
            if (trim($param['county'])) {
                $cData['county'] = trim($param['county']);
                $cData['county_id'] = db('crm_s_address')->where('name', $param['county'])->value('id');
            }
            $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'];
            }
            // 进店状态
            if ($res['is_intostore'] != 2) {
                $cData['is_intostore'] = 2;
                $cData['syjd_day'] = $param['create_time'];
            }
            // 消费类型
            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'];
            }

            if ($param['customer_tel']) {
                $cData['erp_wphone'] = $param['customer_tel'];
            }
            if ($param['mate_tel']) {
                $cData['erp_mphone'] = $param['mate_tel'];
            }
            if($param['order_amount']){
                $cData['totalpay_money'] = $param['order_amount'];
            }
            $cData['update_time'] = $param['create_time'];
            db('crm_c_customerinfo')->where('id', $res['id'])->update($cData);

            // 创建订单
            $oData['order_sn']          = $param['order_sn'];
            $oData['customer_id']       = $res['id'];
            $oData['customer_name']     = $res['customer_name'];
            $oData['consultation_type'] = $res['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']        = $param['brandclass'];
            db('crm_c_customer_order')->insert($oData);
            //如果是转介绍客资，向登记人发消息
            if($res['customer_type']== 2){
                $content = [
                    'touser'       => $res['dj_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'=>date('Y-m-d H:i:s'),
                            'color'=>'#173177'
                        ],
                        'remark'=>[
                            'value'=>'请尽快查看，谢谢',
                            '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']);
        if ($erp_order_type == 2) {
            $param['erp_order_type'] = 2;
            $res = controller("Child", "lib")->createOrderByType($param);
            $returnData['customer_number'] = $res;
            return $returnData;
        }else if ($erp_order_type == 3) {
            $param['erp_order_type'] = 3;
            $res = controller("Child", "lib")->createOrderByType($param);
            $returnData['customer_number'] = $res;
            return $returnData;
        }else if ($erp_order_type == 4) {
            $param['erp_order_type'] = 4;
            $res = controller("Child", "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);

        $iData['brandclass_id']= $brandclass_id;
        $iData['brandclass']   = $brandclass;
        $iData['contact_type'] = 1;
        $iData['contact_w']    = $param['customer_tel'];
        $iData['contact_m']    = $param['mate_tel'];
        
        $res = $this->getCustomerInfomation($iData);
        // var_dump($res);exit;
        // 返回空创建客资及订单
        if (empty($res['customer_number'])) {
            $res = controller("index/Child", "lib")->createCustomer($param);
            // 创建订单
            $oData['order_sn']          = $param['order_sn'];
            $oData['customer_id']       = $res['id'];
            $oData['customer_name']     = $res['customer_name'];
            $oData['consultation_type'] = $res['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']     = $res['brandclass_id'];
            $oData['brandclass']        = $res['brandclass'];
            db('crm_c_customer_order')->insert($oData);
            //如果是转介绍客资，向登记人发消息
            if($res['customer_type']== 2){
                $content = [
                    'touser'       => $res['dj_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'=>date('Y-m-d H:i:s'),
                            'color'=>'#173177'
                        ],
                        'remark'=>[
                            'value'=>'请尽快查看，谢谢',
                            '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;
                $cData['syjd_day'] = $param['create_time'];
            }
            
            // 母亲信息为客资信息
            if ($res['customer_tel'] == $param['customer_tel']) {
                // 客资信息
                if ($res['customer_sex'] != '女') {
                    $cData['customer_sex']   = '女';
                }                
                if ($res['customer_name'] != $param['customer_name'] && $param['customer_name']) {
                    $cData['customer_name']  = $param['customer_name'];
                }
                if ($res['customer_wechat'] != $param['customer_wechat'] && $param['customer_wechat']) {
                    $cData['customer_wechat']  = $param['customer_wechat'];
                }
                // 配偶信息
                if ($res['mate_sex'] != '男') {
                    $cData['mate_sex'] = '男';
                }                
                if ($res['mate_name'] != $param['mate_name'] && $param['mate_name']) {
                    $cData['mate_name']  = $param['mate_name'];
                }
                if ($res['mate_wechat'] != $param['mate_wechat'] && $param['mate_wechat']) {
                    $cData['mate_wechat']  = $param['mate_wechat'];
                }
            }
            // 父亲信息为客资信息
            else if ($res['customer_tel'] == $param['mate_tel']) {
                // 客资信息
                if ($res['customer_sex'] != '男') {
                    $cData['customer_sex']   = '男';
                }                
                if ($res['customer_name'] != $param['mate_name'] && $param['mate_name']) {
                    $cData['customer_name']  = $param['mate_name'];
                }
                if ($res['customer_wechat'] != $param['mate_wechat'] && $param['mate_wechat']) {
                    $cData['customer_wechat']  = $param['mate_wechat'];
                }
                // 配偶信息
                if ($res['mate_sex'] != '女') {
                    $cData['mate_sex'] = '女';
                }                
                if ($res['mate_name'] != $param['customer_name'] && $param['customer_name']) {
                    $cData['mate_name']  = $param['customer_name'];
                }
                if ($res['mate_wechat'] != $param['customer_wechat'] && $param['customer_wechat']) {
                    $cData['mate_wechat']  = $param['customer_wechat'];
                }
            }
            // 消费类型
            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'];
            }
            
            db('crm_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['brandclass_id']      = $param['brandclass_id'];
                $oData['brandclass']         = $brandclassInfo['brandclass'];
                db('crm_c_customer_order')->insert($oData);
            }
            // var_dump($res['asid']);
            // exit;
            // 如果存在第二个追踪人
            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'].'，请查收。';
                $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'].'，请查收。';
                $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);
                //如果是转介绍客资，向登记人发消息
                if($res['customer_type']== 2){
                    $content = [
                        'touser'       => $res['dj_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'=>date('Y-m-d H:i:s'),
                                'color'=>'#173177'
                            ],
                            'remark'=>[
                                'value'=>'请尽快查看，谢谢',
                                'color'=>'#173177'
                            ]
                        ]
                    ];
                    $send_data['content'] = json_encode($content);
                    sendMsg($send_data);
                }
            }
            return $returnData;
        }
    }

    /**
     * 添加消费产品：套系总额
     * @param  
     * @param  order_sn              订单编号
     * @param  order_amount          一销总额
     * @param  two_pin_amount        二销总额
     * 
     * @return array
     */
    public function addOrderTotal($param){
        $orderInfo = $this->checkOrder(['order_sn'=>$param['order_sn']]);
        if($orderInfo['error'] == 1){
            return array('error'=>1,'code'=>100,'msg'=>'订单不存在。','data'=>'');
        }
        try{

            //修改订单表信息
            db()->startTrans();
            $arr = array(
                'order_sn'       => $orderInfo['order_sn'],
                'customer_id'    => $orderInfo['customer_id'],
                'customer_name'  => $orderInfo['customer_name'],
                'order_amount'   => $param['order_amount'],
                'two_pin_amount' => $param['two_pin_amount'],
                'update_time'    => $param['create_time']?date('Y-m-d H:i:s',strtotime($param['create_time'])):date('Y-m-d H:i:s'),
            );
            $ord = controller('index/Child','lib')->updateCustomerOrder($arr);
            //修改客资表套系金额
            $customerData = [
                'id'=>$orderInfo['customer_id'],
                'totalpay_money'=>$param['two_pin_amount']+$param['order_amount'],
                'order_number'=> $orderInfo['order_sn'],
            ];
            $cusInfo = db('crm_c_customerinfo')->where('id',$orderInfo['customer_id'])->field('is_intostore,is_valid,order_number')->find();
            if($cusInfo['is_intostore'] != 2){
                $customerData['is_intostore'] = 2;
                $customerData['syjd_day'] = date('Y-m-d H:i:s',time());
            }
            /*if($cusInfo['is_valid'] != 1){
                $customerData['is_valid'] = 1;
                $customerData['yx_day'] = 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();
            return $arr;
        }catch(\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>102,'msg'=>'添加消费产品时订单表更新失败','data'=>''.$e->getMessage());
        }
    }

    /**
     * 收款接口    
     * @param  
     * @param  order_sn              订单编号
     * @param  paymentdate           收款时间(20190528 八位)
     * @param  collectmoneynumber    收款流水号
     * @param  order_fact            一销收款
     * @param  two_pin_fact          二销收款
     * @param  isdel                 是否删除本次收款（0：不删除；1：删除）
     * 
     * @return array
     */
    public function cashMoney($param){
    	if (!trim($param['order_sn'])) {
    		return array('error'=>1,'code'=>100,'msg'=>'缺少参数，order_sn，请确认','data'=>'');
    	}
    	if (!trim($param['collectmoneynumber'])) {
    		return array('error'=>1,'code'=>101,'msg'=>'缺少参数，collectmoneynumber，请确认','data'=>'');
    	}
        $orderInfo = $this->checkOrder(['order_sn'=>$param['order_sn']]);
        if($orderInfo['error'] == 1){
            return array('error'=>1,'code'=>404,'msg'=>'付款时,订单表查询失败','data'=>'');
        }

        $cInfo = db('crm_c_customerinfo')->where('id',$orderInfo['customer_id'])->field('id,totalpay_money,fact_money,order_number')->find();

        // 无效订单
        if($orderInfo['order_valid'] == 1){
            $checkParam = [
                'brandclass_id' => $orderInfo['brandclass_id'],
                'fact_money'    => $orderInfo['order_fact']+$param['order_fact'],
                'order_money'   => $orderInfo['order_amount'],
            ];
            $result = controller('index/Customer', 'lib')->checkOrderValid($checkParam);
            
            db()->startTrans();
            try {
                // 从 '无效' 订单变成 '有效' 订单
                if ($result === true) {
                    // 更新订单表
                    $orderData = [
                        'order_sn'      => $param['order_sn'],
                        'order_valid'   => 2,
                        'valid_time'    => $param['paymentdate'] ? date('Y-m-d H:i:s',strtotime($param['paymentdate'])) : date('Y-m-d H:i:s'),
                        'order_fact'    => $orderInfo['order_fact']+$param['order_fact'],
                        // 'order_amount'  => $param['order_amount'],
                        'two_pin_fact'  => $orderInfo['two_pin_fact']+$param['two_pin_fact'],
                        // 'two_pin_amount'=> $param['two_pin_amount'],
                        'update_time'   => date('Y-m-d'),
                    ];
                    
                    $oRes = controller('index/Child','lib')->updateCustomerOrder($orderData);
                    // 查询是否存在相同流水号
                    $oDetail = db('c_order_detail')->where('order_sn', $param['order_sn'])->where('collectmoneynumber', $param['collectmoneynumber'])->count();
                    //订单流水表
                    $order = array(
                        'order_sn'    => $param['order_sn'],
                        'pay_time'    => $param['paymentdate'] ? date('Y-m-d H:i:s',strtotime($param['paymentdate'])) : date('Y-m-d H:i:s'),
                        'collectmoneynumber'=> trim($param['collectmoneynumber']),
                        'order_valid' => $orderData['order_valid'],
                    );

                    // $odRes = db('crm_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'],
                    ];
                    if(!$param['order_amount']){
                        $customerData['is_success'] = 3;
                    }
                    $cusInfo = db('crm_c_customerinfo')->where('id',$orderInfo['customer_id'])->field('is_intostore,is_valid')->find();
                    if($cusInfo['is_intostore'] != 2){
                        $customerData['is_intostore'] = 2;
                        $customerData['syjd_day'] = date('Y-m-d H:i:s',time());
                    }
                    if($cusInfo['is_valid'] != 1){
                        $customerData['is_valid'] = 1;
                        $customerData['yx_day'] = date('Y-m-d H:i:s',time());
                    }

					// 如果客资表的订单号一样，说明客资匹配的是当前订单，需要更新，否则客资信息不动
                    if ($param['order_sn'] == $cInfo['order_number']) {
                    	$customerData = [
	                        // 'id'            => $orderInfo['customer_id'],
	                        'is_success'    => 1,
	                        'order_day'     => $orderData['valid_time'],
	                        'fact_money'    => $orderData['order_fact']+$orderInfo['two_pin_fact'],
	                        'totalpay_money'=> $orderInfo['order_amount']+$orderInfo['two_pin_amount'],
	                        'update_time'   => date('Y-m-d H:i:s',time())
	                    ];
	                    db('c_customerinfo')->where('id',$orderInfo['customer_id'])->update($customerData);
                    }
                    // 记日志
                    action_log($param,$orderInfo,$orderInfo['customer_id'],session('staff_id'),session('staff_name'));
                }
                // 从 '无效' 订单变成 '无效' 订单
                else {
                    // 更新订单表
                    $orderData = [
                        'order_sn' => $param['order_sn'],
                        'order_valid' => 1,
                        'earnest_money'=>$orderInfo['earnest_money']+$param['order_fact'],
                        // 'order_fact'=>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'),
                    ];
                    $oRes = controller('index/Child','lib')->updateCustomerOrder($orderData);
                    action_log($param,$orderInfo,$orderInfo['customer_id'],session('staff_id'),session('staff_name'));
                    //订单流水表
                    $order = array(
                        'order_sn' => $param['order_sn'],
                        'pay_time' => $param['create_time'] ? date('Y-m-d H:i:s',strtotime($param['create_time'])) : '',
                        'order_valid' => 1,
                        'order_fact' => $param['order_fact'],
                        'two_pin_fact' => $param['two_pin_fact'],
                        'create_time' => date('Y-m-d H:i:s',time())
                    );
                    // db('crm_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('crm_c_customerinfo')->where('id',$orderInfo['customer_id'])->field('is_intostore,is_valid,order_number')->find();
                    if($cusInfo['is_intostore'] != 2){
                        $customerData['is_intostore'] = 2;
                        $customerData['syjd_day'] = date('Y-m-d H:i:s',time());
                    }
                    /*if($cusInfo['is_valid'] != 1){
                        $customerData['is_valid'] = 1;
                        $customerData['yx_day'] = date('Y-m-d H:i:s',time());
                    }*/
                    if(empty($cusInfo['order_number']) || $cusInfo['order_number'] == $param['order_sn']){
                         controller('index/Customer','lib')->updateCustomer($customerData);
                    }
                }
                db()->commit();
            } catch (Exception $e) {
                db()->rollback();
                return array('error'=>1,'code'=>101,'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/Child', 'lib')->checkOrderValid($checkParam);
            try {
            	// 从 '有效' 订单变成 '无效' 订单
                if($result === false){
                    // 更新订单表
                    $orderData = [
                        'order_sn' => $param['order_sn'],
                        'order_valid' => 1,
                        'order_fact'=>0,
                        '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'),
                    ];

                    //订单流水表
                    $order = array(
                        'order_sn' => $param['order_sn'],
                        'pay_time' => $param['create_time'] ? date('Y-m-d H:i:s',strtotime($param['create_time'])) : '',
                        'order_valid' => 1,
                        'order_fact' => $param['order_fact'],
                        'two_pin_fact' => $param['two_pin_fact'],
                        'create_time' => date('Y-m-d H:i:s',time())
                    );

                	// db('crm_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'],
                    ];
                }
                // 从 '有效' 订单变成 '有效' 订单
                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'),
                    ];

                    //订单流水表
                    $order = array(
                        'order_sn' => $param['order_sn'],
                        'pay_time' => $param['create_time'] ? date('Y-m-d H:i:s',strtotime($param['create_time'])) : '',
                        'order_valid' => 2,
                        'order_fact' => $param['order_fact'],
                        'two_pin_fact' => $param['two_pin_fact'],
                        'create_time' => date('Y-m-d H:i:s',time())
                    );
                    // db('crm_c_order_detail')->insert($order);
                    //修改客资表
                    $customerData = [
                        'id'=>$orderInfo['customer_id'],
                        'totalpay_money'=>$param['order_amount']+$param['two_pin_amount'],
                        'is_success'=>1,
                        'fact_money'=>$cInfo['fact_money']+$param['order_fact']+$param['two_pin_fact'],
                        'order_number'=>$param['order_sn'],
                    ];
                }
                if(!$param['order_amount']) {
                    $customerData['is_success'] = 3;
                }
                $cusInfo = db('crm_c_customerinfo')->where('id',$orderInfo['customer_id'])->field('is_intostore,is_valid,order_number')->find();
                if($cusInfo['is_intostore'] != 2){
                    $customerData['is_intostore'] = 2;
                    $customerData['syjd_day'] = date('Y-m-d H:i:s',time());
                }
                if($cusInfo['is_valid'] != 1){
                    $customerData['is_valid'] = 1;
                    $customerData['yx_day'] = date('Y-m-d H:i:s',time());
                }
                controller('index/Child','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']){
                    controller('index/Customer','lib')->updateCustomer($customerData);
                }

                db()->commit();
            } catch (Exception $e) {
                db()->rollback();
                return array('error'=>1,'code'=>101,'msg' =>'有效订单收款失败','data'=>$e->getMessage());
            }
        }
        if ((int)$param['isdel'] === 1) {
        	db('c_order_detail')->where('order_sn', $param['order_sn'])->where('collectmoneynumber', $param['collectmoneynumber'])->delete();
        }
        return $orderData;
    }

    /**
     * 检查该订单是否存在于客资系统中
     * 
     * @param  customer_id
     * @param  order_sn
     *
     * @return boolean
     * @author lilong<lilong@suxuantech.cn>
     */
    public function checkOrder($param){
        $res = controller("index/Child","lib")->checkOrder($param);
        if (!$res) {
            $return = array('error'=>1,'code'=>201,'msg'=>'不存在该订单信息！');
        }else{
            $return = $res;
        }
        // var_dump($return);
        return $return;
    }

    /**
     * 门市删除订单
     * 
     * @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('crm_c_customer_order')->where('order_sn', $order_sn)->count();
        if (!$haveOrder) {
            $returnData=['code'=> 201,'msg' => '订单不存在'];
        }else{
            // 查询订单所属的客资
            $hasCustomer = db('crm_c_customerinfo')
                ->where('order_number', $order_sn)
                ->field('id,is_success,order_start_time,order_number,fact_money,totalpay_money')
                ->find();
            db()->startTrans();
            try {
                // 删除订单及明细
                db('crm_c_customer_order')->where('order_sn', $order_sn)->delete();
                db('crm_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('crm_c_customerinfo')->where('id',$hasCustomer['id'])->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);

        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');
        $errorStr = '';
        $errorNum = 0;
        foreach ($info as $key => $value) {
            if (!$value) {
                continue;
            }
            $cInfo = explode('-',$value);
            $rData['brandclass_id'] = (int)$param['brandclass_id'];
            $rData['brandclass'] = $param['brandclass'];
            $rData['contact']    = $cInfo[1];
            $isRepeat = db('crm_c_customer_main')->where('wphone',$cInfo[1])->count();
            // $isRepeat = controller('index/Child','lib')->isRepeatCustomer($rData);
            // $isRepeat = controller('crm/Customer','lib')->isRepeat($param['brandclass'],$cInfo[1]);
            // var_dump($param['brandclass']);
            // var_dump($cInfo[1]);
            // var_dump($isRepeat);exit;
            // 没有找到重复客资
            // echo microtime(true).'--'.__LINE__.'<br />';
            if ($isRepeat==0) {
            // if ($isRepeat===false) {
                $customerList[$key]['eid']            = $eid;
                $customerList[$key]['c_from']         = 3;
                $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'] ? $staffInfo['staffnumber'] : '';
                $customerList[$key]['add_shop_code']      = $staffInfo['shop_code'] ? $staffInfo['shop_code'] : trim($param['shop_code']);
                $customerList[$key]['add_shop_name']      = $staffInfo['shop_name'] ? $staffInfo['shop_name'] : trim($param['shop_name']);
                // $customerList[$key]['customer_channel']   = $staffInfo['department_name'] ? $staffInfo['department_name'] : trim($param['dj_staff']);
                // $customerList[$key]['customer_channel_id']= $staffInfo['department_id'] ? $staffInfo['department_id'] : $dj_staff_id;
                $customerList[$key]['customer_channel']   = trim($param['customer_channel']);
                $customerList[$key]['customer_channel_id']= (int)$param['customer_channel_id'];
                $customerList[$key]['shop_code']          = trim($param['shop_code']);
                $customerList[$key]['shop_name']          = trim($param['shop_name']);
                $customerList[$key]['brandclass']         = trim($param['brandclass']);
                $customerList[$key]['brandclass_id']      = (int)$param['brandclass_id'];
                // 介绍人相关
                $customerList[$key]['customer_type']      = 1;
               // $customerList[$key]['introducer_type']    = 1;
                $customerList[$key]['introducer_name']    = trim($param['introducer_name']);
                $customerList[$key]['introducer_ordernum']= trim($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']?$param['consultation_type_id']:NULL;
                $customerList[$key]['consultation_type']   = $param['consultation_type']?$param['consultation_type']:NULL;
                // 客户来源
                // $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;
                // echo microtime(true).'--'.__LINE__.'<br />';
                $tempMain = dealMain('', $customerList[$key]);
                if ($tempMain['code'] == 200) {
                    $customerList[$key]['c_unique'] = $tempMain['c_unique'];
                }else{
                    $errorNum++;
                    $errorStr .= $value.'添加客户信息失败';
                    unset($customerList[$key]);
                }
            }else{
                $errorNum++;
                $errorStr.= $value.'添加失败，已存在相同客资';
                continue;
            }
        }
        
        if (count($info)==$errorNum&&$errorStr) {
            return array('msg'=>$errorStr, 'error'=>1, 'code' => 101);
        }
        // exit;
        db()->startTrans();
        try {
            // echo microtime(true).'--'.__LINE__.'<br />';
            // 写入客资表
            db('crm_c_customerinfo')->insertAll($customerList);
            // echo microtime(true).'--'.__LINE__.'<br />';
            // 写入联系方式表
            $cids = db('crm_c_customerinfo')->master()->where('eid',$eid)->field('id,customer_tel,c_unique,customer_channel,brandclass')->select();
            // echo microtime(true).'--'.__LINE__.'<br />';
            $contactList = [];
            foreach ($cids as $key => $value) {
                $contactList[$key]['c_id']      = $value['id'];
                $contactList[$key]['c_unique']  = $value['c_unique'];
                $contactList[$key]['customer_channel'] = $value['customer_channel'];
                $contactList[$key]['contact']   = trim($value['customer_tel']);
                $contactList[$key]['brandclass']= trim($value['brandclass']);
            }
            // echo microtime(true).'--'.__LINE__.'<br />';
            db('crm_c_customer_contact')->insertAll($contactList);
            // echo microtime(true).'--'.__LINE__.'<br />';
            // 删除客资表中的-eid 
            db('crm_c_customerinfo')->where('eid',$eid)->update(array('eid'=>NULL));
            // echo microtime(true).'--'.__LINE__.'<br />';
            // 是否开启筛客（不筛客），是否开启自动分配（开分配） push到自动分配队列
            /**$is_sk = controller('crm/Child','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'=>'提报失败', 'error'=>1, 'code' => 100,'error'=>$e->getMessage());
        }
        // echo microtime(true).'--'.__LINE__.'<br />';
        // exit;
        // 根据介绍人的手机号 查询这个介绍人介绍了几个客资
        if ($param['introducer_tel']) {
            $returnData['num'] = db('crm_c_customerinfo')->master()->where('introducer_tel',$param['introducer_tel'])->count('id');
        }else{
            $returnData['num'] = 0;
        }
        // echo microtime(true).'--'.__LINE__.'<br />';
        unset($param);
        unset($staffInfo);
        unset($customerList);
        unset($contactList);
        return $returnData;
    }

    /* ---------------------------------------------------------- up ---------------------------------------------------------- */

	/**
	 * 检查该客资是否存在于客资系统中
	 * 
	 * @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       客户备注
     * @param  staff_name            操作人 new
     *
	 * @return array
	 * @author lilong<lilong@suxuantech.cn>
	 */
	public function checkCustomer($param){
        $customer_name = $param['customer_name'];
        // $tel = preg_match('#/^1[3|4|5|6|7|8|9][0-9]{9}$/#', $param['customer_tel']) ? true : false;
        // if(!check_tel($param['customer_tel'])){
        //     return array('error'=>1,'code'=>300,'msg'=>'手机格式错误','data'=>[]);
        // }

		$return = controller("index/Child","lib")->checkCustomer($param);
        // var_dump($return);
        // exit;
		// 客资不存在，录入到客资里
        $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'            => $param['shop_code'],
                'shop_name'            => $staffInfo['shop_name'],
                'add_shop_code'        => $param['shop_code'],
                'add_shop_name'        => $staffInfo['shop_name'],
                'customer_name'        => $customer_name,
                'customer_number'      => str_shuffle(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'   => 1,
                '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,
                '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'             => $param['staff_name'],
                'dj_staff_id'          => $param['staff_id'],
                'dj_staff_number'      => $staffInfo['staffnumber'],
                'tel_staff_id'         => $param['staff_id'],
                'tel_staff'            => $param['staff_name'],
                'tel_time'             => $date,
                'is_first_tel'         => 1,
                'wechat_staff_id'      => $param['customer_wechat'] ? $param['staff_id'] : '',
                'wechat_staff'         => $param['customer_wechat'] ? $param['staff_name'] : '',
                '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'] ? $param['staff_name'] : '',
                '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,
                'customer_remark'      => $param['customer_remark'] ? trim($param['customer_remark']) : NULL,
                'email'                => $param['email'] ? trim($param['email']) : NULL,
                'customer_address'     => $param['customer_address'] ? trim($param['customer_address']) : NULL,
            ];
            // print_r($param);die;
            db()->startTrans();
            try {
                $res = db('crm_c_customerinfo')->insertGetId($data);
                $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'] = $date;
            }
            if(!empty($arr)){
                db()->startTrans();
                try {
                    db('crm_c_customerinfo')->where('id',$return['id'])->update($arr);
                    db()->commit();
                } catch (Exception $e) {
                    $return = array('error'=>1,'code'=>202,'msg'=>'操作失败，请重试！');
                    db()->rollback();
                }
            }
        }
        if ($param['is_in'] == 1) {
            $returnData = $return;
        }else{
            $returnData['customer_number'] = $return['customer_number'];
        }
		return $returnData;
	}

    //获取员工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('crm_c_customerinfo')->where('dj_staff_id',$v['id'])->where('dj_day','between',[$start,$end])->where('sign_name','like','%a%')->count();
            $staffs[$k]['allNum'] = db('crm_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('crm_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('crm_c_customerinfo')->where('customer_number',$cusNumber)->value('id');
        //追踪记录
        $log = db('crm_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('crm_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 month  月份  年-月
     *       shop_code 店code
     *       area_id    分区
     *       time       时间点
     * return  array
     * */
    public function paichengNum($data){
        $month = $data['month'] ? date('Y-m',strtotime($data['month'])) : date('Y-m');
        $shop_code = $data['shop_code'] ? trim($data['shop_code']) : session('shop_code');
        if($data['area_id']){
            $where['area_id']  = intval($data['area_id']);
        }
//        else{
//            $where['area_id']  = NULL;
//        }
        if($data['time']){
            $where['time']  = intval($data['time']);
        }
//        else{
//            $where['time']  = NULL;
//        }
        //已排 次数
        $pcInfo = db('crm_l_pc_log')->where('pc_time','like',$month.'-%')->where('pc_shop_code',$shop_code)->where($where)->group('pc_time')->order('pc_time')->column('count(id)','pc_time');
        //排程设定
        $info = db('crm_l_pc_setting_log')->where('setting_date','like',$month.'-%')->where('shop_code',$shop_code)->where($where)->group('setting_date')->order('setting_date')->column('sum(num)','setting_date');

        if($info){
            $thisFirstKey = key($info);
            $thisFirst = $info[$thisFirstKey];
        }

        if(empty($thisFirst)){
            $temp = db('crm_l_pc_setting_log')->where('setting_date','<',$thisFirstKey)->where($where)->where('shop_code',$shop_code)->group('setting_date')->order('setting_date desc')->column('sum(num)','setting_date');
        }else{
            $temp = db('crm_l_pc_setting_log')->where('setting_date','<',$month.'-01')->where($where)->where('shop_code',$shop_code)->group('setting_date')->order('setting_date desc')->column('sum(num)','setting_date');
        }
        $temp = end($temp);

        $prev = 0;
        if($thisFirstKey != $month.'-01' && $temp){
            $prev = $temp;
        }
        $days = date("t",strtotime($month));
        $return = [];
        $ret = [];
        for($i=0;$i<$days;$i++){
            $date = date('Y-m-d',strtotime($month)+$i*86400);
            if($info[$date]){
                $ret['num'] = $info[$date];
                $prev = $info[$date];
            }else{
                $ret['num'] = $prev;
            }

            $ret['date'] = date('Y-n-j',strtotime($month)+$i*86400);

            $ret['pc'] = $pcInfo[$date] ? $pcInfo[$date] : 0;
            $return[] = $ret;

        }
        return $return;
    }
    /*
     * 排程
     * param
     *      id              客资id
     *      staff_id        操作人id
     *      pc_time         排程日期
     *      pc_shop_code    排程店面code
     *      pc_shop_name    排程店面
     *      area_id
     *      area_name         分区   可选
     *      time            时间点   可选
     *      cameraman_id
     *      cameraman_name  摄影师   可选
     *      sale_id
     *      sale_name       销售   可选
     *      tutor_id
     *      tutor_name      导师   可选
     *      remark          排程备注
     *      model_id        短信模板id   可选
     * return array('code'=>200,'msg'=>'排程成功','data'=>'','time'=>date('Y-n-j',strtotime($data['pc_time'])));
     * */
    public function paicheng($data){
        $where = [];
        if($data['pc_time'] < date('Y-m-d')){
            return array('code' => 106, 'msg' => '已是过去时间,不能排程');
        }
        if($data['pc_shop_code']){
            $where['pc_shop_code'] = trim($data['pc_shop_code']);
            $whereS['shop_code'] = trim($data['pc_shop_code']);
        }
        if($data['area_id']){
            $where['area_id'] = intval($data['area_id']);
            $whereS['area_id'] = intval($data['area_id']);
        }
        else{
            $where['area_id'] = NULL;
            $whereS['area_id'] = NULL;
        }
        if($data['time']){
            $where['time'] = intval($data['time']);
            $whereS['time'] = intval($data['time']);
        }
        else{
            $where['time'] = NULL;
            $whereS['time'] = NULL;
        }
        $res = db('crm_l_pc_log')->where('cid',$data['id'])->where('pc_time',$data['pc_time'])->where($where)->find();
        if($res) {
            return array('code' => 101, 'msg' => '本客资此时间已排程,不能多次操作');
        }
        $todaySetting = db('crm_l_pc_setting_log')->where('shop_code',$data['pc_shop_code'])->where('setting_date',$data['pc_time'])->count();
        if(!$todaySetting){
            $queryDate = db('crm_l_pc_setting_log')->where('shop_code',$data['pc_shop_code'])->where('setting_date','<',$data['pc_time'])->order('setting_date desc')->value('setting_date');

        }else{
            $queryDate = $data['pc_time'];
        }
        $settingRow =db('crm_l_pc_setting_log')->where('setting_date',$queryDate)->where($whereS)->find();
        if(!$settingRow){
            if($data['time'] && $data['area_id']){
                $whereS['time'] = NULL;
                $settingRow =db('crm_l_pc_setting_log')->where('setting_date',$queryDate)->where($whereS)->find();
                if(!$settingRow){
                    $whereS['area_id'] = NULL;
                    $whereS['time'] = $data['time'];
                    $settingRow =db('crm_l_pc_setting_log')->where('setting_date',$queryDate)->where($whereS)->find();
                    if(!$settingRow){
                        $whereS['area_id'] = NULL;
                        $whereS['time'] = NULL;
                        $settingRow =db('crm_l_pc_setting_log')->where('setting_date',$queryDate)->where($whereS)->find();
                    }
                }
            }elseif($data['time'] && empty($data['area_id'])){
                $whereS['time'] = NULL;
                $settingRow =db('crm_l_pc_setting_log')->where('setting_date',$queryDate)->where($whereS)->find();
            }elseif(empty($data['time']) && $data['area_id']){
                $whereS['area_id'] = NULL;
                $settingRow =db('crm_l_pc_setting_log')->where('setting_date',$queryDate)->where($whereS)->find();
            }
        }

        if($settingRow){
            $num = $settingRow['num'];
            $todayTotal = db('crm_l_pc_setting_log')->where('setting_date',$queryDate)->where('shop_code',$data['pc_shop_code'])->sum('num');
        }else{
            $num = 0;
        }
        $todayPcTotal = db('crm_l_pc_log')->where('pc_time',$data['pc_time'])->where('pc_shop_code',$data['pc_shop_code'])->count();
        if($todayPcTotal >= intval($todayTotal)){
            return array('code' => 102, 'msg' => '排程总量已达最大值,不能排程');
        }

        if($num == 0){
            return array('code' => 103, 'msg' => '当前分区时间点无档期不能排程，请设定档期');
        }
        $whereNew['pc_shop_code'] = $settingRow['shop_code'];
        if($settingRow['area_id']) $whereNew['area_id'] = $settingRow['area_id'];
        if($settingRow['time']) $whereNew['time'] = $settingRow['time'];
        $total = db('crm_l_pc_log')->where('pc_time',$data['pc_time'])->where($whereNew)->count();
        if( $total >= $num){
            return array('code' => 104, 'msg' => '已达排程最大次数,不能排程');
        }
        $staff = getStaffInfoById($data['staff_id']);
        db()->startTrans();
        try{
            $arr = [
                'cid' => $data['id'],
                'shop_code' => $staff['shop_code'],
                'shop_name' => $staff['shop_name'],
                'pc_shop_code' => trim($data['pc_shop_code']),
                'pc_shop_name' => $data['pc_shop_name'] ? trim($data['pc_shop_name']) : '',
                'cameraman_id' => intval($data['cameraman_id']),
                'cameraman_name' => $data['cameraman_name'] ? trim($data['cameraman_name']) : '',
                'sale_id' => intval($data['sale_id']),
                'sale_name' => $data['sale_name'] ? trim($data['sale_name']) : '',
                'tutor_id' => intval($data['tutor_id']),
                'tutor_name' => $data['tutor_name'] ? trim($data['tutor_name']) : '',
                'remark'     => trim($data['remark']),
                'pc_time'    => trim($data['pc_time']),
                'area_id'    => $data['area_id'] ? $data['area_id'] : NULL,
                'area_name'    => $data['area_name'] ? trim($data['area_name']) : NULL,
                'time'    => $data['time'] ? trim($data['time']) : NULL,
                'create_time' => date('Y-m-d H:i:s')
            ];
            db('crm_l_pc_log')->insert($arr);
            //crm标记预约进店
            $cData['yjd_action_day']=date('Y-m-d H:i:s');
            $cData['yjd_day']=date('Y-m-d H:i:s',strtotime($data['pc_time'].' '.date('H:i',strtotime($arr['time']))));
            $cData['consulation_shop_code'] = $data['pc_shop_code'];
            $cData['consulation_shop'] = $data['pc_shop_name'];
            db('crm_c_customerinfo')->where('id',$data['id'])->update($cData);
            //追踪记录
            $customerInfo =  db('crm_c_customerinfo')->where('id', $data['id'])->find();
            $params['customer_id'] = $data['id'];
            $params['c_unique'] = $customerInfo['c_unique'];
            $params['customer_name'] = $customerInfo['customer_name'];
            $params['customer_number'] = $customerInfo['customer_number'];
            $params['sales_remark'] = '到店拍预约进店-'.trim($data['remark']);
            $params['sales_day'] = date('Y-m-d H:i:s',time());
            $params['sales_staff'] = $staff['staff_name'] ? $staff['staff_name'] : $staff['staffname'];
            $params['sales_staff_id'] = $data['staff_id'];
            $params['sales_staff_number'] = $staff['staff_number'] ? $staff['staff_number'] : $staff['staffnumber'];
            $params['shop_name'] = $staff['shop_name'];
            $params['shop_code'] = $staff['shop_code'];
            db('crm_c_salestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$data['id'],null);
            //短信
            if($data['model_id']){
                $send_msg = db('crm_s_message_templateinfo')->where('id',$data['model_id'])->value('mtemplate_content');
                $send_msg .= ',店面：'.$data['pc_shop_name'];
                if($arr['area_name']){
                    $send_msg .= ',分区：'.$arr['area_name'];
                }else{
                    $send_msg .= ',分区：任意分区；';
                }
                if($arr['time']){
                    $a = substr($arr['time'],0,2);
                    $b = substr($arr['time'],2,4);
                    $send_msg .= ',时间点：'.$a.':'.$b;
                }else{
                    $send_msg .= ',时间点：任意时间点；';
                }
                $sms = db_config('sms_'.$data['pc_shop_code']);//短信账号
                $param = [
                    'ids' =>$data['id'],//客资id
                    'model_id' => $data['model_id'],//模板id
                    'send_msg' => $send_msg,//发送的模板内容
                    'send_config' => $sms,//短信账号
                ];
                controller('Customer','lib')->send_message($param);
            }
            db()->commit();
            return array('code'=>200,'msg'=>'排程成功','data'=>'','time'=>date('Y-n-j',strtotime($data['pc_time'])));
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'排程失败','data'=>$e->getMessage());
        }
    }
    /*
     * 获取短信模板
     * param        shop_code
     * */
    public function getModel($data){
        $shop_code = $data['shop_code'];
        $res = controller('crm/Customer','lib')->getModel($shop_code);
        return $res;
    }
}