<?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('crm_c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();

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

        $info = db('crm_c_customerinfo')->where('id',$into['cid'])->field('id,c_unique,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('crm_c_customerinfo')->where('id',$into['cid'])->update($data);
            db('crm_c_customer_intostore')->where('id',$param['id'])->update($intostore);
            // 追踪数据
            $track['gtType'] = 4;
            $track['c_unique'] = $info['c_unique'];
            $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('crm_c_salestrackinginfo')->insert($track);

            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>$info['reception_name'] ? $info['reception_name'] : '',
                'data'=>'ERP分配接待人：'.$param['reception_name'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'allotReception',
            ];
            common_log($logData,'crm_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('crm_c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();


        $info = db('crm_c_customerinfo')->where('id',$into['cid'])->field('id,c_unique,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('crm_c_customerinfo')->where('id', $info['id'])->update($cData);
            }
            db('crm_c_customer_intostore')->where('id',$param['id'])->update($inData);
            // 追踪数据
            $track['gtType'] = 4;
            $track['c_unique'] = $info['c_unique'];
            $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('crm_c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>$into['op_signinfo'],
                'data'=>'客资标记：'.$param['op_signinfo'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'customerSign',
            ];
            common_log($logData,'crm_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   baby_name
      * @param   baby_sex
      * @param   baby_birthday              宝宝生日
      * @param   baby_address               出生医院
      * @param   ready_baby_day             预产期
      * @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('crm_c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>102,'msg'=>'未通过进店ID获取到信息');
        }
        $info = db('crm_c_customerinfo')->where('id',$into['cid'])->find();

        $update = [];
        $iUpdate = [];
        $new_data = '';
        $old_data = '';
        if($info['baby_name'] != $update['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'] != $update['baby_sex']){
            $update['baby_sex'] = trim($param['baby_sex']);
            $new_data .= '宝宝性别：'.$update['baby_sex'].'<br>';
            $old_data .= '宝宝性别：'.trim($info['baby_sex']).'<br>';
        }
        if($info['customer_birthday'] != $update['customer_birthday']){
            $update['customer_birthday'] = trim($param['customer_birthday']);
            $new_data .= '宝宝生日：'.$update['customer_birthday'].'<br>';
            $old_data .= '宝宝生日：'.trim($info['customer_birthday']).'<br>';
        }
        if($info['customer_address'] != $update['customer_address']){
            $update['customer_address'] = trim($param['customer_address']);
            $new_data .= '出生医院：'.$update['customer_address'].'<br>';
            $old_data .= '出生医院：'.trim($info['customer_address']).'<br>';
        }
        if($info['ready_baby_day'] != $update['ready_baby_day']){
            $update['ready_baby_day'] = trim($param['ready_baby_day']);
            $new_data .= '预产期：'.$update['ready_baby_day'].'<br>';
            $old_data .= '预产期：'.trim($info['ready_baby_day']).'<br>';
        }
        if($info['customer_name'] != $update['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'] != $update['customer_tel']){
            $update['customer_tel'] = trim($param['customer_tel']);
            $new_data .= '客资手机：'.$update['customer_tel'].'<br>';
            $new_data .= '客资手机：'.trim($info['customer_tel']).'<br>';
        }
        if($info['customer_sex'] != $update['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'] != $update['customer_wechat']){
            $update['customer_wechat'] = trim($param['customer_wechat']);
            $new_data .= '客资微信：'.$update['customer_wechat'].'<br>';
            $old_data .= '客资微信：'.trim($info['customer_wechat']).'<br>';
        }
        if($info['customer_qq'] != $update['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'] != $update['customer_birthday']){
            $update['customer_birthday'] = trim($param['customer_birthday']);
            $new_data .= '客户生日：'.$update['customer_birthday'].'<br>';
            $old_data .= '客户生日：'.$info['customer_birthday'].'<br>';
        }
        if($info['mate_name'] != $update['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'] != $update['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'] != $update['mate_tel']){
            $update['mate_tel'] = trim($param['mate_tel']);
            $new_data .= '配偶手机：'.$update['mate_tel'].'<br>';
            $old_data .= '配偶手机：'.trim($info['mate_tel']).'<br>';
        }
        if($info['mate_wechat'] != $update['mate_wechat']){
            $update['mate_wechat'] = trim($param['mate_wechat']);
            $new_data .= '配偶微信：'.$update['mate_wechat'].'<br>';
            $old_data .= '配偶微信：'.trim($info['mate_wechat']).'<br>';
        }
        if($info['mate_qq'] != $update['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'] != $update['mate_birthday']){
            $update['mate_birthday'] = trim($param['mate_birthday']);
            $new_data .= '配偶生日：'.$update['mate_birthday'].'<br>';
            $old_data .= '配偶生日：'.$info['mate_birthday'].'<br>';
        }
        if($info['marry_day'] != $update['marry_day']){
            $update['marry_day'] = trim($param['marry_day']);
            $new_data .= '结婚日期：'.$update['marry_day'].'<br>';
            $old_data .= '结婚日期：'.$info['marry_day'].'<br>';
        }
        if($info['yp_day'] != $update['yp_day']){
            $update['yp_day'] = trim($param['yp_day']);
            $new_data .= '预拍日期：'.$update['yp_day'].'<br>';
            $old_data .= '预拍日期：'.$info['yp_day'].'<br>';
        }
        if($info['customer_address'] != $update['customer_address']){
            $update['customer_address'] = trim($param['customer_address']);
            $new_data .= '客资地址：'.$update['customer_address'].'<br>';
            $old_data .= '客资地址：'.trim($info['customer_address']).'<br>';
        }
        if($info['reception_name'] != $update['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['customer_area'] != $update['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_cource'] != $update['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['customer_orderaddress'] != $update['customer_orderaddress']){
            $update['customer_orderaddress'] = trim($param['customer_orderaddress']);
            $new_data .= '接单点：'.$update['customer_orderaddress'].'<br>';
            $old_data .= '接单点：'.trim($info['customer_orderaddress']).'<br>';
        }
        if($info['consultation_type'] != $update['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($info['customer_intention'] != $update['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'] != $update['intostore_note']){
            $update['intostore_note'] = trim($param['intostore_remark']);
            $iUpdate['intostore_remark'] = trim($param['intostore_remark']);
            $new_data .= '进店备注：'.$update['intostore_note'].'<br>';
            $old_data .= '进店备注：'.trim($info['intostore_note']).'<br>';
        }



        db()->startTrans();
        try{
            db('crm_c_customerinfo')->where('id',$into['cid'])->update($update);
            db('crm_c_customer_intostore')->where('id',$param['id'])->update($iUpdate);

            // 追踪数据
            $track['gtType'] = 4;
            $track['c_unique'] = $info['c_unique'];
            $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'] = intval($param['staff_name']);
            $track['sales_staff_id'] = intval($param['staff_id']);
            $track['sales_remark'] = '客资编辑';
            $track['shop_code'] = trim($info['shop_code']);
            $track['shop_name'] = trim($info['shop_name']);
            db('crm_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'=>'Customer',
                'action'=>'customerinfo',
            ];
            common_log($logData,'crm_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('crm_c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $info = db('crm_c_customerinfo')->where('id',$into['cid'])->field('id,c_unique,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('crm_c_customer_intostore')->where('id',$param['id'])->update($inData);
            if (!empty($cData)) {
                db('crm_c_customerinfo')->where('id',$cInfo['id'])->update($cData);
            }
            // 追踪数据
            $track['gtType'] = 4;
            $track['c_unique'] = $info['c_unique'];
            $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('crm_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'=>'Customer',
                'action'=>'gift',
            ];
            common_log($logData,'crm_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('crm_c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $info = db('crm_c_customerinfo')->where('id',$into['cid'])->field('id,c_unique,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('crm_c_customer_intostore')->where('id',$param['id'])->update($inData);
            db('crm_c_customerinfo')->where('id',$into['cid'])->update($cData);
            // 追踪数据
            $track['gtType'] = 4;
            $track['c_unique'] = $info['c_unique'];
            $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('crm_c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'ERP标记流失:'.$param['loss_reason'],
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'loss',
            ];
            common_log($logData,'crm_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 is_intostore   进店  必填
     * @param syjd_day
     * @param staff_id   操作人id
     * @param staff_name 操作人
     * */
    public function intostore($param){
        $syjd_day = $param['syjd_day'] ? date('Y-m-d H:i:s',strtotime($param['syjd_day'])) : date('Y-m-d H:i:s');
        if(empty($param['id'])){
            return array('error'=>1,'code'=>100,'msg'=>'未获取到进店ID');
        }
        $into = db('crm_c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到数据');
        }
        $info = db('crm_c_customerinfo')->where('id',$into['cid'])->field('id,c_unique,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')){
            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 ( date('Ymd', strtotime($param['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'] > 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('crm_c_customerinfo')->where('id', $info['id'])->update($cData);
            }

            db('crm_c_customer_intostore')->where('id',$param['id'])->update($inData);
            //删除pool表预约未进店提醒
            db('crm_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']     = '标记提醒';
            $messageD['send_msg']       = '您有一笔客资已标记为：'.$msg.',请确认';

            $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']==5){
                $des = '进店流失';
            }
            // 追踪数据
            $track['gtType'] = 4;
            $track['c_unique'] = $info['c_unique'];
            $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('crm_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'=>'Customer',
                'action'=>'intostore',
            ];
            common_log($logData,'crm_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('crm_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('crm_c_customerinfo')->where('id',$into['cid'])->field('id,c_unique,customer_name,customer_number,customer_tel,sales_staff,sales_staff_id,shop_name,shop_code')->find();
        if(empty($into)){
            return array('error'=>1,'code'=>103,'msg'=>'未通过进店ID获取到客资数据');
        }
        $inData = [];
        $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('crm_c_customer_intostore')->where('id',$param['id'])->update($inData);
            // 追踪数据
            $track['gtType'] = 4;
            $track['c_unique'] = $info['c_unique'];
            $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('crm_c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'删除进店',
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'deleteInto',
            ];
            common_log($logData,'crm_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('crm_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('crm_c_customerinfo')->where('id',$into['cid'])->field('id,c_unique,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('crm_c_customer_intostore')->insertGetId($inData);
            db('crm_c_customerinfo')->where('id',$into['cid'])->update($cData);
            // 追踪数据
            $track['gtType'] = 4;
            $track['c_unique'] = $info['c_unique'];
            $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('crm_c_salestrackinginfo')->insert($track);
            $logData = [
                'create_time'=>date('Y-m-d H:i:s'),
                'customer_id'=>$info['id'],
                'old_data'=>'',
                'data'=>'回门',
                'ip'=>get_client_ip(),
                'staff_id'=>intval($param['staff_id']),
                'staff_name'=>trim($param['staff_name']),
                'module'=>'index',
                'controller'=>'Customer',
                'action'=>'returnDoor',
            ];
            common_log($logData,'crm_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 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 页数
     * */
    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['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);
        }
        $sql  = ' i.status = 1 ';
        
        if($param['flag'] == 1){
            $sql .= ' and (i.is_intostore=1 or i.is_intostore=4) ';
        }elseif($param['flag'] == 2){
            $sql .= ' and (i.is_success=1 or i.is_success=3) ';
        }elseif($param['flag'] == 3){
            $sql .= ' and (i.sys_loss=2  or i.is_intostore=5)';
        }elseif($param['flag'] == 4){
            $sql .= ' and (i.is_intostore=2  or i.is_intostore=3 or i.is_intostore=5)';
        }
        // 不参与匹配的消费类型 
        // $temp = config('exclude_consultation_type');
        // if ($temp) {
        //     $noCon = '';
        //     foreach ($temp as $key => $value) {
        //         $noCon = $value.',';
        //     }
        //     $noCon = trim($noCon,',');
        // }
        $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.c_unique,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.dj_staff,c.sales_staff,c.dj_day,c.order_day,c.yp_day,o.targetdate as order_start_time,o.total_money as totalpay_money,o.payment_money as fact_money,o.orderId as order_number,o.targetdate as target_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.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.baby_name,c.baby_sex,c.baby_birthday,c.baby_address,c.ready_baby_day';
        if($param['content']){
            unset($where,$sql);
            $content = trim($param['content']);

            // $sql = " c.customer_tel = '".$content."' ";
            // $sql = "  i.status = 1 and (c.customer_name like '%".$content."%' or c.customer_tel like '%".$content."%' or c.customer_wechat like '%".$content."%') ";

             $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('crm_c_customer_intostore i')->join('crm_c_customerinfo c','c.id=i.cid','LEFT')->join('c_customerorder o','o.crm_into_id=i.id','LEFT')
                    ->where($sql)
                    ->where('i.consulation_shop_code', 'in', $shops)
                    ->field($field)
                    // ->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('crm_c_customer_intostore i')->join('crm_c_customerinfo c','c.id=i.cid','LEFT')->join('c_customerorder o','o.crm_into_id=i.id','LEFT')
                    ->where($sql)
                    ->where('i.consulation_shop_code', 'in', $shops)
                    ->field($field)
                    // ->where('o.consultation_type','not in', $noCon)
                    ->group('i.id')
                    ->order('i.yjd_day desc ,o.id desc')
                    ->select();
            }
            $count = db('crm_c_customer_intostore i')->join('crm_c_customerinfo c','c.id=i.cid','LEFT')->join('c_customerorder o','o.crm_into_id=i.id','LEFT')
                ->where($sql)
                ->where('i.consulation_shop_code', 'in', $shops)
                ->where($param['search_time'],'between',[$start,$end])
                ->count();
        }else{
            if($param['limit']){
                $info = db('crm_c_customer_intostore i')->join('crm_c_customerinfo c','c.id=i.cid','LEFT')->join('c_customerorder o','o.crm_into_id=i.id','LEFT')
                    ->where($sql)
                    ->where('i.consulation_shop_code', 'in', $shops)
                    ->where($where)
                    ->where($param['search_time'],'between',[$start,$end])
                    ->field($field)
                    // ->where('o.consultation_type','not in', $noCon)
                    ->group('i.id')
                    ->order($param['search_time'].' desc ,o.id desc')
                    ->limit($param['limit'])
                    ->page($param['page'] ? $param['page'] : 1)
                    ->select();
            }else{
                $info = db('crm_c_customer_intostore i')->join('crm_c_customerinfo c','c.id=i.cid','LEFT')->join('c_customerorder o','o.crm_into_id=i.id','LEFT')
                    ->where($sql)
                    ->where('i.consulation_shop_code', 'in', $shops)
                    ->where($where)
                    ->where($param['search_time'],'between',[$start,$end])
                    ->field($field)
                    // ->where('o.consultation_type','not in', $noCon)
                    ->group('i.id')
                    ->order($param['search_time'].' desc ,o.id desc')
                    ->select();
                    // echo db()->getLastSql();
                    // exit;
            }
            $count = db('crm_c_customer_intostore i')->join('crm_c_customerinfo c','c.id=i.cid','LEFT')->join('c_customerorder o','o.crm_into_id=i.id','LEFT')
                ->where($sql)
                ->where($where)
                ->where($param['search_time'],'between',[$start,$end])
                ->where('i.consulation_shop_code', 'in', $shops)
                ->count();
        }
        $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]['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 customer_channel      渠道      必填
     * @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'],$param['customer_channel']);
            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'],$param['customer_channel']);
            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'],$param['customer_channel']);
            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   baby_name
     * @param   baby_sex
     * @param   baby_birthday           宝宝生日
     * @param   baby_address            出生医院
     * @param   ready_baby_day         预产期
     * @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'],0,$param['mwechat'],'');
        if($repeat['code'] != 200){
            //判断客资是否属于此网销
            foreach($repeat['data'] as $k=>$v){
                $res = controller('index/Customer','lib')->checkCustomer($v);
                if($res === false){
                    return array('error'=>1,'code'=>104,'msg'=>'此客资不属于此网销，请先创建回门');
                }
            }
        }
        $allShops = getShopInfo();
        $data = [
            'baby_name'            => $param['baby_name'],
            'baby_sex'            => $param['baby_sex'],
            'baby_birthday'            => $param['baby_birthday'] ? date('Y-m-d',strtotime($param['baby_birthday'])) : NULL,
            'baby_address'            => $param['baby_address'],
            'ready_baby_day'            => $param['ready_baby_day'] ? date('Y-m-d',strtotime($param['ready_baby_day'])) : NULL,
            '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'],
            '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'     => $param['target_time']?$param['target_time']:$create_time,
            'is_valid'             => 1,
            'yx_day'               => $param['target_time']?$param['target_time']:$create_time,
            'introducer_name'      => $param['introducer_name'],
            'introducer_tel'       => $param['introducer_tel'],
            'customer_birthday'    => $param['wbirthday'] ? date('Y-m-d H:i:s', strtotime($param['wbirthday'])) : NULL,
            'mate_birthday'        => $param['mbirthday'] ? date('Y-m-d H:i:s', strtotime($param['mbirthday'])) : NULL,
            'customer_remark'      => trim($param['customer_remark']),
        ];
        //这条客资所有联系方式
        $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{
            // 不管是不是重复客资，后来的数据要更新到新客户上，如果没有客户，要新建一个客户
            $tempMain = dealMain($repeat['c_unique'], $data);
            if ($tempMain['code'] == 200) {
                $data['c_unique'] = $tempMain['c_unique'];
            }else{
                db()->rollback();
                return array('error'=>1,'code'=>201,'msg'=>'主表创建客资失败');
            }
            $res = db('crm_c_customerinfo')->insertGetId($data);
            foreach($contact as $k => $v){
                $contactList[$k]['c_id']=$res;
                $contactList[$k]['contact']=$v;
                $contactList[$k]['brandclass']=$data['brandclass'];
                $contactList[$k]['c_unique']=$data['c_unique'];
                $contactList[$k]['customer_channel']='';
            }
            db('crm_c_customer_contact')->insertAll($contactList);
            if($res){
                //操作进店表
                $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,
                ];
            }
            $res = db('crm_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'=>'Customer',
                'action'=>'createCustomer',
            ];
            common_log($logData,'crm_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 order_sn                单号        必填
     * @param target_time             转单时间    选填
     * @param order_amount            订单套系    选填
     * @param consulation_shop_code   选填
     * @param consulation_shop_name   意向店面    选填
     * @param reception_id            选填
     * @param reception_name          接待人      选填
     * @param consultation_type_id
     * @param consultation_type       消费类型
     * @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('crm_c_customer_intostore')->where('id',$param['id'])->where('status',1)->find();
        if(empty($into)){
            return array('error'=>1,'code'=>101,'msg'=>'未通过进店ID获取到进客数据');
        }

        $info = db('crm_c_customerinfo')->where('id',$into['cid'])->field('id,c_unique,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'=>'该客资已成单，并且已设置为不能成多单，请新创建客资');
        }
        //判断客资是否属于此网销
        $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'=>$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_sn = $param['order_sn'] ? $param['order_sn'] : 'sx_erp'.time().generate_code();
        $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'],
            'order_type'=>$info['order_type'],
            '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'],
            'order_shop_code' => $param['consulation_shop_code'],
            'order_shop_name' => $param['consulation_shop_name'],
        ];
        $cData = [
            'totalpay_money'=>floatval($param['order_amount']),
            'order_number'=>$order_sn,
            'order_start_time'=>$date,
            'order_type'=>$info['order_type'],
            '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['is_intostore'] != 2){
            $cData['is_intostore'] = 2;
            $cData['syjd_day'] = $target_time;
        }
        if(!$info['consultation_type']){
            $cData['consultation_type_id'] = $info['consultation_type_id'];
            $cData['consultation_type'] = $info['consultation_type'];
        }
        // 追踪数据
        $track['gtType'] = 4;
        $track['c_unique'] = $info['c_unique'];
        $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('crm_c_customerinfo')->where('id',$into['cid'])->update($cData);
            db('crm_c_customer_order')->insert($order);
            db('crm_c_customer_intostore')->where('id',$param['id'])->update($intostore);
            db('crm_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'=>'Customer',
                'action'=>'createNewCustomer',
            ];
            common_log($logData,'crm_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('crm_c_customer_intostore i')->join('crm_c_customerinfo c','c.id=i.cid','LEFT')->join('crm_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.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,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,baby_name,baby_sex,baby_birthday,baby_address,ready_baby_day')->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 $return;
    }
    /*
   *getCustomerNumber
   * 首页今日登记数,预约进店数（按意向店面算）
   * shop_code
   * */
    public function getCustomerNumber($data){
        if(empty($data['shop_code'])){
            return json(array('code'=>100,'msg'=>'未获取到店面编码'));
        }
        $cus = db('crm_c_customerinfo c')->join('crm_c_customer_intostore i','c.id=i.cid','LEFT')
            ->where('c.is_status',1)
            ->where('i.status',1)
            ->where('c.dj_day','like','%'.date('Y-m-d').'%')
            ->count('c.id');
        $yjd = db('crm_c_customerinfo c')->join('crm_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('crm_c_customerinfo c')->join('crm_c_customer_intostore i','c.id=i.cid','LEFT')
            ->where('c.is_status',1)
            ->where('i.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('crm_c_customerinfo c')->join('crm_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('crm_c_customerinfo c')->join('crm_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('crm_c_customerinfo c')->join('crm_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
  * @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('crm_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('crm_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'=>'Customer',
            'action'=>'editSyjd',
        ];
        db()->startTrans();
        try{
            db('crm_c_customer_intostore')->where('id',$param['id'])->update($iData);
            if(!empty($cData)){
                db('crm_c_customerinfo')->where('id',$info['id'])->update($cData);
            }
            common_log($logData,'crm_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());
        }
    }
}