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

class Child{

    /*
     * 修改客资信息
     * $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,is_valid,is_intostore,customer_number,shop_code,shop_name,order_number,customer_tel,customer_wechat,customer_qq,customer_weibo,customer_name,mate_tel,mate_wechat,mate_name,mate_sex,sales_staff_id,dj_staff,sales_staff,creator_day,jr_day,c_star_day,c_end_day,yjd_day,syjd_day')
                ->find();
        }

        if (!$res || empty($param['customer_number'])) {
            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'];
            }
            // create_time(获取时间),creator_day(录入时间),jr_day(接入时间),c_star_day(开始追踪时间),yjd_day(预约进店时间)
            $res = db("c_customerinfo")
                ->field('id,is_valid,is_intostore,customer_number,shop_code,shop_name,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,sales_staff,creator_day,jr_day,c_star_day,c_end_day,yjd_day,syjd_day')
                ->where('brandclass_id', $param['brandclass_id'])
                ->where('is_status', 1)
                ->where('is_success', '<>', 1)
                ->where($sql,$array)
                ->find();
            $url = '5a3bbb5d0988d';
            $brand = sx_call($url,['id'=>$param['brandclass_id']]);
            if($brand['code'] == 200){
                $valid_date = $brand['data'][0]['valid_date'];
                if((time()-strtotime($res['dj_day']))/86400 > $valid_date){
                    return $res;
                }else{
                    return false;
                }
            }
        };
        return $res;
	}

	/**
	 * 检查该订单是否存在于客资系统中
	 * 
	 * @param  customer_id
	 * @param  order_sn
	 *
	 * @return boolean
	 * @author lilong<lilong@suxuantech.cn>
	 */
	public function checkOrder($param){
		$where = [
			'order_sn'   =>$param['order_sn'],
		];
		$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'],
            'home_phone'           => $param['home_phone'],
            'baby_name'            => $param['baby_name'],
            'baby_sex'             => $param['baby_sex'],
            'baby_birthday'        => date('Y-m-d',strtotime($param['baby_birthday'])),
            'baby_address'         => $param['baby_address'],
            'customer_number'      => str_shuffle(time().generate_code()),
            'customer_name'        => $param['customer_name'],
            'customer_tel'         => $param['customer_tel'],
            'customer_wechat'      => $param['customer_wechat'],
            'customer_sex'         => '女',
            'mate_name'            => $param['mate_name'],
            'mate_tel'             => $param['mate_tel'],
            'mate_wechat'          => $param['mate_wechat'],
            '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'             => $create_time,
            'creator_day'          => $create_time,
            'create_time'          => $create_time,
            'dj_day'               => $create_time,
            'dj_staff'             => $param['staff_name'],
            'dj_staff_id'          => $param['staff_id'],
            'dj_staff_number'      => $staffInfo['staffnumber'],
            'is_fp'                => 1,
            'sales_staff'          => $param['staff_name'],
            'sales_staff_id'       => $param['staff_id'],
            'sales_staff_number'   => $staffInfo['staffnumber'],
            'tel_staff_id'         => $param['staff_id'],
            'tel_staff'            => $staffInfo['staffname'],
            'tel_time'             => $create_time,
            'is_first_tel'         => $param['customer_tel'] ? 1 : '',
            'wechat_staff_id'      => $param['customer_wechat'] ? $param['staff_id'] : '',
            'wechat_staff'         => $param['customer_wechat'] ? $param['staff_name'] : '',
            'wechat_time'          => $param['customer_wechat'] ? $create_time : NULL,
            'is_first_wechat'      => $param['customer_wechat'] ? 1 : '',
            'customer_type'        => 1,
            'consulation_shop_code'=> $staffInfo['shop_code'],
            'consulation_shop'     => $staffInfo['shop_name'],
            'reception_id'         => $param['staff_id'],
            'reception_name'       => $param['staff_name'],
            'order_number'         => $param['order_sn'],
            'order_start_time'     => $create_time,
            'is_valid'             => 1,
            'yx_day'               => $param['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,
            '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,
        ];
        $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);
        $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['order_money'] && ($param['fact_money'] >= $brandclassInfo['proportion'])) {
                    return true;
                }else{
                    return false;
                }
            }
            //占比
            else if ($brandclassInfo['order_rule'] == 2) {
                if ($param['order_money'] && ($brandclassInfo['proportion']/100*$param['order_money'] <= $param['fact_money'])) {
                    return true;
                }else{
                    return false;
                }
            }
            //未设定订单有效标准时，按订单金额的30%计算，有效订单
            else{
                if ($param['order_money'] && (0.3*$param['order_money'] <= $param['fact_money'])) {
                    return true;
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
    }

    // 如果已经订单，且在当月订单，不能重复录入，否则可以重复录入，来源属于erp；
    // 如果没有订单，且超过有效期，如果30天内追踪过，否则可以重复录入，否则重复录入，来源属于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,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,is_valid,is_intostore,is_success,customer_channel,customer_channel_id')->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( ( 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;
                }
            }
        }
        // 排重表里没有
        else{
            $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')->order('last_trackday', 'not null')->order('last_trackday desc')->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( ( 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['customer_tel']);
        $mphone = trim($param['mate_tel']);
        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;

            // 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('customer_tel|mate_tel|customer_wechat|mate_wechat',$wphone)
                    ->where('last_trackday', 'not null')
                    ->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('customer_tel|mate_tel|customer_wechat|mate_wechat',$wphone)
                    ->where('last_trackday', 'not null')
                    ->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('customer_tel|mate_tel|customer_wechat|mate_wechat',$wphone)
                    ->where('last_trackday', 'not null')
                    ->field('id,customer_number,last_trackday')->order('last_trackday desc')->find();
            }
            if ($winfo) {
                $customer_number = $winfo['customer_number'];
            }
        }
        // 如果只存在男士手机号
        else if ($mphone) {
            if ($param['erp_order_type'] == 2) {
                $minfo = db('crm_c_customerinfo')
                    ->where('customer_tel|mate_tel|customer_wechat|mate_wechat',$mphone)
                    ->where('last_trackday', 'not null')
                    ->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('customer_tel|mate_tel|customer_wechat|mate_wechat',$mphone)
                    ->where('last_trackday', 'not null')
                    ->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('customer_tel|mate_tel|customer_wechat|mate_wechat',$mphone)
                    ->where('last_trackday', 'not null')
                    ->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();
            
            // 男士信息为客资信息
            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'];
            }

            $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'];
        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('last_trackday', 'not null')->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('last_trackday', 'not null')->where('customer_tel|mate_tel|customer_wechat|mate_wechat',$param['mphone'])
                ->field('id,customer_number,'.$param['time'])->order($order)->find();
        }
        
        // 男士女士信息都存
        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;
    }
}