<?php
/**
 * 客资接口实现类
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: wzy<wangzhenya@suxuantech.cn> 2018-1-3 $
 */
namespace app\index\lib;
use app\common\lib\mcInterface;
class Customer{
    /*
     * 修改客资信息
     * $param  如：['id'=>$id,'totalpay_money'=>$param['order_amount'],'fact_money'=>$param['order_fact']]
     * return 受影响的行
     * */
    public function updateCustomer($param){
        $res = db('crm_c_customerinfo')->where('id',$param['id'])->update($param);
        return $res;
    }
    /*
     * 修改客资信息
     * $param  如：['id'=>$id,'totalpay_money'=>$param['order_amount'],'fact_money'=>$param['order_fact']]
     * return 受影响的行
     * */
    public function updateCustomerOrder($param){
        $res = db('crm_c_customer_order')->where('order_sn',$param['order_sn'])->update($param);
        return $res;
    }

    /**
     * 根据事业部获取  店（电商，网销，渠道）
     * @param  brandclass_id   事业部id
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getShops($brandclass_id){
        $shopList = cache('brandShop_'.$brandclass_id);
        if (!$shopList || empty($shopList)) {
            $url = '5a37a1503264d';
            $data['brandclass_id']= $brandclass_id;
            $res = sx_call($url, $data);
            if ($res['code'] == 200) {
                $shopList = $res['data'];
                cache('brandShop_'.$brandclass_id, json_encode($shopList));
            }else{
                $shopList = '';
            }
        }else{
            $shopList = json_decode($shopList, true);
        }
        return $shopList;
    }
    /**
     * 根据事业部id 获取事业部名
     * @param  brandclass_id   事业部id
     * @return str
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getBlandclass($brandclass_id){
        $shopList = cache('brandShop_'.$brandclass_id);
        if (!$shopList || empty($shopList)) {
            $url = '5a37a1503264d';
            $data['brandclass_id']= $brandclass_id;
            $res = sx_call($url, $data);
            if ($res['code'] == 200) {
                $shopList = $res['data'];
                cache('brandShop_'.$brandclass_id, json_encode($shopList));
            }else{
                $shopList = '';
            }
        }else{
            $shopList = json_decode($shopList, true);
        }
        return $shopList;
    }

	/**
	 * 检查该客资是否存在于客资系统中
	 * 
	 * @param  brandclass_id         事业部id
	 * @param  shop_code       
     * @param  customer_number       客户编号
	 * @param  customer_tel
	 * @param  customer_wechat
	 * @param  customer_qq
	 *
	 * @return boolean
	 * @author lilong<lilong@suxuantech.cn>
	 */
	public function checkCustomer($param){
        if ($param['customer_number']) {
            $res = db('crm_c_customerinfo')
                ->where('customer_number', $param['customer_number'])
                ->field('id,c_unique,is_valid,is_intostore,customer_number,shop_code,shop_name,consulation_shop_code,consulation_shop,order_number,customer_tel,customer_wechat,customer_qq,customer_weibo,customer_name,customer_sex,mate_tel,mate_wechat,mate_name,mate_sex,sales_staff_id,dj_staff_id,dj_staff,sales_staff,last_trackday,dj_day,jr_day,c_star_day,c_end_day,yjd_day,syjd_day,c_from,order_type,customer_channel,customer_type,dj_staff_id')
                ->select();
        }
        if (!$res) {
            if ($param['customer_wechat']) {
                $sql = " (customer_wechat = :customer_wechat or customer_qq=:customer_qq or customer_tel = :customer_tel or mate_tel=:mate_tel) ";
                $array['customer_wechat']=$param['customer_wechat'];
                $array['customer_qq']=$param['customer_wechat'];
                $array['customer_tel']=$param['customer_wechat'];
                $array['mate_tel']=$param['customer_wechat'];
            }
            if ($param['customer_qq']) {
                if ($sql) {
                    $sql .= " or (customer_wechat = :customer_wechat1 or customer_qq=:customer_qq1 or customer_tel = :customer_tel1 or mate_tel=:mate_tel1) ";
                } else {
                    $sql= " (customer_wechat = :customer_wechat1 or customer_qq=:customer_qq1 or customer_tel = :customer_tel1 or mate_tel=:mate_tel1) ";
                }
                $array['customer_wechat1']=$param['customer_qq'];
                $array['customer_qq1']=$param['customer_qq'];
                $array['customer_tel1']=$param['customer_qq'];
                $array['mate_tel1']=$param['customer_qq'];
            }
            if ($param['customer_tel']) {
                if ($sql) {
                    $sql .= " or (customer_wechat = :customer_wechat2 or customer_qq=:customer_qq2 or customer_tel = :customer_tel2 or mate_tel=:mate_tel2) ";
                } else {
                    $sql= " (customer_wechat = :customer_wechat2 or customer_qq=:customer_qq2 or customer_tel = :customer_tel2 or mate_tel=:mate_tel2) ";
                }
                $array['customer_wechat2']=$param['customer_tel'];
                $array['customer_qq2']=$param['customer_tel'];
                $array['customer_tel2']=$param['customer_tel'];
                $array['mate_tel2']=$param['customer_tel'];
            }
            if ($param['mate_tel']) {
                if ($sql) {
                    $sql .= " or (customer_wechat = :customer_wechat3 or customer_qq=:customer_qq3 or customer_tel = :customer_tel3 or mate_tel=:mate_tel3) ";
                } else {
                    $sql= " (customer_wechat = :customer_wechat3 or customer_qq=:customer_qq3 or customer_tel = :customer_tel3 or mate_tel=:mate_tel3) ";
                }
                $array['customer_wechat3']=$param['mate_tel'];
                $array['customer_qq3']=$param['mate_tel'];
                $array['customer_tel3']=$param['mate_tel'];
                $array['mate_tel3']=$param['mate_tel'];
            }
            // create_time(获取时间),creator_day(录入时间),jr_day(接入时间),c_star_day(开始追踪时间),yjd_day(预约进店时间)
            $res = $sql?db("crm_c_customerinfo")
                ->field('id,c_unique,is_valid,is_intostore,customer_number,shop_code,shop_name,consulation_shop_code,consulation_shop,order_number,customer_tel,customer_wechat,customer_qq,customer_weibo,customer_name,customer_sex,mate_tel,mate_wechat,mate_name,mate_sex,sales_staff_id,dj_staff_id,dj_staff,sales_staff,last_trackday,dj_day,jr_day,c_star_day,c_end_day,yjd_day,syjd_day,c_from,order_type,customer_channel,customer_type,dj_staff_id')
                ->where('brandclass_id', $param['brandclass_id'])
                ->where('is_status', 1)
                ->where('is_success', '<>', 1)
                ->where($sql,$array)
                ->select():[];
            /* $url = '5a3bbb5d0988d';
             $brand = sx_call($url,['id'=>$param['brandclass_id']]);
            if($brand['code'] == 200){
                $valid_date = $brand['data'][0]['valid_date'];
                $day_now = (int)((time()-strtotime($res['dj_day']))/86400);
                if($day_now > $valid_date){
                    return false;
                }else{
                    return $res;
                }
            }
            */
           //调用匹配规则进行客资匹配找出最符合规则的客资：
        };
        
        $matchCustomize = db_config('customer_match_method');
        if($matchCustomize && method_exists($this,$matchCustomize)){
            //客户定制的方法
            return $this->$matchCustomize($res,$param);
        }
        //标准方法
        return $this->matchCustomer($res,$param);
	}
    
