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

use think\Exception;
namespace app\index\api;


class Intostore
{
    /*
     * 分配接待人
     * @param id     进店表id  必填
     * @param consulation_shop_code        选填
     * @param consulation_shop  意向店面  选填
     * @param reception_id   必填
     * @param reception_name 选填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function allotReception($param){
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        if(empty($param['reception_id'])){
            return array('error'=>1,'code'=>101,'msg'=>'未获取到接待人id');
        }else{
            $data['reception_id'] = $param['reception_id'];
        }
        if(empty($param['reception_name'])){
            $staffinfo = getStaffInfoById($param['reception_id']);
            $reception_name = $staffinfo['staffname'];
        }

        $into = db('c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();
        if(!$into){
            return array('error'=>1,'code'=>102,'msg'=>'未通过进客编号获取到客资信息');
        }
        $data['reception_name'] = $param['reception_name'] ? trim($param['reception_name']) : $reception_name;

        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_tel,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code,reception_id,reception_name')->find();
        if(empty($info)){
            return array('error'=>1,'code'=>102,'msg'=>'未通过客资编号获取到客资信息');
        }
        $intostore = [
            'reception_id'=>$param['reception_id'],
            'reception_name'=>$data['reception_name'],
            'operate_id'=>$param['staff_id'],
            'operate_name'=>$param['staff_name'],
            'update_time'=>date('Y-m-d H:i:s'),
            'fp_rec_time'=>date('Y-m-d H:i:s'),
        ];
        if($param['consulation_shop_code']){
            $data['consulation_shop_code'] =trim($param['consulation_shop_code']);
            $intostore['consulation_shop_code'] = trim($param['consulation_shop_code']);
        }else{
            $intostore['consulation_shop_code'] = ($into['consulation_shop_code']);
        }
        if($param['consulation_shop']){
            $data['consulation_shop'] =trim($param['consulation_shop']);
            $intostore['consulation_shop_name'] = trim($param['consulation_shop']);
        }else{
            $intostore['consulation_shop_name'] = ($into['consulation_shop_name']);
        }
        db()->startTrans();
        try{
            db('c_customerinfo')->where('id',$into['cid'])->update($data);
            db('c_customer_intostore')->where('id',$param['id'])->update($intostore);
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $info['id'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = $param['staff_name'];
            $track['sales_staff_id'] = $param['staff_id'];
            $track['sales_remark'] = '客资标记';
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);

            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>$info['reception_name'] ? $info['reception_name'] : '',
                'data'=>'ERP分配接待人：'.$param['reception_name'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Intostore',
                'action'=>'allotReception',
            ];
            common_log($logData,'action_log');
            db()->commit();

            $return = $this->getCustomerInfo($param['id']);
            return $return;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>105,'msg'=>'分配接待人失败,原因：'.$e->getMessage());
        }
    }

    /*
     * 门市标记
     * @param id 进店id
     * @param op_signinfo   必填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function customerSign($param){
        $now = date('Y-m-d H:i:s');
        $op_signday = $param['op_signday'] ? date('Y-m-d H:i:s',strtotime($param['op_signday'])) : date('Y-m-d H:i:s');
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();


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

        if(empty($info)){
            return array('error'=>1,'code'=>102,'msg'=>'未通过客资编号获取到客资信息');
        }
        
        // 门市标记时，-- 进客表 --如果没有门市接待人员，则当前操作人为门市接待人员
        if (!$into['reception_name']) {
            // 进客数据
            $inData['reception_id']  = (int)$param['staff_id'];
            $inData['reception_name']= trim($param['staff_name']);
            // 客资数据
            $cData['reception_id']  = (int)$param['staff_id'];
            $cData['reception_name']= trim($param['staff_name']);
            $cData['update_time']   = $now;
        }
        // 如果进客表里有接待人员
        else{
            // 如果进客表里的接待人员与客资表里的接待人员不一样 则更新
            if ($into['reception_name'] != $info['reception_name']) {
                $cData['reception_id']  = (int)$into['reception_id'];
                $cData['reception_name']= trim($into['reception_name']);
                $cData['update_time']   = $now;
            }
        }
        // 操作人
        $inData['operate_id']  = (int)$param['staff_id'];
        $inData['operate_name']= trim($param['staff_name']);

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

        $update = [];
        $iUpdate= [];
        $new_data = '';
        $old_data = '';
        $edit = false;
        $iUpdate['update_time'] = date('Y-m-d H:i:s');

        if($param['entrance_type'] != 'appwxerp'){
            if($info['customer_name'] != $param['customer_name']){
                $update['customer_name'] = trim($param['customer_name']);
                $new_data .= '客资姓名：'.$update['customer_name'].'<br>';
                $old_data .= '客资姓名：'.trim($info['customer_name']).'<br>';
            }
            if($info['customer_tel'] != $param['customer_tel']){
                $update['customer_tel'] = trim($param['customer_tel']);
                $new_data .= '客资手机：'.$update['customer_tel'].'<br>';
                $new_data .= '客资手机：'.trim($info['customer_tel']).'<br>';
                $edit = true;
            }
            if($info['customer_sex'] != $param['customer_sex']){
                $update['customer_sex'] = trim($param['customer_sex']);
                $new_data .= '客资性别：'.$update['customer_sex'].'<br>';
                $old_data .= '客资性别：'.trim($info['customer_sex']).'<br>';
            }
            if($info['customer_wechat'] != $param['customer_wechat']){
                $update['customer_wechat'] = trim($param['customer_wechat']);
                $new_data .= '客资微信：'.$update['customer_wechat'].'<br>';
                $old_data .= '客资微信：'.trim($info['customer_wechat']).'<br>';
                $edit = true;
            }
            if($info['customer_qq'] != $param['customer_qq']){
                $update['customer_qq'] = trim($param['customer_qq']);
                $new_data .= '客资qq：'.$update['customer_qq'].'<br>';
                $old_data .= '客资qq：'.trim($info['customer_qq']).'<br>';
            }
            if($info['customer_birthday'] != $param['customer_birthday']){
                $update['customer_birthday'] = date('Y-m-d H:i:s', strtotime($param['customer_birthday']));
                $new_data .= '客户生日：'.$update['customer_birthday'].'<br>';
                $old_data .= '客户生日：'.$info['customer_birthday'].'<br>';
            }
            if($info['mate_name'] != $param['mate_name']){
                $update['mate_name'] = trim($param['mate_name']);
                $new_data .= '配偶姓名：'.$update['mate_name'].'<br>';
                $old_data .= '配偶姓名：'.trim($info['mate_name']).'<br>';
            }
            if($info['mate_sex'] != $param['mate_sex']){
                $update['mate_sex'] = trim($param['mate_sex']);
                $new_data .= '配偶性别：'.$update['mate_sex'].'<br>';
                $old_data .= '配偶性别：'.trim($info['mate_sex']).'<br>';
            }
            if($info['mate_tel'] != $param['mate_tel']){
                $update['mate_tel'] = trim($param['mate_tel']);
                $new_data .= '配偶手机：'.$update['mate_tel'].'<br>';
                $old_data .= '配偶手机：'.trim($info['mate_tel']).'<br>';
                $edit = true;
            }
            if($info['mate_wechat'] != $param['mate_wechat']){
                $update['mate_wechat'] = trim($param['mate_wechat']);
                $new_data .= '配偶微信：'.$update['mate_wechat'].'<br>';
                $old_data .= '配偶微信：'.trim($info['mate_wechat']).'<br>';
                $edit = true;
            }
            if($info['mate_qq'] != $param['mate_qq']){
                $update['mate_qq'] = trim($param['mate_qq']);
                $new_data .= '配偶qq：'.$update['mate_qq'].'<br>';
                $old_data .= '配偶qq：'.trim($info['mate_qq']).'<br>';
            }
            if($info['mate_birthday'] != $param['mate_birthday']){
                $update['mate_birthday'] = date('Y-m-d H:i:s', strtotime($param['mate_birthday']));
                $new_data .= '配偶生日：'.$update['mate_birthday'].'<br>';
                $old_data .= '配偶生日：'.$info['mate_birthday'].'<br>';
            }
            if($info['marry_day'] != $param['marry_day']){
                $update['marry_day'] = date('Y-m-d H:i:s', strtotime($param['marry_day']));
                $new_data .= '结婚日期：'.$update['marry_day'].'<br>';
                $old_data .= '结婚日期：'.$info['marry_day'].'<br>';
            }
            if($info['yp_day'] != $param['yp_day']){
                $update['yp_day'] = date('Y-m-d H:i:s', strtotime($param['yp_day']));
                $new_data .= '预拍日期：'.$update['yp_day'].'<br>';
                $old_data .= '预拍日期：'.$info['yp_day'].'<br>';
            }
            if($info['customer_address'] != $param['customer_address']){
                $update['customer_address'] = trim($param['customer_address']);
                $new_data .= '客资地址：'.$update['customer_address'].'<br>';
                $old_data .= '客资地址：'.trim($info['customer_address']).'<br>';
            }
           
            if($param['consulation_shop_code'] && $info['consulation_shop_code'] != $param['consulation_shop_code']){
                $update['consulation_shop'] = trim($param['consulation_shop_name']);
                $update['consulation_shop_code'] = intval($param['consulation_shop_code']);
                $iUpdate['consulation_shop_name'] = trim($param['consulation_shop']);
                $iUpdate['consulation_shop_code'] = intval($param['consulation_shop_code']);
                $new_data .= '接待店面：'.$update['consulation_shop'].'<br>';
                $old_data .= '接待店面：'.trim($info['consulation_shop']).'<br>';
            }
            if($info['customer_area'] != $param['customer_area']){
                $update['customer_area'] = trim($param['customer_area']);
                 $update['customer_area_id'] = intval($param['customer_area_id']);
                $new_data .= '客资分区：'.$update['customer_area'].'<br>';
                $old_data .= '客资分区：'.trim($info['customer_area']).'<br>';
            }
            if($info['customer_orderaddress'] != $param['customer_orderaddress']){
                $update['customer_orderaddress'] = trim($param['customer_orderaddress']);
                $new_data .= '接单点：'.$update['customer_orderaddress'].'<br>';
                $old_data .= '接单点：'.trim($info['customer_orderaddress']).'<br>';
            }
            if($info['customer_intention'] != $param['customer_intention']){
                $update['customer_intention'] = trim($param['customer_intention']);
                $new_data .= '客户意向：'.$update['customer_intention'].'<br>';
                $old_data .= '客户意向：'.trim($info['customer_intention']).'<br>';
            }
            if($info['intostore_note'] != $param['intostore_remark']){
                $update['intostore_note'] = trim($param['intostore_remark']);
                $iUpdate['intostore_remark'] = trim($param['intostore_remark']);
                $new_data .= '进店备注：'.$update['intostore_remark'].'<br>';
                $old_data .= '进店备注：'.trim($info['intostore_remark']).'<br>';
            }

            if($info['baby_name'] != $param['baby_name']){
                $update['baby_name'] = trim($param['baby_name']);
                $new_data .= '宝宝姓名：'.$update['baby_name'].'<br>';
                $old_data .= '宝宝姓名：'.trim($info['baby_name']).'<br>';
            }
            if($info['baby_sex'] != $param['baby_sex']){
                $update['baby_sex'] = trim($param['baby_sex']);
                $new_data .= '宝宝性别：'.$update['baby_sex'].'<br>';
                $old_data .= '宝宝性别：'.trim($info['baby_sex']).'<br>';
            }
            if($info['baby_birthday'] != $param['baby_birthday']){
                $update['baby_birthday'] = date('Y-m-d H:i:s', strtotime($param['baby_birthday']));
                $new_data .= '宝宝生日：'.$update['baby_birthday'].'<br>';
                $old_data .= '宝宝生日：'.trim($info['baby_birthday']).'<br>';
            }
            if($info['ready_baby_day'] != $param['ready_baby_day']){
                $update['ready_baby_day'] = date('Y-m-d H:i:s', strtotime($param['ready_baby_day']));
                $new_data .= '预产期：'.$update['ready_baby_day'].'<br>';
                $old_data .= '预产期：'.trim($info['ready_baby_day']).'<br>';
            }
            if($info['baby_address'] != $param['baby_address']){
                $update['baby_address'] = trim($param['baby_address']);
                $new_data .= '出生医院：'.$update['baby_address'].'<br>';
                $old_data .= '出生医院：'.trim($info['baby_address']).'<br>';
            }
            if($info['customer_cource'] != $param['customer_cource']){
                $update['customer_cource'] = trim($param['customer_cource']);
                $update['customer_cource_id'] = intval($param['customer_cource_id']);
                $new_data .= '客资来源：'.$update['customer_cource'].'<br>';
                $old_data .= '客资来源：'.trim($info['customer_cource']).'<br>';
            }
            if($info['consultation_type'] != $param['consultation_type']){
                $update['consultation_type_id'] = intval($param['consultation_type_id']);
                $update['consultation_type'] = trim($param['consultation_type']);
                $new_data .= '消费类型：'.$update['consultation_type'].'<br>';
                $old_data .= '消费类型：'.trim($info['consultation_type']).'<br>';
            }
            if( $param['reception_name'] && $info['reception_name'] != $param['reception_name']){
                $update['reception_name'] = trim($param['reception_name']);
                $update['reception_id'] = intval($param['reception_id']);
                $iUpdate['reception_name'] = trim($param['reception_name']);
                $iUpdate['reception_id'] = intval($param['reception_id']);
                $new_data .= '接待人：'.$update['reception_name'].'<br>';
                $old_data .= '接待人：'.trim($info['reception_name']).'<br>';
            }

            if($info['operate_id'] != $param['staff_id']){
                $iUpdate['operate_id'] = intval($param['staff_id']);
                $iUpdate['operate_name'] = trim($param['staff_name']);
                $new_data .= '操作人：'.$update['staff_name'].'<br>';
                $old_data .= '操作人：'.trim($info['staff_name']).'<br>';
            }
        }else{
            if($param['op_signinfo'] && $into['op_signinfo'] != $param['op_signinfo'] ){
                $iUpdate['op_signinfo'] = trim($param['op_signinfo']);
                $iUpdate['op_signday'] = date('Y-m-d H:i:s');
                $new_data .= '门市标记：'.$iUpdate['op_signinfo'].'<br>';
                $old_data .= '门市标记：'.trim($into['op_signinfo']).'<br>';
            }
            if($param['customer_cource'] && $info['customer_cource'] != $param['customer_cource'] ){
                $update['customer_cource'] = trim($param['customer_cource']);
                $update['customer_cource_id'] = intval($param['customer_cource_id']);
                $new_data .= '客资来源：'.$update['customer_cource'].'<br>';
                $old_data .= '客资来源：'.trim($info['customer_cource']).'<br>';
            }
            if($param['consultation_type'] && $info['consultation_type'] != $param['consultation_type'] ){
                $update['consultation_type_id'] = intval($param['consultation_type_id']);
                $update['consultation_type'] = trim($param['consultation_type']);
                $new_data .= '消费类型：'.$update['consultation_type'].'<br>';
                $old_data .= '消费类型：'.trim($info['consultation_type']).'<br>';
            }
            if($param['reception_name'] && $info['reception_name'] != $param['reception_name']){
                $update['reception_name'] = trim($param['reception_name']);
                $update['reception_id'] = intval($param['reception_id']);
                $iUpdate['reception_name'] = trim($param['reception_name']);
                $iUpdate['reception_id'] = intval($param['reception_id']);
                $new_data .= '接待人：'.$update['reception_name'].'<br>';
                $old_data .= '接待人：'.trim($info['reception_name']).'<br>';
            }

            if($info['operate_id'] != $param['staff_id']){
                $iUpdate['operate_id'] = intval($param['staff_id']);
                $iUpdate['operate_name'] = trim($param['staff_name']);
                $new_data .= '操作人：'.$update['staff_name'].'<br>';
                $old_data .= '操作人：'.trim($info['staff_name']).'<br>';
            }
        }
        
        db()->startTrans();
        try{
            db('c_customerinfo')->where('id',$into['cid'])->update($update);
            db('c_customer_intostore')->where('id',$param['id'])->update($iUpdate);

            if($info['c_from'] == 1 && $edit){ //说明联系方式有改动，这里要更新排重表  只更新CRM过去的客资
                $new_contact = db('c_customerinfo')->where('id',$into['cid'])->field('customer_tel,mate_tel,customer_wechat,mate_wechat')->find();
                db('c_customer_contact')->where('c_id',$into['cid'])->delete();
                $contact = [];
                foreach($new_contact as $k=>$v){
                    if($v){
                        $arr['c_id'] = $into['cid'];
                        $arr['contact'] = $v;
                        $arr['brandclass'] = $info['brandclass'];
                        array_push($contact,$arr);
                    }
                }
                db('c_customer_contact')->insertAll($contact);
            }
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $info['id'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = trim($param['staff_name']);
            $track['sales_staff_id'] = intval($param['staff_id']);
            $track['sales_remark'] = 'ERP进客备注：'.trim($param['intostore_remark']);
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>$old_data,
                'data'=>$new_data,
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'crm',
                'controller'=>'Intostore',
                'action'=>'customerinfo',
            ];
            common_log($logData,'action_log');
            db()->commit();
            $return = $this->getCustomerInfo($param['id']);
            return $return;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>105,'msg'=>'客资编辑失败,原因：'.$e->getMessage());
        }
    }
    /*
     * 领取礼品
     * @param id 进店id
     * @param giftinfo   礼品情况  必填
     * @param costs      礼品成本  选填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function gift($param){
        $now = date('Y-m-d H:i:s');
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code,is_intostore,syjd_day,reception_id,reception_name')->find();
        if(empty($info)){
            return array('error'=>1,'code'=>102,'msg'=>'未通过客资编号获取到客资信息');
        }
        $inData = [];
        if($param['giftinfo']){
            $inData['giftinfo'] = trim(trim($param['giftinfo'],','));
        }
        if($param['costs']){
            $inData['costs'] = trim($param['costs']);
        }

        // 领取礼品时，-- 客资表 -- 如果客资没有进店，则标记进店进店，记录进店时间
        if (!$info['syjd_day']) {
            $cData['syjd_day']    = $now;
            $cData['is_intostore']= 2;
        }
        
        // 领取礼品时，-- 进客表 --如果没有门市接待人员，则当前操作人为门市接待人员
        if (!$into['reception_name']) {
            // 进客数据
            $inData['reception_id']  = (int)$param['staff_id'];
            $inData['reception_name']= trim($param['staff_name']);
            // 客资数据
            $cData['reception_id']  = (int)$param['staff_id'];
            $cData['reception_name']= trim($param['staff_name']);
            $cData['update_time']   = $now;
        }
        // 如果进客表里有接待人员
        else{
            // 如果进客表里的接待人员与客资表里的接待人员不一样 则更新
            if ($into['reception_name'] != $info['reception_name']) {
                $cData['reception_id']  = (int)$into['reception_id'];
                $cData['reception_name']= trim($into['reception_name']);
                $cData['update_time']   = $now;
            }
        }

        // 领取礼品时，-- 进客表 --如果没有实际进店时间 则标记进店进客，记录进店时间
        if (!$into['syjd_day']) {
            $inData['syjd_day']    = $now;
            $inData['is_intostore']= 2; 
        }
        
        $inData['update_time'] = $now;
        $inData['operate_id']  = (int)$param['staff_id'];
        $inData['operate_name']= trim($param['staff_name']);
        db()->startTrans();
        try{
            db('c_customer_intostore')->where('id',$param['id'])->update($inData);
            if (!empty($cData)) {
                db('c_customerinfo')->where('id',$info['id'])->update($cData);
            }
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $into['cid'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = $now;
            $track['sales_staff'] = ($param['staff_name']);
            $track['sales_staff_id'] = ($param['staff_id']);
            $track['sales_remark'] = '领取礼品:'.$param['giftinfo'];
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>$now,
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'领取礼品:'.$param['giftinfo'].';成本:'.$param['costs'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Intostore',
                'action'=>'gift',
            ];
            common_log($logData,'action_log');
            db()->commit();
            $return = $this->getCustomerInfo($param['id']);
            return $return;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>105,'msg'=>'领取礼品失败','data'=>$e->getMessage());
        }
    }
    /*
     * 流失  该接口已废弃
     * @param id 进店id
     * @param loss_reason   流失原因  必填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function loss($param){
        $loss_time = $param['loss_time'] ? date('Y-m-d H:i:s',strtotime($param['loss_time'])) : date('Y-m-d H:i:s');
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code,is_success')->find();
        if(empty($info)){
            return array('error'=>1,'code'=>102,'msg'=>'未通过进店ID获取到数据');
        }
        if($into['is_success'] == 1 || $into['is_success'] == 3){
            return array('error'=>1,'code'=>103,'msg'=>'已成单客资不能标记流失');
        }
        $inData = [];
        if($param['loss_reason']){
            $inData['loss_reason'] = $param['loss_reason'] ? trim($param['loss_reason']) : NULL;

            $cData['erp_loss_reason'] = $param['loss_reason'] ? trim($param['loss_reason']) : NULL;
            $cData['erp_loss_time'] = $loss_time;
        }
        
        if(empty($info['syjd_day']) || in_array($info['is_intostore'], [1,4])){
            $cData['syjd_day'] = $loss_time;
            $cData['is_intostore'] = 5;
            $cData['erp_loss'] = 2;
        }
        
        $inData['is_intostore'] = 5;
        // $inData['sys_loss'] = 2;
        $inData['update_time'] = date('Y-m-d H:i:s');
        $inData['syjd_day'] = $loss_time;
        $inData['loss_time'] = $loss_time;
        $inData['operate_id']  = (int)$param['staff_id'];
        $inData['operate_name']= trim($param['staff_name']);

        db()->startTrans();
        try{
            db('c_customer_intostore')->where('id',$param['id'])->update($inData);
            db('c_customerinfo')->where('id',$into['cid'])->update($cData);
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $into['cid'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = ($param['staff_name']);
            $track['sales_staff_id'] = ($param['staff_id']);
            $track['sales_remark'] = 'ERP标记流失'.$param['loss_reason'];
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'ERP标记流失:'.$param['loss_reason'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Intostore',
                'action'=>'loss',
            ];
            common_log($logData,'action_log');
            db()->commit();
            $return = $this->getCustomerInfo($param['id']);
            return $return;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>105,'msg'=>'标记流失失败','data'=>$e->getMessage());
        }
    }
    /*
     * 标记未进店
     * @param id         进店id
     * @param remark     未进店备注
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function notIntostore($param){
        $date = date('Y-m-d H:i:s');
        $into_id = (int)$param['id'];
        if(!$param['id']){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$into_id)->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        if($into['is_intostore']==2 || $into['is_intostore']==3 || $into['is_intostore']==5){
            return array('error'=>1,'code'=>102,'msg'=>'已进店客资不能标记为‘未进店’');
        }
        $cInfo= db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,sales_staff_number,shop_name,shop_code,is_success,is_intostore,syjd_day,brandclass_id,dj_staff_id,dj_staff,reception_id,reception_name')->find();
        if(empty($cInfo)){
            return array('error'=>1,'code'=>103,'msg'=>'未获取到客资数据');
        }
        // 进店表
        $iData['intostore_remark']= $into['intostore_remark'].';'.trim($param['remark']);
        $iData['is_intostore']    = 4;
        // 客资表
        if ($cInfo['is_intostore']==1) {
            $cData['is_intostore'] = 4;
        }

        // 进客等操作时，-- 进客表 --如果没有门市接待人员，则当前操作人为门市接待人员
        if (!$into['reception_name']) {
            // 进客数据
            $iData['reception_id']  = (int)$param['staff_id'];
            $iData['reception_name']= trim($param['staff_name']);
            // 客资数据
            $cData['reception_id']  = (int)$param['staff_id'];
            $cData['reception_name']= trim($param['staff_name']);
            $cData['update_time']   = $now;
        }
        // 如果进客表里有接待人员
        else{
            // 如果进客表里的接待人员与客资表里的接待人员不一样 则更新
            if ($into['reception_name'] != $info['reception_name']) {
                $cData['reception_id']  = (int)$into['reception_id'];
                $cData['reception_name']= trim($into['reception_name']);
                $cData['update_time']   = $now;
            }
        }
        // 操作人
        $iData['operate_id']  = (int)$param['staff_id'];
        $iData['operate_name']= trim($param['staff_name']);

        db()->startTrans();
        try {
            if (!empty($cData)) {
                db('c_customerinfo')->where('id', $cInfo['id'])->update($cData);
            }
            db('c_customer_intostore')->where('id',$into_id)->update($iData);
            //删除pool表预约未进店提醒
            db('c_fp_pool')->where('cid',$into['cid'])->where('pool_type',11)->delete();

            // 发消息 记录追踪记录
            $messageD['send_type']      = 1;
            $messageD['send_time']      = $date;
            $messageD['send_title']     = '标记提醒';
            $messageD['send_msg']       = '您有一笔客资已标记为：邀约未进店,'.trim($param['remark']);
            $messageD['receive_status'] = 1;
            $messageD['receive_time']   = $date;
            $messageD['operation_type'] = 2;
            $messageD['operation']      = '';
            $timeOut = db_config('fp_timeout_'.$cInfo['shop_code']);
            $messageD['time_out']       = $timeOut ? $timeOut : 60;
            $remind = getRemind($cInfo['brandclass_id']);
            // 弹窗消息
            if(in_array('tan',$remind['jd']['send_method']) && in_array('dj',$remind['jd']['send_receive'])){
                $messageD['receive_id']     = $cInfo['dj_staff_id'];
                $messageD['receive_name']   = $cInfo['dj_staff'];
                $resM = sendSystemMessage($messageD);
            }
            if($cInfo['sales_staff_id'] && in_array('tan',$remind['jd']['send_method']) && in_array('sales',$remind['jd']['send_receive'])){
                $messageD['receive_id']     = $cInfo['sales_staff_id'];
                $messageD['receive_name']   = $cInfo['sales_staff'];
                $resM = sendSystemMessage($messageD);
            }
            // 发送微信模板消息
            if(in_array('tui',$remind['jd']['send_method']) && in_array('dj',$remind['jd']['send_receive'])){
                $content = [
                    'touser'       => $cInfo['dj_staff_id'],
                    'template_id'  => OPENTM_YX,
                    'data'         => [
                        'first'=>[
                            'value'=> $messageD['send_msg'],
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $cInfo['customer_name'],
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $cInfo['sales_staff'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> $date,
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> 'ID:'.$cInfo['id'].'，手机：'.$cInfo['customer_tel'].'，请尽快查看，谢谢',
                            'color'=> '#173177'
                        ],
                    ],
                ];
                $send_data['content'] = json_encode($content);
                $res = sendMsg($send_data);
            }
            if($cInfo['sales_staff_id'] && in_array('tui',$remind['jd']['send_method']) && in_array('sales',$remind['jd']['send_receive'])){
                $content = [
                    'touser'       => $cInfo['sales_staff_id'],
                    'template_id'  => OPENTM_YX,
                    'data'         => [
                        'first'=>[
                            'value'=> $messageD['send_msg'],
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $cInfo['customer_name'],
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $cInfo['sales_staff'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> $date,
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> 'ID:'.$cInfo['id'].'，手机：'.$cInfo['customer_tel'].'，请尽快查看，谢谢',
                            'color'=> '#173177'
                        ],
                    ],
                ];
                $send_data['content'] = json_encode($content);
                $res = sendMsg($send_data);
            }
            // 追踪数据
            $track['gtType']         = 4;
            $track['customer_id']    = $cInfo['id'];
            $track['customer_name']  = $cInfo['customer_name'];
            $track['customer_number']= $cInfo['customer_number'];
            $track['sales_day']      = date('Y-m-d H:i:s');
            $track['sales_staff']    = $param['staff_name'];
            $track['sales_staff_id'] = $param['staff_id'];
            $track['sales_remark']   = '标记邀约未进店:'.trim($param['remark']);
            $track['shop_code']      = trim($cInfo['shop_code']);
            $track['shop_name']      = trim($cInfo['shop_name']);
            $track['no_track']       = 'erp标记';
            db('c_salestrackinginfo')->insert($track);

            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'标记邀约未进店:'.trim($param['remark']),
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Intostore',
                'action'=>'intostore',
            ];
            common_log($logData,'action_log');
            db()->commit();
            $return = $this->getCustomerInfo($into_id);
            return $return;
        } catch (\Exception $e) {
            db()->rollback();
            return array('error'=>1,'code'=>110,'msg'=>'标记未进店失败','data'=>$e->getMessage());
        }

    }
    /*
     * 进客 进店非进客
     * @param id 进店id
     * @param is_intostore   进店(2:进店进客 3:进店非进客 4:邀约未进店 5:进店流失)  必填
     * @param syjd_day
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function intostore($param){
        $syjd_day = $param['syjd_day']&&$param['syjd_day']!='false' ? date('Y-m-d H:i:s',strtotime($param['syjd_day'])) : date('Y-m-d H:i:s');
        $now = date('Y-m-d H:i:s');
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code,is_success,is_intostore,syjd_day,brandclass_id,dj_staff_id,dj_staff,reception_id,reception_name')->find();
        if(empty($info)){
            return array('error'=>1,'code'=>102,'msg'=>'未获取到客资数据');
        }
        if($into['is_success'] == 1 || $into['is_success'] == 3){
            return array('error'=>1,'code'=>103,'msg'=>'已成单客资不能再标记');
        }
        if($param['is_intostore'] == 1 && $into['is_intostore'] > 1){
            return array('error'=>1,'code'=>104,'msg'=>'不能标为未进店');
        }
        if($param['is_intostore'] == $into['is_intostore'] && date('Ymd',strtotime($param['syjd_day']))<>date('Ymd') && $param['is_intostore']!=5){
            return array('error'=>1,'code'=>105,'msg'=>'已是此进店状态，不能重复标记');
        }
        if($param['is_intostore'] == 2 && ($into['is_intostore'] == 5)){
            return array('error'=>1,'code'=>106,'msg'=>'已是进店流失，不能标为进店进客,你可以直接转订单或创建回门');
        }
        // if($param['is_intostore'] == 4 && $into['is_intostore'] > 1){
        //     return array('error'=>1,'code'=>107,'msg'=>'不能标为邀约流失');
        // }
        if($param['is_intostore'] == 4){ 
            $syjd_day = NULL;
        }else{
            if ( date('Ymd', strtotime($syjd_day)) <> date('Ymd', strtotime($into['yjd_day']))) {
                return array('error'=>1,'code'=>108,'msg'=>'预约日期与实际进店日期不一致，请确认！');
            }
        }
        
        $inData = [];
        $cData = [];
        $msg = '';
        if($param['is_intostore'] == 5){
            $inData['loss_reason'] = trim($param['loss_reason']);
            $inData['loss_time'] = $syjd_day;
            $inData['syjd_day']  = $syjd_day;
            $inData['is_intostore'] = 5;

            if (!$info['syjd_day'] || date('Ymd',strtotime($info['syjd_day']))==date('Ymd',strtotime($param['syjd_day']))) {
                $cData['is_intostore'] = 5;
                $cData['syjd_day'] = $syjd_day;
            }
            $cData['erp_loss_reason'] = $param['loss_reason'] ? trim($param['loss_reason']) : NULL;
            $cData['erp_loss_time'] = $syjd_day;
            $cData['erp_loss'] = 2;

            $msg = '进店流失';
        }else if ($param['is_intostore'] == 4) {
            if (!$info['syjd_day'] || date('Ymd',strtotime($info['syjd_day']))==date('Ymd',strtotime($param['syjd_day']))) {
                $cData['is_intostore'] = 4;
                $cData['syjd_day'] = $syjd_day;
            }
            
            $inData['syjd_day']    = $syjd_day;
            $inData['is_intostore']= 4  ;
            $msg = '邀约未进店';
        }else{
            if($param['is_intostore'] > 1 && $param['is_intostore'] < 4){
                if (!$info['syjd_day']) {
                    $cData['syjd_day'] = $syjd_day;
                }
                $cData['is_intostore'] = $param['is_intostore'];
                $cData['erp_loss_time'] = NULL;
                // $cData['erp_loss_reason'] =  NULL;
                $cData['erp_loss'] = 1;

                // $inData['loss_reason'] = NULL;
                $inData['is_intostore'] = $param['is_intostore'];
                $inData['syjd_day'] = $syjd_day;
                $inData['loss_time'] = NULL;
                
                $msg = $param['is_intostore'] == 3 ? '进店非进客' : '进店进客';
            }
        }
        //进店必须有进店时间
        if(($param['is_intostore'] == 2 || $param['is_intostore'] == 3||$param['is_intostore'] == 5) && empty($syjd_day)){
            return array('error'=>1,'code'=>109,'msg'=>'进店不能没有进店时间');
        }
        $inData['update_time'] = date('Y-m-d H:i:s');
        $remind = getRemind($info['brandclass_id']);

        // 进客等操作时，-- 进客表 --如果没有门市接待人员，则当前操作人为门市接待人员
        if (!$into['reception_name']) {
            // 进客数据
            $inData['reception_id']  = (int)$param['staff_id'];
            $inData['reception_name']= trim($param['staff_name']);
            // 客资数据
            $cData['reception_id']  = (int)$param['staff_id'];
            $cData['reception_name']= trim($param['staff_name']);
            $cData['update_time']   = $now;
        }
        // 如果进客表里有接待人员
        else{
            // 如果进客表里的接待人员与客资表里的接待人员不一样 则更新
            if ($into['reception_name'] != $info['reception_name']) {
                $cData['reception_id']  = (int)$into['reception_id'];
                $cData['reception_name']= trim($into['reception_name']);
                $cData['update_time']   = $now;
            }
        }
        // 操作人
        $inData['operate_id']  = (int)$param['staff_id'];
        $inData['operate_name']= trim($param['staff_name']);
        db()->startTrans();
        try{
            if (!empty($cData)) {
                db('c_customerinfo')->where('id', $info['id'])->update($cData);
            }

            db('c_customer_intostore')->where('id',$param['id'])->update($inData);
            //删除pool表预约未进店提醒
            db('c_fp_pool')->where('cid',$into['cid'])->where('pool_type',11)->delete();
            $messageD['send_type']      = 1;
            $messageD['send_time']      = $inData['update_time'];
            $messageD['send_title']     = 'ERP进店标记提醒';
            $messageD['send_msg']       = '您有一笔客资ID为：'.$param['id'].'，已标记为：'.$msg.',请确认';
            $messageD['customer_id']    = $param['id'];
            $messageD['receive_status'] = 1;
            $messageD['receive_time']   = $inData['update_time'];
            $messageD['operation_type'] = 2;
            $messageD['operation']      = '';
            $timeOut = db_config('fp_timeout_'.$info['shop_code']);
            $messageD['time_out']       = $timeOut ? $timeOut : 60;

            if(in_array('tan',$remind['jd']['send_method']) && in_array('dj',$remind['jd']['send_receive'])){
                $messageD['receive_id']     = $info['dj_staff_id'];
                $messageD['receive_name']   = $info['dj_staff'];
                $resM = sendSystemMessage($messageD);
            }
            if($info['sales_staff_id'] && in_array('tan',$remind['jd']['send_method']) && in_array('sales',$remind['jd']['send_receive'])){
                $messageD['receive_id']     = $info['sales_staff_id'];
                $messageD['receive_name']   = $info['sales_staff'];
                $resM = sendSystemMessage($messageD);
            }
            // 发送微信模板消息
            if(in_array('tui',$remind['jd']['send_method']) && in_array('dj',$remind['jd']['send_receive'])){
                $content = [
                    'touser'       => $info['dj_staff_id'],
                    'template_id'  => OPENTM_YX,
                    'data'         => [
                        'first'=>[
                            'value'=> $messageD['send_msg'],
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $info['customer_name'],
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $info['sales_staff'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> $inData['update_time'],
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> 'ID:'.$info['id'].'，手机：'.$info['customer_tel'].'，请尽快查看，谢谢',
                            'color'=> '#173177'
                        ],
                    ],
                ];
                $send_data['content'] = json_encode($content);
                $res = sendMsg($send_data);
            }
            if($info['sales_staff_id'] && in_array('tui',$remind['jd']['send_method']) && in_array('sales',$remind['jd']['send_receive'])){
                $content = [
                    'touser'       => $info['sales_staff_id'],
                    'template_id'  => OPENTM_YX,
                    'data'         => [
                        'first'=>[
                            'value'=> $messageD['send_msg'],
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $info['customer_name'],
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $info['sales_staff'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> $inData['update_time'],
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> 'ID:'.$info['id'].'，手机：'.$info['customer_tel'].'，请尽快查看，谢谢',
                            'color'=> '#173177'
                        ],
                    ],
                ];
                $send_data['content'] = json_encode($content);
                $res = sendMsg($send_data);
            }
            if($param['is_intostore']==2){
                $des = '进店进客';
            }elseif($param['is_intostore']==3){
                $des = '进店非进客';
            }elseif($param['is_intostore']==4){
                $des = '邀约未进店';
            }elseif($param['is_intostore']==5){
                $des = '进店流失';
            }
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $into['cid'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = ($param['staff_name']);
            $track['sales_staff_id'] = ($param['staff_id']);
            $track['sales_remark'] = '标记进客/非进客:'.$des;
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);

            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'标记进客/非进客:'.$des,
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Intostore',
                'action'=>'intostore',
            ];
            common_log($logData,'action_log');
            db()->commit();
            $return = $this->getCustomerInfo($param['id']);
            return $return;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>110,'msg'=>'标记进客/非进客失败','data'=>$e->getMessage());
        }
    }

    /*
     * 删除进店
     * @param id 进店id
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function deleteInto($param){
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        if(!empty($into['giftinfo'])){
            return array('error'=>1,'code'=>102,'msg'=>'已领取礼品，不能删除');
        }
        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code')->find();
        if(empty($into)){
            return array('error'=>1,'code'=>103,'msg'=>'未通过进店ID获取到客资数据');
        }
        $inorder = db('c_customer_order')->where('into_id',$param['id'])->find();
        if(!empty($into['order_sn'])){
            return array('error'=>1,'code'=>104,'msg'=>'已转单，不能删除');
        }

        $inData = [];
        $inData['status']      = 99;
        $inData['operate_id']  = (int)$param['staff_id'];
        $inData['operate_name']= trim($param['staff_name']);

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

        if(date('Ymd',strtotime($into['yjd_day'])) >= date('Ymd')){
            return array('error'=>1,'code'=>102,'msg'=>'预约在今天或之后，不可回门');
        }
        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code,is_intostore,syjd_day,is_loss,erp_loss')->find();
        if(empty($info)){
            return array('error'=>1,'code'=>103,'msg'=>'未通过进店ID获取到数据');
        }
        if($info['is_intostore'] == 1 || $info['is_intostore'] == 4){
            return array('error'=>1,'code'=>104,'msg'=>'未进店客资不可回门！');
        }
        $inData = [];
        $cData = [];
        if($param['reception_id']){
            $inData['reception_id'] = intval($param['reception_id']);
        }
        if($param['reception_name']){
            $inData['reception_name'] = trim($param['reception_name']);
        }
        if($param['fp_rec_time']){
            $inData['fp_rec_time'] = ($param['fp_rec_time']);
        }
        if($into['consulation_shop_code']){
            $inData['consulation_shop_code'] = $param['consulation_shop_code'] ? trim($param['consulation_shop_code']) : trim($into['consulation_shop_code']);
            $cData['consulation_shop_code'] = $param['consulation_shop_code'] ? trim($param['consulation_shop_code']) : trim($into['consulation_shop_code']);
        }
        if($into['consulation_shop_name']){
            $inData['consulation_shop_name'] = trim($into['consulation_shop_name']);
            $cData['consulation_shop'] = trim($into['consulation_shop_name']);
        }
        if($into['operate_id']){
            $inData['operate_id'] = intval($param['staff_id']);
        }
        if($into['operate_name']){
            $inData['operate_name'] = trim($param['staff_name']);
        }

        $inData['cid'] = $into['cid'];
        $inData['yjd_day'] = $param['yjd_day'] ? date('Y-m-d H:i:s',strtotime($param['yjd_day'])) : date('Y-m-d H:i:s');
        $inData['syjd_day'] = $param['yjd_day'] ? date('Y-m-d H:i:s',strtotime($param['yjd_day'])) : date('Y-m-d H:i:s');
        $inData['create_time'] = date('Y-m-d H:i:s');
        $inData['is_intostore'] = 2;
        $inData['is_success'] = 2;
        $inData['reback'] = 2;


        $cData['yjd_day'] = $param['yjd_day'] ? date('Y-m-d H:i:s',strtotime($param['yjd_day'])) : date('Y-m-d H:i:s');
        $cData['yjd_action_day'] = date('Y-m-d H:i:s');
        if($info['is_intostore'] == 1 || $info['is_intostore'] == 4){
            $cData['is_intostore'] = 2;
            $cData['syjd_day'] = $param['yjd_day'] ? date('Y-m-d H:i:s',strtotime($param['yjd_day'])) : date('Y-m-d H:i:s');
        }
        if($info['is_loss'] == 1){
            $cData['is_loss'] = 2;
            $cData['loss_cause'] = NULL;
            $cData['loss_remark'] = NULL;
            $cData['loss_day'] = NULL;
        }
        if($info['erp_loss'] == 2){
            $cData['erp_loss'] = 1;
            $cData['erp_loss_reason'] = NULL;
            $cData['erp_loss_time'] = NULL;
        }
        db()->startTrans();
        try{
            $id = db('c_customer_intostore')->insertGetId($inData);
            db('c_customerinfo')->where('id',$into['cid'])->update($cData);
            // 追踪数据
            $track['gtType'] = 4;
            $track['customer_id'] = $into['cid'];
            $track['customer_name'] = $info['customer_name'];
            $track['customer_number'] = $info['customer_number'];
            $track['sales_day'] = date('Y-m-d H:i:s');
            $track['sales_staff'] = ($param['staff_name']);
            $track['sales_staff_id'] = ($param['staff_id']);
            $track['sales_remark'] = '回门';
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'回门',
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Intostore',
                'action'=>'returnDoor',
            ];
            common_log($logData,'action_log');
            db()->commit();
            $return = $this->getCustomerInfo($id);
            return $return;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>109,'msg'=>'回门失败','data'=>$e->getMessage());
        }
    }
    /*
     * 进客列表
     * @param search_time    查询时间方式      选填
     * @param content    精确查询内容      选填
     * @param start    end    开始结束时间     选填
     * @param flag          查询标记     选填
     * @param reception_id   接待人id  选填
     * @param sales_staff_id 网销员工ID  选填
     * @param customer_intention_id   客户意向  选填
     * @param consulation_shop_code   意向店面  选填   可查询多个  查的归属店
     * @param consultation_type_id   消费类型  选填
     * @param customer_cource_id   客户来源  选填
     * @param dj_staff_id   客户来源  选填
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * @param limit 条数
     * @param page 页数
     * @param reception_id_is_null 如果等于1，查询包含接待人为空的
     * */
    public function customerList($param){
        $where = [];
        if($param['search_time']){
            if($param['search_time'] == 'yjd_day' || $param['search_time'] == 'syjd_day' || $param['search_time'] == 'fp_rec_time'){
                $param['search_time'] = 'i.'.$param['search_time'];
            }else{
                $param['search_time'] = 'c.'.$param['search_time'];
            }
        }else{
            $param['search_time'] = 'i.yjd_day';
        }
        if($param['start']){
            $start = date('Y-m-d',strtotime($param['start']));
        }else{
            $start = date('Y-m-d');
        }
        if($param['end']){
            $end = date('Y-m-d 23:59:59',strtotime($param['end']));
        }else{
            $end = date('Y-m-d 23:59:59');
        }
        if($param['dj_staff_id']){
            $where['c.dj_staff_id'] = intval($param['dj_staff_id']);
        }

        if($param['reception_id']){
            // $where['i.reception_id'] = intval($param['reception_id']);
            if($param['reception_id_is_null'] == 1){
                $r_sql = ' (i.reception_id is null or i.reception_id="" or i.reception_id='.$param['reception_id'].') ';
            }else{
                // $where['i.reception_id'] = intval($param['reception_id']);
                $r_sql = ' i.reception_id='.$param['reception_id'];
            }
        }
        // 网销员工
        if ((int)$param['sales_staff_id']) {
            $r_sql = ' c.sales_staff_id='.$param['sales_staff_id'];
        }
        if($param['consultation_type_id']){
            $where['c.consultation_type_id'] = intval($param['consultation_type_id']);
        }
        if($param['customer_cource_id']){
            $where['c.customer_cource_id'] = intval($param['customer_cource_id']);
        }
        if($param['customer_intention_id']){
            $where['c.customer_intention_id'] = intval($param['customer_intention_id']);
        }
        if($param['consulation_shop_code']){ //查的归属店
            $temp = trim($param['consulation_shop_code'],',');
            $shops= explode(',', $temp);
            $where['i.consulation_shop_code'] = array('in',$shops);
        }
        $sql  = ' c.is_status=1 and i.status = 1 ';
        
        if($param['flag'] == 1){
            $sql .= ' and (i.is_intostore=1 or i.is_intostore=4) ';
        }elseif($param['flag'] == 2){
            $sql .= ' and (i.is_success=1 or i.is_success=3) ';
        }elseif($param['flag'] == 3){
            $sql .= ' and (i.sys_loss=2  or i.is_intostore=5)';
        }elseif($param['flag'] == 4){
            $sql .= ' and (i.is_intostore=2  or i.is_intostore=3 or i.is_intostore=5)';
        }elseif($param['flag'] == 5){
            $sql .= ' and (i.sys_loss=2  or i.is_intostore=5 or i.is_intostore=3)';
        }
        // 不参与匹配的消费类型 
        // $temp = config('exclude_consultation_type');
        // if ($temp) {
        //     $noCon = '';
        //     foreach ($temp as $key => $value) {
        //         $noCon = $value.',';
        //     }
        //     $noCon = trim($noCon,',');
        // }

        if($param['content']){
            unset($where,$sql);
            $content = trim($param['content']);

            // $sql = " c.customer_tel = '".$content."' "; 
            // c.consultation_type,o.consultation_type as o_consultation_type,c.customer_area,o.customer_area as o_customer_area,
            // $sql = "  i.status = 1 and (c.customer_name like '%".$content."%' or c.customer_tel like '%".$content."%' or c.customer_wechat like '%".$content."%') "; consultation_type customer_area

             $sql = "  i.`status` = 1 and (c.customer_name like '%".$content."%' or c.customer_tel like '%".$content."%' or c.customer_wechat like '%".$content."%' or c.mate_tel like '%".$content."%' or c.mate_wechat like '%".$content."%')";
            if($param['limit']){
                $info = db('c_customer_intostore i')->join('c_customerinfo c','c.id=i.cid','LEFT')->join('c_customer_order o','o.into_id=i.id','LEFT')
                    ->where($sql)
                    ->where('i.consulation_shop_code', 'in', $shops)
                    ->where($r_sql)
                    // ->where('o.refund','1')
                    ->field('i.id,i.cid,i.yjd_day,i.syjd_day,i.consulation_shop_code,i.consulation_shop_name,i.reception_id,i.reception_name,i.operate_name,i.op_signinfo,i.op_signday,i.loss_reason,i.loss_time,i.is_intostore,i.is_success,i.giftinfo,i.reback,i.intostore_remark,c.is_valid,c.is_loss,c.customer_number,c.customer_tel,c.customer_wechat,c.customer_qq,c.customer_name,c.mate_tel,c.mate_name,c.mate_wechat,c.mate_qq,c.customer_address,c.consultation_type,o.consultation_type as o_consultation_type,c.customer_channel,c.customer_cource,c.customer_intention,c.customer_orderaddress,c.access_model,c.customer_area,o.customer_area as o_customer_area,c.customer_region,c.next_time,c.customer_capacity,c.dj_staff,c.sales_staff,c.dj_day,c.order_day,c.yp_day,c.order_start_time,c.totalpay_money,c.fact_money,o.order_sn as order_number,o.target_time,c.order_start_time,c.customer_remark,c.shop_name,c.add_shop_name,c.customer_birthday,c.mate_birthday,c.marry_day,c.customer_sex,c.mate_sex,i.create_time as yjd_action_day,c.brandclass_id,c.brandclass,c.sales_department_id,c.baby_name,c.baby_sex,c.ready_baby_day,c.sign_name,c.baby_birthday,c.customer_weibo,c.budget,c.customer_key,c.baby_address,c.is_urgent,c.channel_plan_number,c.next_time,c.photo_address,c.fp_staff,c.is_next,c.mate_idtype,c.mate_weibo,c.mate_idnumber')
                    // ->where('o.consultation_type','not in', $noCon)
                    ->group('i.id')
                    ->order('i.yjd_day desc ,o.id desc')
                    ->limit($param['limit'])
                    ->page($param['page'] ? $param['page'] : 1)
                    ->select();
            }else{
                $info = db('c_customer_intostore i')->join('c_customerinfo c','c.id=i.cid','LEFT')->join('c_customer_order o','o.into_id=i.id','LEFT')
                    ->where($sql)
                    ->where('i.consulation_shop_code', 'in', $shops)
                    ->where($r_sql)
                    // ->where('o.refund','1')
                    ->field('i.id,i.cid,i.yjd_day,i.syjd_day,i.consulation_shop_code,i.consulation_shop_name,i.reception_id,i.reception_name,i.operate_name,i.op_signinfo,i.op_signday,i.loss_reason,i.loss_time,i.is_intostore,i.is_success,i.giftinfo,i.reback,i.intostore_remark,c.is_valid,c.is_loss,c.customer_number,c.customer_tel,c.customer_wechat,c.customer_qq,c.customer_name,c.mate_tel,c.mate_name,c.mate_wechat,c.mate_qq,c.customer_address,c.consultation_type,o.consultation_type as o_consultation_type,c.customer_channel,c.customer_cource,c.customer_intention,c.customer_orderaddress,c.access_model,c.customer_area,o.customer_area as o_customer_area,c.customer_region,c.next_time,c.customer_capacity,c.dj_staff,c.sales_staff,c.dj_day,c.order_day,c.yp_day,c.order_start_time,c.totalpay_money,c.fact_money,o.order_sn as order_number,o.target_time,c.order_start_time,c.customer_remark,c.shop_name,c.add_shop_name,c.customer_birthday,c.mate_birthday,c.marry_day,c.customer_sex,c.mate_sex,i.create_time as yjd_action_day,c.brandclass_id,c.brandclass,c.sales_department_id,c.baby_name,c.baby_sex,c.ready_baby_day,c.sign_name,c.baby_birthday,c.customer_weibo,c.budget,c.customer_key,c.baby_address,c.is_urgent,c.channel_plan_number,c.next_time,c.photo_address,c.fp_staff,c.is_next,c.mate_idtype,c.mate_weibo,c.mate_idnumber')
                    // ->where('o.consultation_type','not in', $noCon)
                    ->group('i.id')
                    ->order('i.yjd_day desc ,o.id desc')
                    ->select();
            }
            $count = db('c_customer_intostore i')->join('c_customerinfo c','c.id=i.cid','LEFT')->join('c_customer_order o','o.into_id=i.id','LEFT')
                ->where($sql)
                ->where('i.consulation_shop_code', 'in', $shops)
                ->where($param['search_time'],'between',[$start,$end])
                ->where($r_sql)
                ->where('o.refund','1')
                ->count();
        }else{
            if($param['limit']){
                $info = db('c_customer_intostore i')->join('c_customerinfo c','c.id=i.cid','LEFT')->join('c_customer_order o','o.into_id=i.id','LEFT')
                    ->where($sql)
                    ->where($where)
                    ->where($param['search_time'],'between',[$start,$end])
                    ->where($r_sql)
                    // ->where('o.refund','1')
                    ->field('i.id,i.cid,i.yjd_day,i.syjd_day,i.consulation_shop_code,i.consulation_shop_name,i.reception_id,i.reception_name,i.operate_name,i.op_signinfo,i.op_signday,i.loss_reason,i.loss_time,i.is_intostore,i.is_success,i.giftinfo,i.costs,i.reback,i.intostore_remark,i.status,c.is_valid,c.is_loss,c.customer_number,c.customer_tel,c.customer_wechat,c.customer_qq,c.customer_name,c.mate_tel,c.mate_name,c.mate_wechat,c.mate_qq,c.customer_address,c.consultation_type,o.consultation_type as o_consultation_type,c.customer_channel,c.customer_cource,c.customer_intention,c.customer_orderaddress,c.access_model,c.customer_area,o.customer_area as o_customer_area,c.customer_region,c.next_time,c.customer_capacity,c.dj_staff,c.sales_staff,c.dj_day,c.order_day,c.yp_day,c.order_start_time,c.totalpay_money,c.fact_money,o.order_sn as order_number,o.target_time,c.order_start_time,c.customer_remark,c.shop_name,c.add_shop_name,c.customer_birthday,c.mate_birthday,c.marry_day,c.customer_sex,c.mate_sex,i.create_time as yjd_action_day,c.brandclass_id,c.brandclass,c.sales_department_id,c.baby_name,c.baby_sex,c.ready_baby_day,c.sign_name,c.baby_birthday,c.customer_weibo,c.budget,c.customer_key,c.baby_address,c.is_urgent,c.channel_plan_number,c.next_time,c.photo_address,c.fp_staff,c.is_next,c.mate_idtype,c.mate_weibo,c.mate_idnumber')
                    // ->where('o.consultation_type','not in', $noCon)
                    ->group('i.id')
                    ->order($param['search_time'].' desc ,o.id desc')
                    ->page($param['page'] ? $param['page'] : 1)
                    ->limit($param['limit'])
                    ->select();
            }else{
                $info = db('c_customer_intostore i')->join('c_customerinfo c','c.id=i.cid','LEFT')->join('c_customer_order o','o.into_id=i.id','LEFT')
                    ->where($sql)
                    ->where('i.consulation_shop_code', 'in', $shops)
                    ->where($where)
                    ->where($param['search_time'],'between',[$start,$end])
                    ->where($r_sql)
                    // ->where('o.refund','1')
                    ->field('i.id,i.cid,i.yjd_day,i.syjd_day,i.consulation_shop_code,i.consulation_shop_name,i.reception_id,i.reception_name,i.operate_name,i.op_signinfo,i.op_signday,i.loss_reason,i.loss_time,i.is_intostore,i.is_success,i.giftinfo,i.costs,i.reback,i.intostore_remark,i.status,c.is_valid,c.is_loss,c.customer_number,c.customer_tel,c.customer_wechat,c.customer_qq,c.customer_name,c.mate_tel,c.mate_name,c.mate_wechat,c.mate_qq,c.customer_address,c.consultation_type,o.consultation_type as o_consultation_type,c.customer_area,o.customer_area as o_customer_area,c.customer_channel,c.customer_cource,c.customer_intention,c.customer_orderaddress,c.access_model,c.customer_region,c.next_time,c.customer_capacity,c.dj_staff,c.sales_staff,c.dj_day,c.order_day,c.yp_day,c.order_start_time,c.totalpay_money,c.fact_money,o.order_sn as order_number,o.target_time,c.order_start_time,c.customer_remark,c.shop_name,c.add_shop_name,c.customer_birthday,c.mate_birthday,c.marry_day,c.customer_sex,c.mate_sex,i.create_time as yjd_action_day,c.brandclass_id,c.brandclass,c.sales_department_id,c.baby_name,c.baby_sex,c.ready_baby_day,c.sign_name,c.baby_birthday,c.customer_weibo,c.budget,c.customer_key,c.baby_address,c.is_urgent,c.channel_plan_number,c.next_time,c.photo_address,c.fp_staff,c.is_next,c.mate_idtype,c.mate_weibo,c.mate_idnumber')
                    // ->where('o.consultation_type','not in', $noCon)
                    ->group('i.id')
                    ->order($param['search_time'].' desc ,o.id desc')
                    ->select();
            }
            $count = db('c_customer_intostore i')->join('c_customerinfo c','c.id=i.cid','LEFT')->join('c_customer_order o','o.into_id=i.id','LEFT')
                ->where($sql)
                ->where($where)
                ->where($param['search_time'],'between',[$start,$end])
                ->where('i.consulation_shop_code', 'in', $shops)
                ->where($r_sql)
                // ->where('o.refund','1')
                ->count();
        }
        //echo db('c_customer_intostore')->getLastSql();exit;
        $dep = controller('crm/Customer','lib')->getDepartment();
        foreach($info as $k=>$v){
            $info[$k]['is_intostore'] = getIsIntostore($v['is_intostore']);
            $info[$k]['is_feiin'] = $v['is_intostore'] == 3 ? '进店非进客' : '';
            $info[$k]['is_loss'] = $v['is_intostore'] == 5 ? '是' : '否';
            $info[$k]['is_lingqu'] = $v['giftinfo'] ? '已领取':'';
            $info[$k]['is_quxiao'] = $v['status'] == 2 ? '取消':'';
            $info[$k]['reback'] = $v['reback'] == 2 ? '回门客资' : '';
            $info[$k]['reBack'] = $v['reback'] == 2 ? '回门客资' : '';

            $info[$k]['yp_day'] = $v['yp_day'] ? date('Y-m-d',strtotime($v['yp_day'])) : '';
            $info[$k]['marry_day'] = $v['marry_day'] ? date('Y-m-d',strtotime($v['marry_day'])) : '';
            $info[$k]['mate_birthday'] = $v['mate_birthday'] ? date('Y-m-d',strtotime($v['mate_birthday'])) : '';
            $info[$k]['customer_birthday'] = $v['customer_birthday'] ? date('Y-m-d',strtotime($v['customer_birthday'])) : '';
            $info[$k]['customer_remark'] = $v['customer_remark'] ? strip_tags($v['customer_remark']) : '';
            $info[$k]['intostore_remark'] = $v['intostore_remark'] ? strip_tags($v['intostore_remark']) : '';

            $info[$k]['consultation_type'] = $v['o_consultation_type'] ? $v['o_consultation_type'] : $v['consultation_type'];
            $info[$k]['customer_area'] = $v['o_customer_area'] ? $v['o_customer_area'] : $v['customer_area'];

            $info[$k]['is_valid'] = getIsValidAttr($v['is_valid']);
            $info[$k]['is_success'] = getIsSuccess($v['is_success']);
            $info[$k]['sales_department_name'] = $dep[$v['sales_department_id']]['department_name'];
            $info[$k]['count'] = $count;
        }
        return $info;
    }
    /*
     * 检查客资信息
     * @param customer_tel    男士手机号      选填
     * @param mate_tel        女生手机号      选填
     * @param branclass   事业部
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function checkCustomerRepeat($param){
        if(!$param['brandclass']){
            return array('error'=>1,'code'=>101,'msg'=>'未找到事业部');
        }
        if($param['customer_tel'] && $param['mate_tel']){
            $repeat = controller('crm/Customer','lib')->isRepeat($param['brandclass'],$param['customer_tel'],0,0,$param['mate_tel']);
            if($repeat['code'] != 200){
                $info = controller('index/Customer','lib')->checkCustomer($repeat['data']);
                // return $info;
                return array('error'=>1,'code'=>99,'msg'=>'客资重复','data'=>$info);
            }else{
                return array('code'=>200,'msg'=>'未重复客资');
            }
        }
        if($param['customer_tel']){
            $repeat = controller('crm/Customer','lib')->isRepeat($param['brandclass'],$param['customer_tel']);
            if($repeat['code'] != 200){
                $info = controller('index/Customer','lib')->checkCustomer($repeat['data']);
                //                return $info;
                return array('error'=>1,'code'=>99,'msg'=>'客资重复','data'=>$info);
            }else{
                return array('code'=>200,'msg'=>'未重复客资');
            }
        }

        if($param['mate_tel']){
            $repeat = controller('crm/Customer','lib')->isRepeat($param['brandclass'],0,0,0,$param['mate_tel']);
            if($repeat['code'] != 200){
                $info = controller('index/Customer','lib')->checkCustomer($repeat['data']);
                //                return $info;
                return array('error'=>1,'code'=>99,'msg'=>'客资重复','data'=>$info);;
            }else{
                return array('code'=>200,'msg'=>'未重复客资');
            }
        }
    }
    /*
     * 新增客资
     * @param  brandclass_id         事业部id
     * @param  shop_code             shop_code
     * @param  staff_id              员工id
     * @param  staff_name            员工姓名
     * @param  create_time           创建时间 (y-m-d H:i:s)
     * @param  consultation_type     消费类型
     * @param  consultation_type_id  消费类型 id
     * @param  customer_cource       客户来源
     * @param  customer_cource_id    客户来源 id
     * @param  customer_intention    客户意向
     * @param  customer_intention_id 客户意向 id
     * @param  customer_area         客户分区
     * @param  customer_area_id      客户分区 id
     * @param  marry_day             结婚日期
     * @param  baby_birthday         宝宝生日
     * @param  wname                 女士姓名
     * @param  wphone                女士手机
     * @param  mname                 男士姓名
     * @param  mphone                男士手机
     * @param  wwechat               女士微信
     * @param  mwechat               男士微信
     * @param  wbirthday             女士生日
     * @param  mbirthday             男士生日
     * @param  introducer_name       介绍人姓名
     * @param  introducer_tel        介绍人电话
     * @param  province              省
     * @param  city                  市
     * @param  county                区/县
     * @param  customer_address      客户地址
     * @param  customer_remark       客户备注
     * */
    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'] ? $staffInfo['staffname'] : $staffInfo['staff_name'];
        }
        $repeat = controller('crm/Customer','lib')->isRepeat($param['brandclass'],$param['wphone'],$param['wwechat'],$param['customer_qq'],$param['mphone']);
        if($repeat['code'] != 200){
            $error = 2;
            //判断客资是否属于此网销
            foreach($repeat['data'] as $k=>$v){
                $res = controller('index/Customer','lib')->checkCustomer($v);
                if($res === false){
                    $error = 1;
                }
            }
            if ($error == 1) {
                return array('error'=>1,'code'=>104,'msg'=>'此客资不属于此网销，请先创建回门');
            }else{
                return array('error'=>1,'code'=>105,'msg'=>'客资重复，请勿重复录入客资，网销可以预约此客资进店');
            }
        }
        $allShops = getShopInfo();
        $data = [
            'brandclass_id'        => (int)$param['brandclass_id'],
            'brandclass'           => $staffInfo['brandclass'],
            'shop_code'            => $param['shop_code'],
            'shop_name'            => $allShops[$param['shop_code']]['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_qq'          => $param['customer_qq'],
            'customer_address'     => $param['customer_address'],
            'customer_sex'         => '女',
            'mate_name'            => $param['mname'],
            'mate_tel'             => $param['mphone'],
            'mate_wechat'          => $param['mwechat'],
            'mate_qq'              => $param['mate_qq'],
            'mate_sex'             => '男',
            'marry_day'            => $param['marry_day'] ? date('Y-m-d H:i:s', strtotime($param['marry_day'])) : NULL,
            'yp_day'               => $param['yp_day'] ? date('Y-m-d H:i:s', strtotime($param['yp_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'],
            'customer_intention_id'=> (int)$param['customer_intention_id'],
            'customer_intention'   => $param['customer_intention'],
            'customer_orderaddress'=> $param['customer_orderaddress'],
            'customer_channel'     => $param['customer_channel'] ?: '',
            'customer_channel_id'  => (int)$param['customer_channel_id'] ?: '',
            'c_from'               => 2,
            'is_intostore'         => 2,
            'yjd_action_day'       => $param['target_time']?$param['target_time']:$create_time,
            'yjd_day'              => $param['target_time']?$param['target_time']:$create_time,
            'syjd_day'             => $param['target_time']?$param['target_time']:$create_time,
            'creator_day'          => $create_time,
            'create_time'          => $create_time,
            'dj_day'               => $create_time,
            'dj_staff'             => $param['staff_name'],
            'dj_staff_id'          => $param['staff_id'],
            'dj_staff_number'      => $staffInfo['staffnumber'],
            'is_fp'                => 1,
            // 'sales_staff'          => $param['staff_name'],
            // 'sales_staff_id'       => $param['staff_id'],
            // 'sales_staff_number'   => $staffInfo['staffnumber'],
            'tel_staff_id'         => $param['staff_id'],
            'tel_staff'            => $staffInfo['staffname'],
            'tel_time'             => $create_time,
            'is_first_tel'         => 1,
            'wechat_staff_id'      => $param['mwechat'] ? $param['staff_id'] : '',
            'wechat_staff'         => $param['mwechat'] ? $param['staffname'] : '',
            'wechat_time'          => $param['mwechat'] ? $create_time : NULL,
            'is_first_wechat'      => $param['mwechat'] ? 1 : '',
            'customer_type'        => 1,
            'consulation_shop_code'=> $param['shop_code'],
            'consulation_shop'     => $allShops[$param['shop_code']]['shop_name'],
            'reception_id'         => $param['reception_id'] ? $param['reception_id'] : NULL,
            'reception_name'       => $param['reception_name'] ? $param['reception_name'] : NULL,
            'order_start_time'     => NULL,
            '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,
            'customer_remark'      => trim($param['customer_remark']),
            'intostore_note'       => trim($param['intostore_remark']),
            'baby_name'            => $param['baby_name'],
            'baby_sex'             => $param['baby_sex'],
            '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'         => trim($param['baby_address']),
        ];

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

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

        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,dj_staff_id,dj_staff,shop_name,shop_code,is_success,is_intostore,syjd_day,order_number,consulation_shop_code,consulation_shop,brandclass_id,brandclass,customer_orderaddress,customer_channel_id,customer_channel,consultation_type,customer_type,reception_id,reception_name,order_type')->find();

        if(empty($info)){
            return array('error'=>1,'code'=>103,'msg'=>'未通过进店ID获取到客资数据');
        }
        $one_order = db_config('one_customer_more_order');//同一客资允许多次订单,有过成交，就一直成交
        if(($info['is_success'] == 1 || $info['is_success'] == 3) &&  $one_order == 2){
            return array('error'=>1,'code'=>120,'msg'=>'该客资已成单，并且已设置为不能成多单，请新创建客资');
        }
        // 根据订单号查询订单表
        $order_sn = $param['order_sn'] ? $param['order_sn'] : 'sx_erp'.time().generate_code();
        $orderInfo = db('c_customer_order')->where('order_sn', $order_sn)->field('customer_id,order_sn')->find();
        // 如果不为空说明订单表中有相同单号 如果没找到 走正常流程
        if (!empty($orderInfo)) {
            // 如果客资ID也一样说明之前开单成功了，返回成功信息即可；否则报错，订单号重复
            if ($orderInfo['customer_id'] == $into['cid']) {
                $return = $this->getCustomerInfo($param['id']);
                return $return;
            }else{
                return array('error'=>1,'code'=>108,'msg'=>'存在重复单号，请确定。');
            }
        }

        //判断客资是否属于此网销 （进客里需要判断这个吗）
        $res = controller('index/Customer','lib')->checkCustomer(['brandclass_id'=>$info['brandclass_id'],'shop_code'=>$info['shop_code'],'customer_tel'=>$info['customer_tel'],'customer_number'=>$info['customer_number'],'is_in'=>1]);
        if($res === false){
            return array('error'=>1,'code'=>104,'msg'=>'此客资不属于此网销，请先创建客资');
        }
        $intostore = [
            'cid'=>$into['cid'],
            'syjd_day'=> $into['syjd_day'] ? $into['syjd_day'] : $target_time,
            'consulation_shop_code'=>$param['consulation_shop_code'] ? $param['consulation_shop_code'] : ($info['consulation_shop_code'] ? $info['consulation_shop_code'] : NULL),
            'consulation_shop_name'=>$param['consulation_shop_name'] ? $param['consulation_shop_name'] :($info['consulation_shop']?$info['consulation_shop']:NULL),
            'reception_id'=>$param['reception_id'] ? $param['reception_id'] : ($info['reception_id']?$info['reception_id']:NULL),
            'reception_name'=>$param['reception_name'] ? $param['reception_name'] : ($info['reception_name']?$info['reception_name']:NULL),
            'operate_id'=>$param['staff_id'],
            'operate_name'=>$param['staff_name'],
            'is_intostore'=>2,
            'sys_loss'=>1,
            'loss_reason'=>NULL,
            'loss_time'=>NULL,
            'is_success'=>3,
            'update_time'=>$date,
        ];

        $order = [
            'order_sn' => $order_sn,
            'customer_id'=>$into['cid'],
            'customer_name'=>$info['customer_name'],
            'customer_channel_id'=>$info['customer_channel_id'],
            'customer_channel'=>$info['customer_channel'],
            'consultation_type'=> $param['consultation_type'] ? $param['consultation_type'] : $info['consultation_type'],
            'customer_area'=> $param['customer_area'],
            // 'order_type'=>$info['order_type'],
            'order_type'=>2,
            'create_time'=>$date,
            'order_amount'=>floatval($param['order_amount']),
            'customer_orderaddress'=>$info['customer_orderaddress'],
            'shop_code'=>$info['shop_code'],
            'shop_name'=>$info['shop_name'],
            'order_note'=>$param['order_note'],
            'target_time'=>$target_time,
            'brandclass_id'=>$info['brandclass_id'],
            'brandclass'=>$info['brandclass'],
            'into_id'=>$into['id'],
        ];
        // 根据男女手机号判断 待定
        $cData = [
            'customer_area' => $param['customer_area'],
            'customer_area_id' => $param['customer_area_id'],
            'totalpay_money'=>floatval($param['order_amount']),
            'order_number'=>$order_sn,
            'order_start_time'=>$target_time,
            'order_type'=>2,
            'is_success'=>3,
            'reception_id'=>$param['reception_id'] ? $param['reception_id'] : ($info['reception_id']?$info['reception_id']:NULL),
            'reception_name'=>$param['reception_name'] ? $param['reception_name'] : ($info['reception_name']?$info['reception_name']:NULL),
            'consulation_shop_code'=>$param['consulation_shop_code'] ? $param['consulation_shop_code'] : ($info['consulation_shop_code'] ? $info['consulation_shop_code'] : NULL),
            'consulation_shop'=>$param['consulation_shop_name'] ? $param['consulation_shop_name'] :($info['consulation_shop']?$info['consulation_shop']:NULL),
        ];

        if(!$info['syjd_day']){
            $cData['is_intostore'] = 2;
            $cData['syjd_day'] = $target_time;
        }
        // 追踪数据
        $track['gtType'] = 4;
        $track['customer_id'] = $into['cid'];
        $track['customer_name'] = $info['customer_name'];
        $track['customer_number'] = $info['customer_number'];
        $track['sales_day'] = date('Y-m-d H:i:s');
        $track['sales_staff'] = $param['staff_name'];
        $track['sales_staff_id'] = $param['staff_id'];
        $track['sales_remark'] = 'ERP转订单';
        $track['shop_code'] = trim($info['shop_code']);
        $track['shop_name'] = trim($info['shop_name']);

        $remind = getRemind($info['brandclass_id']);
        // 发送站内弹窗消息
        $message['send_type']  = 1;
        $message['send_time']  = date('Y-m-d H:i:s');
        $message['send_title'] = '订单提醒';
        $message['send_msg']   = '您有一笔客资已订单，ID：'.$info['id'].'，姓名：'.$info['customer_name'];
        if($info['customer_tel']){
            $message['send_msg'] .= '，手机：'.$info['customer_tel'];
        }elseif($info['mate_tel']){
            $message['send_msg'] .= '，手机：'.$info['mate_tel'];
        }
        $message['send_msg'] .='，请确认。';

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

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

        db()->startTrans();
        try{
            db('c_customerinfo')->where('id',$into['cid'])->update($cData);
            db('c_customer_order')->insert($order);
            db('c_customer_intostore')->where('id',$param['id'])->update($intostore);
            db('c_salestrackinginfo')->insert($track);
            if($info['dj_staff_id'] && in_array('tan',$remind['order']['send_method']) && in_array('dj',$remind['order']['send_receive'])){
                $message['receive_id']     = $info['dj_staff_id'];
                $message['receive_name']   = $info['dj_staff'];
                sendSystemMessage($message);
            }
            if($info['sales_staff_id'] && in_array('tan',$remind['order']['send_method']) && in_array('sales',$remind['order']['send_receive'])){
                $message['receive_id']     = $info['sales_staff_id'];
                $message['receive_name']   = $info['sales_staff'];
                sendSystemMessage($message);
            }
            //微信推送
            if($info['customer_type']== 2 || in_array('tui',$remind['order']['send_method']) && in_array('dj',$remind['order']['send_receive'])){
                $content = [
                    'touser'       => $info['dj_staff_id'],
                    'template_id'  => OPENTM_YX,
                    'data'         => [
                        'first'=>[
                            'value'=> '您有一笔客资已订单',
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $info['customer_name'],
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $info['sales_staff'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> date('Y-m-d H:i:s'),
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> 'ID:'.$info['id'].',订单号：'.$order_sn.'请尽快查看，谢谢',
                            'color'=> '#173177'
                        ],
                    ]
                ];
                $send_data['content'] = json_encode($content);
                sendMsg($send_data);
            }
            if(($info['dj_staff_id']!= $info['sales_staff_id']) && $info['sales_staff_id'] && in_array('tui',$remind['order']['send_method']) && in_array('sales',$remind['order']['send_receive'])){
                $content = [
                    'touser'       => $info['sales_staff_id'],
                    'template_id'  => OPENTM_YX,
                    'data'         => [
                        'first'=>[
                            'value'=> '您有一笔客资已订单',
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $info['customer_name'],
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $info['sales_staff'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> date('Y-m-d H:i:s'),
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> 'ID:'.$info['id'].',订单号：'.$order_sn.'请尽快查看，谢谢',
                            'color'=> '#173177'
                        ],
                    ]
                ];
                $send_data['content'] = json_encode($content);
                sendMsg($send_data);
            }
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$into['cid'],
                'old_data'=>'',
                'data'=>'ERP转单：'.$order_sn,
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Intostore',
                'action'=>'createNewCustomer',
            ];
            common_log($logData,'action_log');
            db()->commit();
            $return = $this->getCustomerInfo($param['id']);
            return $return;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>109,'msg'=>'转单失败'.$e->getMessage(),'data'=>$e->getMessage());
        }
    }
    /*
     * 根据进店id获取客资信息
     * */
    public function getCustomerInfo($into_id){
        $return = db('c_customer_intostore i')->join('c_customerinfo c','c.id=i.cid','LEFT')->join('c_customer_order o','o.into_id=i.id','LEFT')
            ->where('i.id',$into_id)
            // ->field('i.id,i.cid,i.yjd_day,i.syjd_day,i.consulation_shop_code,i.consulation_shop_name,i.reception_id,i.reception_name,i.operate_name,i.op_signinfo,i.op_signday,i.loss_reason,i.loss_time,i.is_intostore,i.is_success,i.giftinfo,i.costs,i.reback,i.intostore_remark,i.status,c.is_valid,c.is_loss,c.customer_number,c.customer_tel,c.customer_wechat,c.customer_qq,c.customer_name,c.mate_tel,c.mate_name,c.mate_wechat,c.mate_qq,c.customer_address,c.consultation_type,c.customer_channel,c.customer_cource,c.customer_intention,c.customer_orderaddress,c.access_model,c.customer_area,c.customer_region,c.next_time,c.customer_capacity,c.dj_staff,c.sales_staff,c.dj_day,c.order_day,c.yp_day,o.target_time,c.order_start_time,c.totalpay_money,c.fact_money,o.order_sn as order_number,c.customer_remark,c.shop_name,c.add_shop_name,c.customer_birthday,c.mate_birthday,c.marry_day,c.customer_sex,c.mate_sex,c.yjd_action_day,c.brandclass_id,c.brandclass,c.sales_department_id')
            ->field('i.id,i.yjd_day,i.syjd_day,i.consulation_shop_code,i.consulation_shop_name,i.reception_id,i.reception_name,i.operate_name,i.op_signinfo,i.op_signday,i.loss_reason,i.loss_time,i.is_intostore,i.is_success,i.giftinfo,i.costs,i.reback,i.intostore_remark,c.is_valid,c.is_loss,c.customer_number,c.customer_tel,c.customer_wechat,c.customer_qq,c.customer_name,c.mate_tel,c.mate_name,c.mate_wechat,c.mate_qq,c.customer_address,c.consultation_type,o.consultation_type as o_consultation_type,c.customer_channel,c.customer_cource,c.customer_intention,c.customer_orderaddress,c.access_model,c.customer_area,o.customer_area as o_customer_area,c.customer_region,c.next_time,c.customer_capacity,c.dj_staff,c.sales_staff,c.dj_day,c.order_day,c.yp_day,c.order_start_time,c.totalpay_money,c.fact_money,o.order_sn as order_number,o.target_time,c.order_start_time,c.customer_remark,c.shop_name,c.add_shop_name,c.customer_birthday,c.mate_birthday,c.marry_day,c.customer_sex,c.mate_sex,i.create_time as yjd_action_day,c.brandclass_id,c.brandclass,c.sales_department_id,c.baby_name,c.baby_sex,c.ready_baby_day,c.sign_name,c.baby_birthday,c.customer_weibo,c.budget,c.customer_key,c.baby_address,c.is_urgent,c.channel_plan_number,c.next_time,c.photo_address,c.fp_staff,c.is_next,c.mate_idtype,c.mate_weibo,c.mate_idnumber,c.order_type as co_type,o.order_type as oo_type,c.id as cid')
            ->find();

        $dep = controller('crm/Customer','lib')->getDepartment();
        $return['is_loss'] = $return['is_intostore'] == 5 ? '是' : '否';
        $return['is_feiin'] = $return['is_intostore'] == 3 ? '进店非进客' : '';
        $return['is_intostore'] = getIsIntostore($return['is_intostore']);
        $return['is_lingqu'] = $return['giftinfo'] ? '已领取':'';
        $return['is_quxiao'] = $return['status'] == 2 ? '取消':'';
        $return['reBack'] = $return['reback'] == 2 ? '回门客资':'';
        $return['reback'] = $return['reback'] == 2 ? '回门客资':'';
        // $return['erp_loss'] = $return['erp_loss'] == 2 ? '是':'否';

        $return['yp_day'] = $return['yp_day'] ? date('Y-m-d',strtotime($return['yp_day'])) : '';
        $return['marry_day'] = $return['marry_day'] ? date('Y-m-d',strtotime($return['marry_day'])) : '';
        $return['mate_birthday'] = $return['mate_birthday'] ? date('Y-m-d',strtotime($return['mate_birthday'])) : '';
        $return['customer_birthday'] = $return['customer_birthday'] ? date('Y-m-d',strtotime($return['customer_birthday'])) : '';
        $return['customer_remark'] = $return['customer_remark'] ? strip_tags($return['customer_remark']) : '';
        $return['intostore_remark'] = $return['intostore_remark'] ? strip_tags($return['intostore_remark']) : '';

        $return['is_valid'] = getIsValidAttr($return['is_valid']);
        $return['is_success'] = getIsSuccess($return['is_success']);
        $return['sales_department_name'] = $dep[$return['sales_department_id']]['department_name'];

        $return['op_signday'] = substr($return['op_signday'], 0,10);
        $return['yjd_day'] = substr($return['yjd_day'], 0,16);
        $return['syjd_day'] = substr($return['syjd_day'], 0,16);
        return $return;
    }
    /*
     *getCustomerNumber
     * 首页今日登记数,预约进店数（按意向店面算）
     * shop_code
     * */
    public function getCustomerNumber($data){
        if(empty($data['shop_code'])){
            return json(array('code'=>100,'msg'=>'未获取到店面编码'));
        }
        $cus = db('c_customerinfo c')->join('c_customer_intostore i','c.id=i.cid','LEFT')
            ->where('c.is_status',1)
            ->where('c.c_from',2)
            ->where('i.status',1)
            ->where('c.dj_day','like','%'.date('Y-m-d').'%')
            ->count('c.id');
        $yjd = db('c_customerinfo c')->join('c_customer_intostore i','c.id=i.cid','LEFT')
            ->where('i.consulation_shop_code',$data['shop_code'])
            ->where('c.is_status',1)
            ->where('i.status',1)
            ->where('i.yjd_day','like','%'.date('Y-m-d').'%')
            ->count('c.id');
        return array('code'=>200,'msg'=>'','dj'=>$cus,'yjd'=>$yjd);
    }
    /*
     * 获取店面进客数量
     * shop_code
     * */
    public function getIntoNumber($data){
        if(empty($data['shop_code'])){
            return json(array('code'=>100,'msg'=>'未获取到店面编码'));
        }
        $start =  $data['start'] ? date('Y-m-d 00:00:00',strtotime($data['start']))  : date('Y-m-d 00:00:00');
        $end = $data['end'] ? date('Y-m-d 23:59:59',strtotime($data['end']))  : date('Y-m-d 23:59:59');
        $all = db('c_customerinfo c')->join('c_customer_intostore i','c.id=i.cid','LEFT')
            ->where('c.is_status',1)
            ->where('i.status',1)
            ->where('i.yjd_day','between',[$start,$end])
            ->where('i.consulation_shop_code', $data['shop_code'])
            ->count('i.id');
        $notJd = db('c_customerinfo c')->join('c_customer_intostore i','c.id=i.cid','LEFT')
            ->where('c.is_status',1)
            ->where('i.status',1)
            ->where('i.is_intostore','in',[1,4])
            ->where('i.yjd_day','between',[$start,$end])
            ->where('i.consulation_shop_code', $data['shop_code'])
            ->count('i.id');
        $succ = db('c_customerinfo c')->join('c_customer_intostore i','c.id=i.cid','LEFT')
            ->where('c.is_status',1)
            ->where('i.status',1)
            ->where('i.is_success','in',[1,3])
            ->where('i.yjd_day','between',[$start,$end])
            ->where('i.consulation_shop_code', $data['shop_code'])
            ->count('i.id');
        $loss= db('c_customerinfo c')->join('c_customer_intostore i','c.id=i.cid','LEFT')
            ->where('c.is_status',1)
            ->where('i.status',1)
            ->where(('i.is_intostore in(3,5) or i.sys_loss=2'))
            ->where('i.yjd_day','between',[$start,$end])
            ->where('i.consulation_shop_code', $data['shop_code'])
            ->count('i.id');
        return array('code'=>200,'msg'=>'','all'=>$all,'notJd'=>$notJd,'succ'=>$succ,'loss'=>$loss);
    }


    /*
     * 修改时间进店时间（仅修改时间，不修改日期） 不用，振亚写了，冲突了
     * @param id           进店表id    必填
     * @param time         时分秒      必填
     * @param staff_id     操作人id    必填
     * @param staff_name   操作人      必填
     * */
    public function changeSyjdTime($param){
        if(!(int)$param['id']){
            return array('error'=>1,'code'=>100,'msg'=>'缺少参数，进店ID');
        }
        if(!$param['time']){
            return array('error'=>1,'code'=>101,'msg'=>'缺少参数，进店时间');
        }
        if(!(int)$param['staff_id']){
            return array('error'=>1,'code'=>102,'msg'=>'缺少参数，操作人');
        }

        $into = db('c_customer_intostore')->where('id',(int)$param['id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>103,'msg'=>'未通过进店ID获取到进客数据');
        }
    }

    /*
     * 修改实际进店时间的时分秒
     * @param id
     * @param time :143025
     * @param staff_id
     * @param staff_name
     * return info
     * */
    public function editSyjd($param){
        if(empty($param['time'])){
            return json(array('code'=>99,'msg'=>'未获取到实际进店时间的时分秒'));
        }
        if(empty($param['id'])){
            return json(array('code'=>100,'msg'=>'未获取到进客ID'));
        }
        $into = db('c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        if(empty($into['syjd_day'])){
            return array('error'=>1,'code'=>102,'msg'=>'未获取到进客表实际进店时间');
        }
        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code,syjd_day')->find();
        if(empty($info)){
            return array('error'=>1,'code'=>103,'msg'=>'未通过进店ID获取到客资数据');
        }
        if(empty($info['syjd_day'])){
            return array('error'=>1,'code'=>104,'msg'=>'为获取到客资表实际进店时间');
        }
        $into_syjd = date('Ymd',strtotime($into['syjd_day']));
        if(date('Ymd') != $into_syjd){
            return array('error'=>1,'code'=>105,'msg'=>'不是当天进客，不能修改');
        }
        $info_syjd = date('Ymd',strtotime($info['syjd_day']));
        if($into['syjd_day'] && $info['syjd_day'] && ($into_syjd == $info_syjd)){
            $iData['syjd_day'] = date('Y-m-d H:i:s',strtotime($info_syjd.trim($param['time'])));
            $cData['syjd_day'] = date('Y-m-d H:i:s',strtotime($info_syjd.trim($param['time'])));
        }else{
            $iData['syjd_day'] = date('Y-m-d H:i:s',strtotime($info_syjd.trim($param['time'])));
        }

        $logData = [
            'create_time'=>date('Y-m-d H:i:s'),
            'customer_id'=>$info['id'],
            'old_data'=> $into['syjd_day'],
            'data'=>'ERP修改实际进店时间：'.$iData['syjd_day'],
            'ip'=>get_client_ip(),
            'staff_id'=>intval($param['staff_id']),
            'staff_name'=>trim($param['staff_name']),
            'module'=>'index',
            'controller'=>'Intostore',
            'action'=>'editSyjd',
        ];
        db()->startTrans();
        try{
            db('c_customer_intostore')->where('id',$param['id'])->update($iData);
            if(!empty($cData)){
                db('c_customerinfo')->where('id',$info['id'])->update($cData);
            }
            common_log($logData,'action_log');
            db()->commit();
            $return = $this->getCustomerInfo($param['id']);
            return $return;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>109,'msg'=>'修改时间进店时间失败','data'=>$e->getMessage());
        }
    }
    /**
     * 新增追踪记录接口   进客右键 ‘追踪’
     * 
     * @param  id         进店id
     * @param  remark     未进店备注
     * @param  staff_id   操作人id
     * @param  staff_name 操作人
     * 
     * @return boolean
     * @author lilong<lilong@suxuantech.cn>
     */
    public function addIntoTrackInfo($param){
        $date = date('Y-m-d H:i:s');
        $into_id = (int)$param['id'];
        if(!$param['id']){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('c_customer_intostore')->where('id',$into_id)->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $cInfo= db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,sales_staff_number,shop_name,shop_code,is_success,is_intostore,syjd_day,brandclass_id,dj_staff_id,dj_staff,reception_id,reception_name')->find();
        if(empty($cInfo)){
            return array('error'=>1,'code'=>102,'msg'=>'未获取到客资数据');
        }
        
        // 进客等操作时，-- 进客表 --如果没有门市接待人员，则当前操作人为门市接待人员
        if (!$into['reception_name']) {
            // 进客数据
            $iData['reception_id']  = (int)$param['staff_id'];
            $iData['reception_name']= trim($param['staff_name']);
            // 客资数据
            $cData['reception_id']  = (int)$param['staff_id'];
            $cData['reception_name']= trim($param['staff_name']);
            $cData['update_time']   = $date;
        }
        // 如果进客表里有接待人员
        else{
            // 如果进客表里的接待人员与客资表里的接待人员不一样 则更新
            if ($into['reception_name'] != $cInfo['reception_name']) {
                $cData['reception_id']  = (int)$into['reception_id'];
                $cData['reception_name']= trim($into['reception_name']);
                $cData['update_time']   = $date;
            }
        }
        // 操作人
        $iData['operate_id']  = (int)$param['staff_id'];
        $iData['operate_name']= trim($param['staff_name']);

        db()->startTrans();
        try {
            if (!empty($cData)) {
                db('c_customerinfo')->where('id', $cInfo['id'])->update($cData);
            }
            db('c_customer_intostore')->where('id',$into_id)->update($iData);
            // 追踪数据
            $track['gtType']         = 4;
            $track['customer_id']    = $cInfo['id'];
            $track['customer_name']  = $cInfo['customer_name'];
            $track['customer_number']= $cInfo['customer_number'];
            $track['sales_day']      = date('Y-m-d H:i:s');
            $track['sales_staff']    = $param['staff_name'];
            $track['sales_staff_id'] = $param['staff_id'];
            $track['sales_remark']   = 'erp进客追踪：'.trim($param['remark']);
            $track['shop_code']      = trim($cInfo['shop_code']);
            $track['shop_name']      = trim($cInfo['shop_name']);
            $track['no_track']       = 'erp进客追踪';
            db('c_salestrackinginfo')->insert($track);

            db()->commit();
            $return = $this->getCustomerInfo($into_id);
            return $return;
        } catch (\Exception $e) {
            db()->rollback();
            return array('error'=>1,'code'=>103,'msg'=>'追踪失败','data'=>$e->getMessage());
        }
    }
    /**
     * 新增追踪记录接口   这个是给TQ写的
     * 
     * @param  cid            客资id
     * @param  customerinfo   要修改的客资信息（json数组，必须与客资表，字段名一致）
     * @param  trackinfo      要添加的追踪信息（json数组，必须与追踪记录表，字段名一致）
     * @param  staffname      操作人（必须与mc中人员名一致，不包含离职员工）
     * 
     * @return boolean
     * @author lilong<lilong@suxuantech.cn>
     */
    public function addCustomerTrackInfo($params){
        $cid = (int)$params['cid'];
        if (!$cid) {
            return array('error'=>1,'code'=>100,'msg'=>'缺少参数，客资id');
        }
        $cInfo = db('c_customerinfo')->where('id',$cid)->count();
        if (!$cInfo) {
            return array('error'=>1,'code'=>101,'msg'=>'参数错误，不存在ID为'.$cid.'的客资');
        }
        $staffname = trim($params['staffname']);
        if (!$staffname) {
            return array('error'=>1,'code'=>102,'msg'=>'缺少参数，操作人');
        }
        $trackinfo = json_decode(trim($params['staffname']), true);
        if (empty($trackinfo)) {
            return array('error'=>1,'code'=>103,'msg'=>'缺少参数，追踪信息');
        }
        // $customerinfo = json_decode(trim($params['staffname']), true);
        
        $mc = new \app\common\lib\mcInterface();
        $staffinfo = $mc->getStaffInfo(['staffname'=>$staffname]);
        
        $tParam['cid'] = $cid;
        $tParam['trackinfo']   = $trackinfo;
        $tParam['staffinfo']   = $staffinfo;
        // $tParam['customerinfo']= $customerinfo;
        unset($cid,$staffname,$trackinfo,$staffinfo/*,$customerinfo*/);
        $return = controller('crm/Customer','lib')->addCustomerTrackInfo($tParam);
        unset($tParam);
        return $return;
    }
    /*
     * ERP预约进店
     * @param   into_id         进客ID    必填
     * @param   yjd_day         预约时间    必填  格式：YY-mm-dd HH:ii:ss
     * @param   consulation_shop_code       预约店面code     必填
     * @param   consulation_shop       预约店面  必填
     * @param   reception_id        门市id
     * @param   reception_name      门市
     * @param   staff_id        操作人id      必填
     * @param   staff_name      操作人
     * @param   intostore_note    进店备注
     * */
    public function erpYjd($param){
        if(empty($param['into_id'])){
            return array('code'=>100,'msg'=>'未获取到进客ID');
        }
        if(empty($param['yjd_day'])){
            return array('code'=>100,'msg'=>'未获取到预约时间');
        }
        if(empty($param['consulation_shop_code'])){
            return array('code'=>100,'msg'=>'未获取到预约店面');
        }
        if(empty($param['staff_id'])){
            return array('code'=>100,'msg'=>'未获取到操作人ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['into_id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $info = db('c_customerinfo')->where('id',$into['cid'])->field('id,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code,syjd_day')->find();
        if(empty($info)){
            return array('error'=>1,'code'=>103,'msg'=>'未通过进店ID获取到客资数据');
        }
        $into_arr['id'] = $into['cid'];
        $into_arr['yjd_day'] = $param['yjd_day'];
        $into_arr['staff_id'] = intval($param['staff_id']);
        $into_arr['staff_name'] = trim($param['staff_name']);
        if($into['reception_id']){
            $into_arr['reception_id'] = intval($param['reception_id']);
            $into_arr['reception_name'] = trim($param['reception_name']);
        }
        if($param['consulation_shop_code']){
            $into_arr['consulation_shop_code'] = trim($param['consulation_shop_code']);
            $into_arr['consulation_shop'] = trim($param['consulation_shop']);
        }
        if($param['intostore_note']){
            $into_arr['intostore_note'] = trim($param['intostore_note']);
        }
        $res = controller('crm/Customer','lib')->customerYJD($into_arr);
        if($res['code'] == 200){
            $return = $this->getCustomerInfo($param['into_id']);
            return $return;
        }else{
            return array('error'=>1,'code'=>$res['code'],'msg'=>$res['msg']);
        }
    }
    /*
     * 绑定订单
     * @param into_id  进客id
     * @param order_sn 单号
     * @param staff_id
     * @param staff_name 操作人
     * */
    public function bindOrder(){
        $param = input();
        if(empty($param['into_id'])){
            return array('code'=>100,'msg'=>'未获取到进客ID');
        }
        if(empty($param['order_sn'])){
            return array('code'=>101,'msg'=>'未获取到订单号');
        }
        if(empty($param['staff_id'])){
            return array('code'=>102,'msg'=>'未获取到操作人ID');
        }
        $into = db('c_customer_intostore')->where('id',$param['into_id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>103,'msg'=>'未通过进店ID获取到进客数据');
        }
        $info = db('c_customer_order')
            ->where('customer_id',$into['cid'])
            ->where('order_sn',trim($param['order_sn']))
            ->where('is_delete',2)
            ->find();
        if(empty($info)){
            return array('error'=>1,'code'=>104,'msg'=>'未通过进店ID和单号获取到订单数据');
        }
        if($info['into_id'] == intval($param['into_id'])){
            return array('code'=>105,'msg'=>'已经匹配过此进客ID和订单，不能再匹配');
        }elseif($info['into_id'] > 0){
            return array('code'=>106,'msg'=>'此订单已经匹配别的进客ID，不能匹配');
        }
        db()->startTrans();
        try{
            //插入进客ID
            $oInfo['into_id'] = intval($param['into_id']);
            db('c_customer_order')->where('id',$info['id'])->update($oInfo);
            //修改进客表进店状态和成交状态
            $iInfo['syjd_day'] = $info['create_time'];
            $iInfo['is_intostore'] = 2;
            $iInfo['sys_loss'] = 1;
            $iInfo['loss_reason'] = null;
            $iInfo['loss_time'] = null;
            if($info['order_valid'] == 2){
                $iInfo['is_success'] = 1;
            }else{
                $iInfo['is_success'] = 3;
            }
            if($into['operate_id'] != intval($param['staff_id'])){
                $iInfo['operate_id'] = intval($param['staff_id']);
                $iInfo['operate_name'] = trim($param['staff_name']);
            }
            db('c_customer_intostore')->where('id',$into['id'])->update($iInfo);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$into['cid'],
                'old_data'=> $into,
                'data'=>'ERP绑定订单：单号：'.$param['order_sn'].';进客ID：'.$param['into_id'].';客资ID：'.$into['cid'].';操作人：'.$param['staff_name'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Intostore',
                'action'=>'bindOrder',
            ];
            common_log($logData,'action_log');
            db()->commit();
            $return = $this->getCustomerInfo($param['into_id']);
            return $return;
        }catch (\Exception $e){
            db()->rollback();
            return array('error'=>1,'code'=>107,'msg'=>'订单匹配失败','data'=>$e->getMessage());
        }
    }
}