<?php
/**
 * CRM 基本模块  南宁qqbaby定制 
 * 默认接口方法，此方法内定议基础框架所需要的方法，用于验证模块合法性，模块版本，对接基础架构中需要的方法
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: yuanweibo<1198002730@qq.com> 2021-04-19 $
 */
namespace app\crm\controller;
use think\Cache;
use app\index\controller\Base;
use think\Exception;
use think\Controller;
class Nnqq extends Base{
    /*--------------------------------- 南宁qqbaby定制 客资流转 ---------------------------------*/
        /**
         * 客资录入时新增两个字段，
         * is_liuzhuan 默认是1 代表这个客资未流转过 流转之后 修改为2 代表该客资流转过，可以查看，不允许追踪
         **/

        /**
         * 客资流转页面
         */
        public function customerRemove(){
            // 南宁qqbaby  2021-04-19
            if (!customize('nnqqbaby')) {
                return $this->redirect('/');
            }

            // $mc = new \app\common\lib\mcInterface();
            // 检查权限
            // if (!check_right('')) {
                // $return = array('error'=>'1','msg'=>'您没有客资流转的权限，请先设置权限');
                // return json($return);exit;
            // }
            // 获取当前操作人的可操作店 并默认选中当前店
            $p = [
                'staff_id'=> session('staff_id'),
                'brandclass_id'=> session('brandclass_id'),
                'shop_type' => session('shop_type')
            ];
            $temp_shops = getShops($p);
            $shopList = [];
            foreach ($temp_shops as $key => $value) {
                $temp['shop_code'] = $value['shop_code'];
                $temp['shop_name'] = $value['shop_name'];
                if ($value['shop_code'] == session('shop_code')) {
                    $temp['selected'] = 1;
                    // 查询当前店下的部门
                    $pd['shop_code'] = $value['shop_code'];
                    $dList = getDepartments($pd);
                    $departmentList = [];
                    foreach ($dList as $k => $v) {
                        $departmentList[$k]['id'] = $v['id'];
                        $departmentList[$k]['department_name']= $v['department_name'];
                    }
                    $this->assign('departmentList',$departmentList);
                }else{
                    $temp['selected'] = 0;
                }
                $shopList[] = $temp;
            }
            $this->assign('shopList',$shopList);
            
            return $this->fetch();
        }
        /**
         * 客资流转页面 ‘查询’ 根据 预产期 宝宝生日 预产期和宝宝生日 查询客资
         * @param  day_type    时间类型（预产期 宝宝生日 预产期和宝宝生日）
         * @param  shop_code   当前客资的追踪店面
         * @param  dj_staff    当前客资的录入人
         * @param  sale_staff  当前客资的追踪人
         * @param  start       开始时间
         * @param  end         结束时间
         * @param  page        页码
         * @param  limit       单页数量
         *
         * @return json
         * @author lilong<lilong@suxuantech.cn>
         */
        public function customerFind(){
            // 检查权限
            // if (!check_right('')) {
            //     $return = array('msg'=>'您没有客资流转的权限，请先设置权限');
            //     return json($return);exit;
            // }
            $param = input();
            if (!$param['customer_tel']) {
                if (!$param['shop_code']) {
                    $return = array('msg'=>'请选择客资归属店面');
                    return json($return);exit;
                }
                if (!$param['day_type']) {
                    $return = array('msg'=>'请选择时间类型');
                    return json($return);exit;
                }
                if (!$param['start']) {
                    $return = array('msg'=>'请选择开始时间');
                    return json($return);exit;
                }
                if (!$param['end']) {
                    $return = array('msg'=>'请选择结束时间');
                    return json($return);exit;
                }
            }
            
            // $page = $param['page'];
            // $limit = $param['limit'];

            $where['c.c_from']     = 1; // 不包含erp客资
            $where['c.is_status']  = 1; // 未删除的客资
            $where['c.is_liuzhuan']= 1; // 未流转的客资
            $where['c.brandclass_id']= session('brandclass_id'); // 所属事业部
            $sql  = ' 1=1 ';
            if ($param['customer_tel']) {
                $where['c.customer_tel'] = trim($param['customer_tel']);
            }else{
                if ($param['shop_code']) {
                    $where['c.shop_code']= $param['shop_code'];
                }
                if ($param['department_id']) {
                    $where['c.sales_department_id']= $param['department_id'];
                }
                if ($param['group_id']) {
                    $sql .= ' and (c.dj_group_id = "'.$param['group_id'].'" or c.sales_group_id = "'.$param['group_id'].'" ) ';
                }
                $start= date('Y-m-d 00:00:00', strtotime($param['start']));
                $end  = date('Y-m-d 23:59:59', strtotime($param['end']));
                // 预产期
                if ($param['day_type'] == 'ready_baby_day') {
                    $sql .= ' and (c.ready_baby_day between "'.$start.'" and "'.$end.'" ) ';
                }
                // 宝宝生日
                else if ($param['day_type'] == 'baby_birthday') {
                    $sql .= ' and (c.baby_birthday between "'.$start.'" and "'.$end.'") ';
                }
                // 宝宝生日或预产期
                else if ($param['day_type'] == 'ready_baby_birthday') {
                    $sql .= ' and (c.ready_baby_day between "'.$start.'" and "'.$end.'" or c.baby_birthday between "'.$start.'" and "'.$end.'") ';
                }
            }
            
            $cusInfos = db('crm_c_customerinfo')->alias('c')
                ->where($where)->where($sql)
                // ->limit($limit)->page($page)
                ->field('c.id,c.customer_name,c.customer_tel,c.customer_wechat,c.ready_baby_day,c.baby_name,c.baby_birthday,c.customer_channel,c.province,c.city,c.customer_address,c.customer_remark,c.is_valid,c.is_success,c.dj_staff,c.sales_staff,c.shop_name,c.sales_department_name,c.dj_group_name,c.sales_group_name')
                ->select();
            $sql0 = db()->getLastSql();
            foreach ($cusInfos as $key => $value) {
                $cusInfos[$key]['ready_baby_day'] = $value['ready_baby_day'] ? date('Y-m-d',strtotime($value['ready_baby_day'])) : '';
                $cusInfos[$key]['baby_birthday'] = $value['baby_birthday'] ? date('Y-m-d',strtotime($value['baby_birthday'])) : '';

                $cusInfos[$key]['is_valid'] = getIsValidAttr($value['is_valid']);
                $cusInfos[$key]['is_success'] = getIsSuccess($value['is_success']);
            }
            $count = db('crm_c_customerinfo')->alias('c')
                ->where($where)->where($sql)
                ->count();
            $result['sql']  = $sql0;
            $result['code'] = 0;
            $result['msg']  = '';
            $result['count']= $count;
            $result['data'] = $cusInfos;
            return json($result);
        }
        /**
         * 客资流转页面 根据条件（ 时间条件/店/部门/组 ） 将符合条件的客资流转到目标  店/部门/组 下的某人
         * @param  shop_code     当前客资的追踪店面
         * @param  department_id 当前客资的追踪部门
         * @param  group_id      当前客资的追踪小组
         * @param  day_type      时间类型（预产期 宝宝生日 预产期和宝宝生日）
         * @param  start         开始时间
         * @param  end           结束时间
         * @param  t_shop_code   客资的目标店面 target
         * @param  t_department  客资的目标部门 target
         * @param  t_group       客资的目标小组 target
         * @param  t_staff       客资的目标人员 target
         * @param  ids           选中的客资id
         *
         * @return boolen
         * @author lilong<lilong@suxuantech.cn>
         */
        public function customerRemoveAction(){
            // 检查权限
            // if (!check_right('')) {
            //     $return = array('code'=>99,'msg'=>'您没有客资流转的权限，请先设置权限');
            //     return json($return);exit;
            // }
            $param = input();
            $sql = 'c.c_from=1 AND c.is_status=1 AND c.is_liuzhuan=1 and brandclass_id='.session('brandclass_id');

            if (!empty(json_decode($param['ids'],true))) {
                $ids = '';
                $temp = json_decode($param['ids'],true);
                foreach ($temp as $key => $value) {
                    $ids .= $value.',';
                }
                $sql .= ' AND c.id IN ('.trim($ids,',').') ';
            }else{
                if (!$param['shop_code']) {
                    $return = array('code'=>100,'msg'=>'请选择客资归属店面');
                    return json($return);exit;
                }
                if (!$param['day_type']) {
                    $return = array('code'=>101,'msg'=>'请选择时间类型');
                    return json($return);exit;
                }
                if (!$param['start']) {
                    $return = array('code'=>102,'msg'=>'请选择开始时间');
                    return json($return);exit;
                }
                if (!$param['end']) {
                    $return = array('code'=>103,'msg'=>'请选择结束时间');
                    return json($return);exit;
                }
                if (!$param['t_shop_code']) {
                    $return = array('code'=>104,'msg'=>'请选择目标店面');
                    return json($return);exit;
                }
                if (!$param['t_staff_id']) {
                    $return = array('code'=>105,'msg'=>'请选择目标员工');
                    return json($return);exit;
                }

                if ($param['shop_code']) {
                    $sql .= ' AND c.shop_code="'.$param['shop_code'].'"';
                }
                if ($param['department_id']) {
                    $sql .= ' AND c.sales_department_id='.$param['department_id'];
                }
                if ($param['group_id']) {
                    $sql .= ' and (c.dj_group_id = "'.$param['group_id'].'" or c.sales_group_id "'.$param['group_id'].'" ) ';
                }

                $start= date('Y-m-d 00:00:00', strtotime($param['start']));
                $end  = date('Y-m-d 00:00:00', strtotime($param['end']));
                // 预产期
                if ($param['day_type'] == 'ready_baby_day') {
                    $sql .= ' AND (c.ready_baby_day between "'.$start.'" AND "'.$end.'" ) ';
                }
                // 宝宝生日
                else if ($param['day_type'] == 'baby_birthday') {
                    $sql .= ' AND (c.baby_birthday between "'.$start.'" AND "'.$end.'") ';
                }
                // 宝宝生日或预产期
                else if ($param['day_type'] == 'ready_baby_birthday') {
                    $sql .= ' AND (c.ready_baby_day between "'.$start.'" AND "'.$end.'" or c.baby_birthday between "'.$start.'" AND "'.$end.'") ';
                }

            }


                
            // 根据条件查出所有符合条件的客资 复制客资信息
            // $where['c.c_from']     = 1;// 不包含erp客资
            // $where['c.is_status']  = 1;// 未删除的客资
            // $where['c.is_liuzhuan']= 1;// 未流转的客资
            
                
            

            $count = db('crm_c_customerinfo')->alias('c')
                ->where($sql)->count();
            // echo db()->getLastSql();
            // die;
            if ($count == 0) {
                $return = array('code'=>300,'msg'=>'没有可流转的客资，请重新选择客资');
                return json($return);exit;
            }

            $insertSql = '';
            $now = date('Y-m-d H:i:s');
            db()->startTrans();
            try {
                // 写入导入表获取导入id
                $excelInsert['file_name'] = '客资流转';
                $excelInsert['staff_id']  = session('staff_id');
                $excelInsert['staff_name']= session('staff_name');;
                $excelInsert['addtime'] = date('Y-m-d H:i:s');
                $excelInsert['status'] = 1;
                $excelInsert['all_number'] = $count;
                $excelInsert['import_number'] = $count;
                $excelInsert['fail_number'] = 0;
                $excelInsert['belong_shop_code'] = $param['shop_code'];
                $eid = db('crm_c_excel_import')->insertGetId($excelInsert);
                // 复制进客资表 及 from 表
                $cusCoyp = '
                INSERT INTO crm_c_customerinfo 
                    (eid,c_unique,customer_number,customer_name,customer_sex,customer_tel,customer_wechat,customer_weibo,customer_qq,province_id,province,city_id,city,county_id,county,customer_address,mate_name,mate_sex,mate_tel,mate_wechat,mate_weibo,mate_qq,mate_address,consultation_type_id,consultation_type,customer_type,customer_channel_id,customer_channel,customer_cource_id,customer_cource,access_model_id,access_model,customer_region_id,customer_region,is_valid,yx_day,customer_birthday,customer_idtype,customer_idnumber,mate_birthday,mate_idtype,mate_idnumber,introducer_name,introducer_ordernum,introducer_tel,wedding_date,dj_staff,dj_staff_id,dj_staff_number,dj_day,fp_staff_id,fp_staff,fp_staff_number,fp_day,is_fp,sales_staff,sales_staff_id,sales_staff_number,jr_day,customer_remark,shop_name,shop_code,brandclass,create_time,add_shop_code,add_shop_name,tel_staff_id,tel_staff,tel_time,is_first_tel,ready_baby_day,baby_birthday,baby_address,marry_day,tel_belong,tel_operator,tel_area_code,brandclass_id,is_first_wechat,wechat_staff_id,wechat_staff,wechat_time,update_time,dj_department_id,sales_department_id,baby_name,baby_sex,home_phone,email,introduce_staff_name,ad_page,dj_department_name,sales_department_name,b_id,b_name,sales_group_id,sales_group_name)
                SELECT
                    '.$eid.',c_unique,UUID(),customer_name,customer_sex,customer_tel,customer_wechat,customer_weibo,customer_qq,province_id,province,city_id,city,county_id,county,customer_address,mate_name,mate_sex,mate_tel,mate_wechat,mate_weibo,mate_qq,mate_address,consultation_type_id,consultation_type,customer_type,customer_channel_id,customer_channel,customer_cource_id,customer_cource,access_model_id,access_model,customer_region_id,customer_region,2,"'.$now.'",customer_birthday,customer_idtype,customer_idnumber,mate_birthday,mate_idtype,mate_idnumber,introducer_name,introducer_ordernum,introducer_tel,wedding_date,"'.session('staff_name').'",'.session('staff_id').',"'.session('staff_number').'","'.$now.'",'.session('staff_id').',"'.session('staff_name').'","'.session('staff_number').'","'.$now.'",1,"'.$param['t_staff_name'].'",'.$param['t_staff_id'].',sales_staff_number,"'.$now.'",customer_remark,"'.$param['t_shop_name'].'","'.$param['t_shop_code'].'",brandclass,create_time,add_shop_code,add_shop_name,'.session('staff_id').',"'.session('staff_name').'",tel_time,is_first_tel,ready_baby_day,IFNULL(baby_birthday,ready_baby_day),baby_address,marry_day,tel_belong,tel_operator,tel_area_code,brandclass_id,is_first_wechat,wechat_staff_id,wechat_staff,wechat_time,update_time,'.session('department_id').','.$param['t_department_id'].',baby_name,baby_sex,home_phone,email,introduce_staff_name,ad_page,"'.session('department_name').'","'.$param['t_department_name'].'",b_id,b_name,"'.$param['t_group_id'].'","'.$param['t_group_name'].'"
                FROM
                    `crm_c_customerinfo` `c` WHERE '.$sql;
                //2021-04-19 fp_department_id,fp_department_name,qq_staff_id,qq_staff,qq_time,,qq_time,is_first_qq,creator_day,introducer_number,introducer_type 这些字段没有 去掉
                db()->query($cusCoyp);

                // 更新原客资的状态（ is_liuzhuan=2 ）
                db('crm_c_customerinfo')->alias('c')
                    ->where($where)->where($sql)
                    ->update(['is_liuzhuan'=>2 ]);
                db()->commit();
                // 更新联系方式（排重）表
                $cusTelSql = 'INSERT INTO crm_c_customer_contact(c_id,c_unique,contact,brandclass,customer_channel) SELECT id,c_unique,customer_tel,brandclass,add_shop_code FROM crm_c_customerinfo WHERE eid='.$eid.' AND IFNULL(customer_tel,"") <> ""';
                db()->query($cusTelSql);
                $cusWetchatSql = 'INSERT INTO crm_c_customer_contact(c_id,c_unique,contact,brandclass,customer_channel) SELECT id,c_unique,customer_wechat,brandclass,add_shop_code FROM crm_c_customerinfo WHERE eid='.$eid.' AND IFNULL(customer_wechat,"") <> ""';
                db()->query($cusWetchatSql);
                $mateTelSql = 'INSERT INTO crm_c_customer_contact(c_id,c_unique,contact,brandclass,customer_channel) SELECT id,c_unique,mate_tel,brandclass,add_shop_code FROM crm_c_customerinfo WHERE eid='.$eid.' AND IFNULL(mate_tel,"") <> ""';
                db()->query($mateTelSql);
                $mateWechatSql = 'INSERT INTO crm_c_customer_contact(c_id,c_unique,contact,brandclass,customer_channel) SELECT id,c_unique,mate_wechat,brandclass,add_shop_code FROM crm_c_customerinfo WHERE eid='.$eid.'  AND IFNULL(mate_wechat,"") <> ""';
                db()->query($mateWechatSql);
                // 查询新添加的客资 补充
                do {
                    $trackData= [];
                    $logsData = [];
                    $now = date('Y-m-d H:i:s');
                    $cusInfo  = db('crm_c_customerinfo')->where('eid',$eid)->where('track_record','null')->field('id,c_unique,customer_name,customer_number,customer_tel,customer_wechat,ready_baby_day,baby_birthday,baby_name')->limit('100')->select();
                    if (!$cusInfo) {
                        break;
                    }
                    $ids = '';
                    foreach ($cusInfo as $key => $value) {
                        $ids .= $value['id'].',';
                        // 追踪记录数据
                        $trackData[$key]['gtType'] = '4';
                        $trackData[$key]['c_unique'] = $value['c_unique'];
                        $trackData[$key]['customer_id'] = $value['id'];
                        $trackData[$key]['customer_number'] = $value['customer_number'];
                        $trackData[$key]['customer_name'] = $value['id'];
                        $trackData[$key]['customer_tel'] = $value['customer_tel'];
                        $trackData[$key]['sales_day'] = $now;
                        $trackData[$key]['sales_staff'] = session('staff_name');
                        $trackData[$key]['sales_staff_id'] = session('staff_id');
                        $trackData[$key]['shop_name'] = $param['t_shop_name'];
                        $trackData[$key]['shop_code'] = $param['t_shop_code'];
                        $trackData[$key]['sales_remark'] = '新增客资==》客资流转，所属店面：'.$param['t_shop_name'].'；所属部门：'.$param['t_department_name'].'；所属小组：'.$param['t_group_name'].'；所属员工：'.$param['t_staff_name'];
                        // 操作日志数据
                        $logsData[$key]['module'] = 'crm';
                        $logsData[$key]['controller'] = 'Nnqq';
                        $logsData[$key]['action'] = 'customerRemoveActionx';
                        $logsData[$key]['old_data'] = [];
                        $logsData[$key]['data'] = '妈妈姓名：'.$value['customer_name'].'<br/>妈妈手机：'.$value['customer_tel'].'<br/>妈妈微信：'.$value['customer_wechat'].'<br/>预产期：'.$value['ready_baby_day'].'<br/>宝宝姓名：'.$value['baby_name'].'<br/>宝宝生日：'.$value['baby_birthday'].'<br/>所属店面：'.$param['t_shop_name'].'<br/>所属部门：'.$param['t_department_name'].'<br/>所属小组：'.$param['t_group_name'].'<br/>所属员工：'.$param['t_staff_name'];
                        $logsData[$key]['customer_id'] = $value['id'];
                        $logsData[$key]['staff_name'] = session('staff_name');
                        $logsData[$key]['staff_id'] = session('staff_id');
                        $logsData[$key]['ip'] = get_client_ip();
                        $logsData[$key]['create_time'] = $now;
                    }
                    $ids = trim($ids);
                    // 批量更新客资最后一次追踪记录
                    db('crm_c_customerinfo')->where('id','in',$ids)->update(['track_record'=>'新增客资==》客资流转']);
                    // 批量添加追踪记录
                    db('crm_c_salestrackinginfo')->insertAll($trackData);
                    // 批量添加操作日志
                    db('crm_action_log','db_logs')->insertAll($logsData);
                    $count = db('crm_c_customerinfo')->where('eid',$eid)->where('track_record','null')->count();
                } while ( $count>0 );
                db()->commit();
                return array('code'=>200,'msg'=>'客资流转成功');
            } catch (\Exception $e) {
                db()->rollback();
                return array('code'=>199,'msg'=>'客资流转失败'.$e->getMessage().'-'.$e->getLine(),'data'=>$e->getTrace());
            }
        }
    /*--------------------------------- 南宁qqbaby定制 客资流转 ---------------------------------*/
}