    /**
     * 多条客资匹配规则，此方法后续可能会因各家不一样，加不同的实现方式
     * 
     * @param  array  $customerList [description]
     * @param  array  $params       [description]
     * @return [type]               [description]
     */
    public function matchCustomer($customerList=[],$params=[]){
        if(empty($customerList)){
            return false;
        }
        $validDate = 0;
        if($params['brandclass_id']){
            $mc = new mcInterface();
            $brand = $mc->getBrand(['id'=>$params['brandclass_id']]);
            $validDate = $brand?$brand['valid_date']:0;
        }
        $validDateRule = db_config('valid_date_rule');
        $validDateRule  = $validDateRule?$validDateRule:'dj_day';
        $matchedCustomer = [];
        if($validDate){
            foreach ($customerList as $value) {
                if($value['c_from'] == 2){
                    return true;
                }
                $dayNow = ceil((int)((time()-strtotime($value[$validDateRule]))/86400));
                if($dayNow < $validDate){
                    $matchedCustomer = $value;
                }
            }
        }else{
            //没有客资过期过期时间，取最后一条
            foreach ($customerList as $value) {
                if($value['c_from'] == 2){
                    return true;
                }
                $djDay = strtotime($value['dj_day']);
                if(!$matchedCustomer || strtotime($matchedCustomer['dj_day']) < $djDay){
                    $matchedCustomer = $value;
                }
            }
        }
        return $matchedCustomer?$matchedCustomer:false;
    }
    /**
     * 多条客资匹配规则，上海桔子定制
     * config 配置：'customer_match_method' => 'matchCustomer_juzi',
     * @param  array  $customerList [description]
     * @param  array  $params       [description]
     * @return [type]               [description]
     */
    public function matchCustomer_juzi($customerList=[],$params=[]){
        if(empty($customerList)){
            return false;
        }
        foreach ($customerList as $key => $value) {
            if($value['c_from'] == 2){
                return true;
            }
        }
        $validDate = 0;
        if($params['brandclass_id']){
            $mc = new mcInterface();
            $brand = $mc->getBrand(['id'=>$params['brandclass_id']]);
            $validDate = $brand?$brand['valid_date']:0;
        }
        $validDateRule = db_config('valid_date_rule');
        $validDateRule  = $validDateRule?$validDateRule:'dj_day';
        $matchedCustomer = [];
        if($validDate){
            foreach ($customerList as $value) {

                if($value['is_valid'] == 3 || $value['is_valid'] == 4 || !$value['last_trackday']){
                    //无效，驳回，未追踪过的，不算他的。
                    //if($value['c_from'] != 2)
                        continue;
                }
                $dayNow = $value[$validDateRule]?ceil((int)((time()-strtotime($value[$validDateRule]))/86400)):0;
                $trackDay = $value['last_trackday']?ceil((int)((time()-strtotime($value['last_trackday']))/86400)):0;
                //在有效期内，最近十天内有追踪
                if($dayNow < $validDate && $trackDay <=10){
                    if(!$matchedCustomer){
                        $matchedCustomer = $value;
                    }else{
                        $thisYjdDay = $value['yjd_day']?strtotime($value['yjd_day']):0;
                        $matchedYjdDay = $matchedCustomer['yjd_day']?strtotime($matchedCustomer['yjd_day']):0;
                        if($thisYjdDay == 0 && $matchedYjdDay == 0){
                            //都没约过，用最近追踪的
                            $matchedTrackDay = $matchedCustomer['last_trackday']?strtotime($matchedCustomer['last_trackday']):0;
                            $thisTrackDay = $value['last_trackday']?strtotime($value['last_trackday']):0;
                            if($thisTrackDay >= $matchedTrackDay){
                                $matchedCustomer = $value;
                            }
                        }else if($thisYjdDay != 0 && $thisYjdDay <= $matchedYjdDay){
                            //这条约过，是先约的
                            $matchedCustomer = $value;
                        }else if ($thisYjdDay != 0 && $matchedYjdDay == 0){
                            //这条约过，上条未约过
                            $matchedCustomer = $value;
                        }
                    }
                }
            }
        }else{
            //没有客资过期过期时间，
            foreach ($customerList as $value) {
                $trackDay = $value['last_trackday']?ceil((int)((time()-strtotime($value['last_trackday']))/86400)):0;
                if($trackDay <=10){
                    if(!$matchedCustomer){
                        $matchedCustomer = $value;
                    }else{
                        $thisYjdDay = $value['yjd_day']?strtotime($value['yjd_day']):0;
                        $matchedYjdDay = $matchedCustomer['yjd_day']?strtotime($matchedCustomer['yjd_day']):0;
                        if($thisYjdDay == 0 && $matchedYjdDay == 0){
                            //都没约过，用最近的
                            $matchedTrackDay = $matchedCustomer['last_trackday']?strtotime($matchedCustomer['last_trackday']):0;
                            $thisTrackDay = $value['last_trackday']?strtotime($value['last_trackday']):0;
                            if($thisTrackDay >= $matchedTrackDay){
                                $matchedCustomer = $value;
                            }
                        }else if($thisYjdDay != 0 && $thisYjdDay <= $matchedYjdDay){
                            //先约的
                            $matchedCustomer = $value;
                        }else if ($thisYjdDay != 0 && $matchedYjdDay == 0){
                            //这条约过，上条未约过
                            $matchedCustomer = $value;
                        }
                    }
                }
            }
        }
        return $matchedCustomer?$matchedCustomer:false;
    }
	/**
	 * 检查该订单是否存在于客资系统中
	 * 
	 * @param  customer_id
	 * @param  order_sn
	 *
	 * @return boolean
	 * @author lilong<lilong@suxuantech.cn>
	 */
	public function checkOrder($param){
		$where = [
			'order_sn'   =>$param['order_sn'],
			// 'customer_id'=>$param['customer_id'],
		];
		$res = db('crm_c_customer_order')->where($where)->find();

		return $res;
	}

    public function getBrandClassInfo($brandclass_id){
        //根据事业部id查询设定的有效条件
        $brandclassInfo = cache('brandclassInfo_'.$brandclass_id);
        if(empty($brandclassInfo)){
            $info = sx_call('5a38840b15ba9',['id'=>$brandclass_id]);
            if($info['code'] == 200){
                cache('brandclassInfo_'.$brandclass_id,$info['data'][0]);
                $brandclassInfo = $info['data'][0];
            }
        }
        return $brandclassInfo;
    }
    //创建订单
    public function addCustomerOrder($param){
        $res = db('crm_c_customer_order')->insertGetId($param);
        // echo db()->getLastSql();
        return $res;
    }

    // 新建客资 
    public function createCustomer($param){
        $date = date('Y-m-d H:i:s');
        $staffInfo = getStaffInfoById($param['staff_id']);
        $create_time = $param['create_time'] ? date('Y-m-d H:i:s',strtotime($param['create_time'])) : $date;
        if (!$param['staff_name']) {
            $param['staff_name'] = $staffInfo['staffname'];
        }
        // $res = controller('crm/Customer','lib')->isRepeat($staffInfo['brandclass'],$param['wphone'],$param['wwechat'],null,$param['mphone']);
        // if($res['code'] == 201){//客资已存在
        //     if(empty($res['data'])){
        //         $sql = '1=1 ';
        //         if($param['wphone']){
        //             $sql .= ' and customer_tel="'.$param['wphone'].'"';
        //         }
        //         if($param['wwechat']){
        //             $sql .= ' and customer_wechat="'.$param['wwechat'].'"';
        //         }
        //         if($param['mphone']){
        //             $sql .= ' and mate_tel="'.$param['mphone'].'"';
        //         }
        //         if($param['mphone']){
        //             $sql .= ' and mate_wechat="'.$param['mphone'].'"';
        //         }
        //         $info = db('crm_c_customerinfo')->where('is_status',1)->where('brandclass',$staffInfo['brandclass'])->where($sql)->find();
        //         return $info;
        //     }else{
        //         return $res['data'];
        //     }
        // }
        $data = [
            'brandclass_id'        => (int)$param['brandclass_id'],
            'brandclass'           => $staffInfo['brandclass'],
            'shop_code'            => $staffInfo['shop_code'],
            'shop_name'            => $staffInfo['shop_name'],
            'add_shop_code'        => $staffInfo['shop_code'],
            'add_shop_name'        => $staffInfo['shop_name'],
            'customer_number'      => str_shuffle(time().generate_code()),
            'customer_name'        => $param['wname'],
            'customer_tel'         => $param['wphone'],
            'customer_wechat'      => $param['wwechat'],
            'customer_sex'         => '女',
            'mate_name'            => $param['mname'],
            'mate_tel'             => $param['mphone'],
            'mate_wechat'          => $param['mwechat'],
            'mate_sex'             => '男',
            'marry_day'            => $param['marry_day'] ? date('Y-m-d H:i:s', strtotime($param['marry_day'])) : NULL,
            'ready_baby_day'       => $param['ready_baby_day']?date('Y-m-d H:i:s',strtotime($param['ready_baby_day'])):NULL,
            'consultation_type_id' => (int)$param['consultation_type_id'],
            'consultation_type'    => $param['consultation_type'],
            'customer_area_id'     => (int)$param['customer_area_id'],
            'customer_area'        => $param['customer_area'],
            'customer_cource_id'   => (int)$param['customer_cource_id'],
            'customer_cource'      => $param['customer_cource'],
            'c_from'               => 2,
            'is_intostore'         => 2,
            'syjd_day'             => $param['target_time']?$param['target_time']:$create_time,
            'creator_day'          => $create_time,
            'create_time'          => $create_time,
            'dj_day'               => $create_time,
            'dj_staff'             => $param['staffname'],
            'dj_staff_id'          => $param['staff_id'],
            'dj_staff_number'      => $staffInfo['staffnumber'],
            'is_fp'                => 1,
            // 'sales_staff'          => $param['staff_name'],
            // 'sales_staff_id'       => $param['staff_id'],
            // 'sales_staff_number'   => $staffInfo['staffnumber'],
            'tel_staff_id'         => $param['staff_id'],
            'tel_staff'            => $staffInfo['staffname'],
            'tel_time'             => $create_time,
            'is_first_tel'         => 1,
            'wechat_staff_id'      => $param['mwechat'] ? $param['staff_id'] : '',
            'wechat_staff'         => $param['mwechat'] ? $param['staffname'] : '',
            'wechat_time'          => $param['mwechat'] ? $create_time : NULL,
            'is_first_wechat'      => $param['mwechat'] ? 1 : '',
            'customer_type'        => 1,
            'consulation_shop_code'=> $staffInfo['shop_code'],
            'consulation_shop'     => $staffInfo['shop_name'],
            'reception_id'         => $param['reception_id'],
            'reception_name'       => $param['reception_name'],
            'order_number'         => $param['order_sn'],
            'order_start_time'     => $param['target_time']?$param['target_time']:$create_time,
            'is_valid'             => 1,
            'yx_day'               => $param['target_time']?$param['target_time']:$create_time,
            'introducer_name'      => $param['introducer_name'],
            'introducer_tel'       => $param['introducer_tel'],
            'customer_birthday'    => $param['wbirthday'] ? date('Y-m-d H:i:s', strtotime($param['wbirthday'])) : NULL,
            'mate_birthday'        => $param['mbirthday'] ? date('Y-m-d H:i:s', strtotime($param['mbirthday'])) : NULL,
        ];

        $res = db('crm_c_customerinfo')->insertGetId($data);
        $contact = [];
        if($data['customer_tel']){
            array_push($contact,$data['customer_tel']);
        }
        if($data['customer_wechat']){
            array_push($contact,$data['customer_wechat']);
        }
        if($data['customer_qq']){
            array_push($contact,$data['customer_qq']);
        }
        if($data['mate_tel']){
            array_push($contact,$data['mate_tel']);
        }
        $contact=array_unique($contact);
        $contactList = [];
        foreach($contact as $k => $v){
            $contactList[$k]['c_id']=$res;
            $contactList[$k]['contact']=$v;
            $contactList[$k]['brandclass']=$data['brandclass'];
        }
        db('crm_c_customer_contact')->insertAll($contactList);
        if($res){
            if($data['customer_tel']){
                history_log(['customer_tel'=>$data['customer_tel']],[],$res,$data['dj_staff_id'],$data['dj_staff'],'crm','Customer','editCustomerTel');
            }

        }
        $data['id']     = $res;
        $data['status'] = 1;
        $return = $data;
        return $return;
    }

    // 判断订单是否有效
    public function checkOrderValid($param){
        $brandclassInfo = $this->getBrandClassInfo($param['brandclass_id']);
        if(!empty($brandclassInfo)){
            //实收款
            if($brandclassInfo['order_rule'] == 1){
                // 有效
                if ($param['fact_money'] && ($param['fact_money'] >= $brandclassInfo['proportion'])) {
                    return true;
                }else{
                    return false;
                }
            }
            //占比
            else if ($brandclassInfo['order_rule'] == 2) {
                if ($param['fact_money'] && ($param['fact_money']/$param['order_money'] >= $brandclassInfo['proportion']/100)) {
                    return true;
                }else{
                    return false;
                }
            }
            //未设定订单有效标准时，按订单金额的30%计算，有效订单
            else{
                if ($param['fact_money'] && ($param['fact_money']/$param['order_money'] >= 0.3)) {
                    return true;
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
    }

    // 如果已经订单，那么重复录入，来源属于erp；
    // 如果没有订单，且超过有效期，重复录入，来源属于erp；
    // 如果没有订单，且没有超过有效期，不重复录入，来源属于crm
    public function isRepeatCustomer($param){
        // 查排重表
        $cid = db('crm_c_customer_contact')
            ->where('contact',$param['contact'])
            ->where('brandclass',$param['brandclass'])
            ->order('id desc')
            ->value('c_id');

        // 有，再查客资表
        if ($cid) {
            $cus = db('crm_c_customerinfo')->where('id',$cid)->field('id,customer_number,customer_name,is_valid,is_success,customer_cource,customer_cource_id,customer_orderaddress,customer_orderaddress_id,marry_day,customer_name,customer_sex,customer_tel,customer_wechat,customer_birthday,mate_name,mate_sex,mate_tel,mate_wechat,mate_birthday,introducer_name,introducer_number,introducer_tel,province,province_id,city,city_id,county,county_id,customer_address,customer_channel_id,customer_channel,sales_staff,sales_staff_id,sales_staff_number,dj_day,yjd_action_day,c_star_day,last_trackday,order_start_time,c_from,syjd_day,is_intostore,order_number')->find();
            // 未成交，看看过期没有
            if ($cus['is_success'] == 2) {
                // 客资过期时间
                $valid_date = cache('valid_date_'.$param['brandclass_id']);
                if (!$valid_date) {
                    $url = '5a3bbb5d0988d';
                    $brand = sx_call($url,['id'=>$param['brandclass_id']]);
                    $valid_date = $brand['data'][0]['valid_date'];
                    cache('valid_date_'.$param['brandclass_id'], $valid_date);
                }
                // 超过有效期
                if( $valid_date && ( time()-strtotime($cus['dj_day']) )/86400 > $valid_date ){
                    return false;
                }else{
                    return $cus;
                }
            }
            // 已订单或者已定金
            else{
                $now = date('Y-m');
                $order_end = date('Y-m', strtotime($cus['order_start_time']));

                if ($now == $order_end) {
                    return $cus;
                }else{
                    // erp重复录入
                    return false;
                }
                
            }
        }
        // 排重表里没有
        else{
            // return false;
            // 30天有过追踪
            $tAgo = date('Y-m-d H:i:s',strtotime('-30 days'));
            $where = [
                'brandclass' => $param['brandclass'],
                'is_status'  => 1,
                'c_from'     => 1,
            ];
            $cus = db('crm_c_customerinfo')->where('customer_tel|mate_tel|customer_wechat|mate_wechat',$param['contact'])->where($where)->where('last_trackday','>',$tAgo)->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,is_intostore,syjd_day,order_number')->order('last_trackday desc')->find();
            // echo '--step--in4--'.microtime(true);
            // 未成交，看看过期没有
            if ($cus['is_success'] == 2) {
                // 客资过期时间
                $valid_date = cache('valid_date_'.$param['brandclass_id']);
                if (!$valid_date) {
                    $url = '5a3bbb5d0988d';
                    $brand = sx_call($url,['id'=>$param['brandclass_id']]);
                    // echo '--step--inU--'.microtime(true);
                    $valid_date = $brand['data'][0]['valid_date'];
                    cache('valid_date_'.$param['brandclass_id'], $valid_date, 864000);
                }
                // 超过有效期
                if( ( time()-strtotime($cus['dj_day']) )/86400 > $valid_date ){
                    // 30天有过追踪
                    $tAgo = date('Y-m-d H:i:s',strtotime('-30 days'));
                    if ($cus['last_trackday'] > $tAgo) {
                        return $cus;
                    }else{
                        return false;
                    }
                }else{
                    return $cus;
                }
            }
            // 已订单或者已定金
            else{
                $now = date('Y-m');
                $order_end = date('Y-m', strtotime($cus['order_start_time']));

                if ($now == $order_end) {
                    return $cus;
                }else{
                    // erp重复录入
                    return false;
                }
            }
        }
    }

    // 根据crm设定的客资判断规则 （ 简单 单一 规则） 2： tel_time ； 3： c_star_day (开始追踪)  4： last_trackday (最后一次追踪) 
    public function createOrderByType($param){
        // 先判断有几个手机号，
            // 如果只有一个手机号，去客资表里匹配：有，更新客资，创建订单；无：创建客资，创建订单
            // 如果有两个手机号，分别去客资表里匹配，如果只匹配一条客资，更新客资信息，创建订单，如果匹配两条客资，挑选方式根据  2或3的条件，更新客资，创建订单，如果两个手机号，一个客资都没有匹配到，那么创建一个客资，创建订单
        //---------------------------------- 开始 ----------------------------------//
        // 如果两个手机号都存在
        $wphone = trim($param['wphone']);
        $mphone = trim($param['mphone']);
        $brandclass_id = (int)$param['brandclass_id'];

        if ($wphone) {
            if (!check_tel($wphone)) {
                $wphone = '';
            }
        }
        if ($mphone) {
            if (!check_tel($mphone)) {
                $mphone = '';
            }
        }
        $customer_number = '';

        // 如果两个手机号都存在
        if ($wphone && $mphone) {
            $gParam['wphone'] = $wphone;
            $gParam['mphone'] = $mphone;
            $gParam['brandclass_id'] = $brandclass_id;

            // dj_day => tel_time
            if ($param['erp_order_type'] == 2) {
                $gParam['time'] = 'tel_time';
                $gParam['order']= 'asc';
            }
            // c_star_day
            else if ($param['erp_order_type'] == 3) {
                $gParam['time'] = 'c_star_day';
                $gParam['order']= 'asc';
            }
            // last_trackday
            else if ($param['erp_order_type'] == 4) {
                $gParam['time'] = 'last_trackday';
                $gParam['order']= 'desc';
            }
            $customer_number = $this->getCustomerNumber($gParam);
        }
        // 如果只存在女士手机号
        else if($wphone){
            if ($param['erp_order_type'] == 2) {
                $winfo = db('crm_c_customerinfo')
                    ->where('brandclass_id',$brandclass_id)
                    ->where('customer_tel|mate_tel|customer_wechat|mate_wechat',$wphone)
                    ->field('id,customer_number,tel_time')->order('tel_time asc')->find();
            }
            // c_star_day
            else if ($param['erp_order_type'] == 3) {
                $winfo = db('crm_c_customerinfo')
                    ->where('brandclass_id',$brandclass_id)
                    ->where('customer_tel|mate_tel|customer_wechat|mate_wechat',$wphone)
                    ->field('id,customer_number,c_star_day')->order('c_star_day asc')->find();
            }
            // last_trackday
            else if ($param['erp_order_type'] == 4) {
                $winfo = db('crm_c_customerinfo')
                    ->where('brandclass_id',$brandclass_id)
                    ->where('customer_tel|mate_tel|customer_wechat|mate_wechat',$wphone)
                    ->field('id,customer_number,last_trackday')->order('last_trackday desc')->find();
            }
            // echo db()->getLastSql();
            // var_dump($winfo);
            // exit;
            if ($winfo) {
                $customer_number = $winfo['customer_number'];
            }
        }
        // 如果只存在男士手机号
        else if ($mphone) {
            if ($param['erp_order_type'] == 2) {
                $minfo = db('crm_c_customerinfo')
                    ->where('brandclass_id',$brandclass_id)
                    ->where('customer_tel|mate_tel|customer_wechat|mate_wechat',$mphone)
                    ->field('id,customer_number,tel_time')->order('tel_time asc')->find();
            }
            // c_star_day
            else if ($param['erp_order_type'] == 3) {
                $minfo = db('crm_c_customerinfo')
                    ->where('brandclass_id',$brandclass_id)
                    ->where('customer_tel|mate_tel|customer_wechat|mate_wechat',$mphone)
                    ->field('id,customer_number,c_star_day')->order('c_star_day asc')->find();
            }
            // last_trackday
            else if ($param['erp_order_type'] == 4) {
                $minfo = db('crm_c_customerinfo')
                    ->where('brandclass_id',$brandclass_id)
                    ->where('customer_tel|mate_tel|customer_wechat|mate_wechat',$mphone)
                    ->field('id,customer_number,last_trackday')->order('last_trackday desc')->find();
            }
            if ($minfo) {
                $customer_number = $minfo['customer_number'];
            }
        }
        // 两个都不存在
        else{
            return array('code'=>102,'msg'=>'手机号不存在或格式错误','error'=>$param['wphone'].'/'.$param['mphone']);
        }
        // 找到客资 更新客资
        if ($customer_number) {
            $cInfo = db('crm_c_customerinfo')
                ->where('customer_number',$customer_number)
                ->field('id,customer_name,customer_tel,is_valid,is_intostore,consultation_type_id,customer_area_id,customer_channel,customer_channel_id,shop_code,shop_name,brandclass_id,brandclass')
                ->find();
            // echo db()->getLastSql();
            // var_dump($cInfo);
            // exit;
            // 男士信息为客资信息
            if ($cInfo['customer_tel'] == $mphone) {
                // 客资信息
                if ($cInfo['customer_sex'] != '男') {
                    $cData['customer_sex']   = '男';
                }                
                if ($cInfo['customer_name'] != $param['mname'] && $param['mname']) {
                    $cData['customer_name']  = $param['mname'];
                }
                if ($cInfo['customer_wechat'] != $param['mwechat'] && $param['mwechat']) {
                    $cData['customer_wechat']  = $param['mwechat'];
                }
                // 配偶信息
                if ($cInfo['mate_sex'] != '女') {
                    $cData['mate_sex'] = '女';
                }                
                if ($cInfo['mate_name'] != $param['wname'] && $param['wname']) {
                    $cData['mate_name']  = $param['wname'];
                }
                if ($cInfo['mate_wechat'] != $param['wwechat'] && $param['wwechat']) {
                    $cData['mate_wechat']  = $param['wwechat'];
                }
            }
            // 女士信息为客资信息
            else {
            // else ($cInfo['customer_tel'] == $wphone) {
                // 客资信息
                if ($cInfo['customer_sex'] != '女') {
                    $cData['customer_sex']   = '女';
                }                
                if ($cInfo['customer_name'] != $param['wname'] && $param['wname']) {
                    $cData['customer_name']  = $param['wname'];
                }
                if ($cInfo['customer_wechat'] != $param['wwechat'] && $param['wwechat']) {
                    $cData['customer_wechat']  = $param['wwechat'];
                }
                // 配偶信息
                if ($cInfo['mate_sex'] != '男') {
                    $cData['mate_sex'] = '男';
                }                
                if ($cInfo['mate_name'] != $param['mname'] && $param['mname']) {
                    $cData['mate_name']  = $param['mname'];
                }
                if ($cInfo['mate_wechat'] != $param['mwechat'] && $param['mwechat']) {
                    $cData['mate_wechat']  = $param['mwechat'];
                }
            }
            // 有效
            if ($cInfo['is_valid'] != 1 && $cInfo['is_valid'] != 3) {
                $cData['is_valid'] = 1;
                $cData['yx_day'] = $param['create_time'];
            }
            // 进店
            if ($cInfo['is_intostore'] != 2) {
                $cData['is_intostore'] = 2;
                $cData['syjd_day'] = $param['create_time'];
            }

            // 消费类型
            if ($cInfo['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 ($cInfo['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 ($cInfo['brandclass'] != $param['brandclass'] && $param['brandclass']) {
                $cData['brandclass']   = $param['brandclass'];
            }

            $cData['order_number']     = $param['order_sn'];
            $cData['order_start_time'] = $param['target_time'];
            db('crm_c_customerinfo')->where('customer_number',$customer_number)->update($cData);
        }
        // 找不到客资 创建客资
        else{
            $res = $this->createCustomer($param);
            $customer_number = $res['customer_number'];
        }
        // 创建订单
        if (!$cInfo) {
            $cInfo = db('crm_c_customerinfo')
                ->where('customer_number',$customer_number)
                ->field('id,customer_name,customer_channel,customer_channel_id,shop_code,shop_name,brandclass_id,brandclass')
                ->find();
        }
        $oData['order_sn']           = $param['order_sn'];
        $oData['customer_id']        = $cInfo['id'];
        $oData['customer_name']      = $cInfo['customer_name'];
        $oData['customer_channel_id']= $cInfo['customer_channel_id'];
        $oData['customer_channel']   = $cInfo['customer_channel'];
        $oData['consultation_type']  = $param['consultation_type'];
        $oData['target_time']        = $param['target_time'];
        $oData['create_time']        = $param['create_time'];
        $oData['shop_code']          = $cInfo['shop_code'];
        $oData['shop_name']          = $cInfo['shop_name'];
        $oData['order_type']         = 2;
        $oData['order_note']         = $param['order_note'];
        $oData['brandclass_id']      = $cInfo['brandclass_id'];
        $oData['brandclass']         = $cInfo['brandclass'] ? $cInfo['brandclass'] : $param['brandclass'];
        db('crm_c_customer_order')->insert($oData);

        return $customer_number;
    }

    /**
     * 两个手机号，一个时间进行判断客资
     * 
     * @param  wphone  女士手机号
     * @param  mphone  男士手机号
     * @param  time    具体时间  dj_day(tel_time) c_star_day last_trackday 等
     * @param  order   时间条件  asc desc
     *
     * @return customer_number
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getCustomerNumber($param){
        // 排序规则
        $order = $param['time'].' '.$param['order'];
        if ($param['wphone']) {
            $winfo = db('crm_c_customerinfo')->where('is_success', 2)->where('customer_tel|mate_tel|customer_wechat|mate_wechat',$param['wphone'])
                ->field('id,customer_number,'.$param['time'])->order($order)->find();
        }
        if ($param['mphone']) {
            $minfo = db('crm_c_customerinfo')->where('is_success', 2)->where('customer_tel|mate_tel|customer_wechat|mate_wechat',$param['mphone'])
                ->field('id,customer_number,'.$param['time'])->order($order)->find();
        }
        // var_dump($winfo);
        // var_dump($minfo);
        // exit;
        // 男士女士信息都存
        if ($winfo && $minfo) {
            // 如果男士客资编号与女士客资编号一样
            if ($winfo['customer_number'] == $minfo['customer_number']) {
                $customer_number = $winfo['customer_number'];
            }else{
                if ($param['order'] == 'asc') {
                    if ($winfo[$param['time']] < $minfo[$param['time']]) {
                        $customer_number = $winfo['customer_number'];
                    }else{
                        $customer_number = $minfo['customer_number'];
                    }
                }else{
                    if ($winfo[$param['time']] < $minfo[$param['time']]) {
                        $customer_number = $minfo['customer_number'];
                    }else{
                        $customer_number = $winfo['customer_number'];
                    }
                }
            }
        }
        // 只存在女士信息
        elseif ($winfo && !$minfo) {
            $customer_number = $winfo['customer_number'];
        }
        // 只存在男士信息
        elseif (!$winfo && $minfo) {
            $customer_number = $minfo['customer_number'];
        }
        // 都不存在
        else{
            $customer_number = '';
        }
        return $customer_number;
        //$res = db('crm_c_customerinfo')->where('customer_number', $customer_number)->field('id,customer_number,customer_cource,customer_cource_id,customer_orderaddress,customer_orderaddress_id,marry_day,customer_name,customer_sex,customer_tel,customer_wechat,customer_birthday,mate_name,mate_sex,mate_tel,mate_wechat,mate_birthday,introducer_name,introducer_tel,introducer_number,customer_address,sales_staff,sales_staff_id,dj_day,c_star_day,last_trackday')->find();
        // return $res;
    }

}