<?php
/**
 * CRM 后台队列 
 * 
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 * 
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2017-10-17 $
 */
namespace app\crm\controller;
use think\Controller;
use think\Session;
use app\common\lib\redisQueue;

class Systemlist extends Controller {

	public function allotData($data){
		$success = 0;
		$false = 0;
		$hid = $data['hid'];
		$eid = $data['eid'];
		// 单条
		if ($data['type'] == 1) {
			$res = $this->disposeHistoryData($eid, $hid, $data['staff_id'],$data['identity'],$data['cinfo'],$data['old_data'],$data['new_data'],$data['controller'],$data['action']);
			// 0609  这里是不是不用了
			db('c_history_data')->where('id',$hid)->delete();
		}else if ($data['type'] == 2) { // 客资批量导入
			// 根据eid获取所有批量导入的客资
			$customers = db('crm_c_customerinfo')->where('eid', $data['eid'])->select();
			foreach ($customers as $key => $value) {
				$cinfo = [
					'id'     => $value['id'],
		            'dj_id'  => $value['dj_staff_id'],
		            'dj_day' => $value['dj_day'],
				];
				$oldData = [];
				$newData = $value;
				$res = $this->disposeHistoryData($eid, $hid, $data['staff_id'],$data['identity'],$cinfo,$data['old_data'],$data['new_data'],$data['controller'],$data['action']);
				if ($res) {
					$success++;
				}else{
					$false++;
				}
			}
			if ($false==0) {
				db('c_history_data')->where('id',$hid)->delete();
			}
		}
		// action('Message/historyDataRedisList');
	}

	/**
	 * 对历史数据的处理(记录与更改)
	 * @param  str	    staff_id	操作者ID		   exp：6
	 * @param  str	    identity	操作身份		   exp：录入record，筛客filter，销售sale 
	 * @param  str	    cinfo	    customerinfo       exp：array(id,dj_id,dj_day,sel_id,sel_day,jr_id,jr_day)
	 * @param  array	oldData	    原始数据
	 * @param  array	newData     新数据
	 * @param  str  	controller	控制器名
	 * @param  str  	action  	方法名
	 *
	 * @return boolean
	 * @author Eric
	 */
	public function  disposeHistoryData($eid, $hid, $staff_id, $identity, $cinfo, $oldData, $newData, $controller, $action){
	    // 在客资编辑功能（customerInfo）
	    if ($controller=='Customer') {
	    	if ($action=='customerInfo' || $action=='customerSign') {
	    		foreach ($newData as $key => $value) {
		    		// 对比提交数据和原始数据
		    		if ($value != $oldData[$key]) {
		    			// 将字段  对应成  中文
			    		$kStr = translate('c_customerinfo',$key);
			    		// 记录日志  用
			    		$oldDataL[$kStr]  = $oldData[$key];
		                $newDataL[$kStr]  = $value;
		                // 数据统计用
		                $old_data[$key] = $oldData[$key];
		                $new_data[$key] = $value;
		            }else{
		            	// 如果提交数据和原始数据相同  重新启动队列
	            		action('crm/Message/historyDataRedisList');
		            }
		    	}
	    	}
	    	
	    }else{
	    	// 对比提交数据和原始数据
	        foreach ($newData as $key => $value) {
	        	// 找出更改的数据
	            if ($value != $oldData[$key]) {
	            	// 记录日志  用
	                $oldDataL[$key]  = $oldData[$key];
	                $newDataL[$key]  = $value;
	                // 数据统计  用
	                $old_data[$key] = $oldData[$key];
	                $new_data[$key] = $value;
	            }else{
	            	// 如果提交数据和原始数据相同  重新启动队列
	            	action('crm/Message/historyDataRedisList');
	            }
	        }
	    }
	    
		// 1:newdata，olddata，customerID，staffID，staffName
		$staffInfo = getStaffInfoById($staff_id);
		action_log($newDataL, $oldDataL, $cinfo['id'], $staff_id, $staffInfo['staffname'], $module, $controller, $action);
		unset($staffInfo);
		// exit;
		// 字段 setInc+1/setDec-1
		/*
		'dj_customer'	   '提报客资数',						     录入相关
		'dj_mobile'		   '提报手机号数',						     录入相关
		'sel_customer'	   '筛客 客资数量',				       筛客、
		'fp_customer'	   '分配客资数',			 销售相关、筛客、
		'fp_no_mobile'	   '分配无手机号数',		 销售相关、筛客、
		'add_mobile'	   '新增手机号数',		     销售相关、筛客、
		'valid_customer'   '有效客资数',			 销售相关、筛客、录入相关
		'no_valid_customer''无效客资数',			 销售相关、筛客、录入相关
		'yjd'			   '预约进店数',			 销售相关、筛客、录入相关
		'syjd_jk'		   '实际进店数，进客',	     销售相关、筛客、录入相关 erp提供
		'syjd_no_jk'	   '实际进店数，非进客',	 销售相关、筛客、录入相关 erp提供
		'order'			   '成单数',				 销售相关、筛客、录入相关 erp提供
		'valid_order'	   '有效成单数',			 销售相关、筛客、录入相关 erp提供
		'tel_visit'        '电访量'                  销售相关、筛客、录入相关
		'a_customer'	   'A客数',	                 销售相关、筛客、
		*/
		
		// 如果存在登记人
		if ($cinfo['dj_id']) {
			$data[$cinfo['dj_id']] = $cinfo['dj_day'];
		}
		// 如果存在筛客人
		if ($cinfo['sel_id']) {
			$data[$cinfo['sel_id']] = $cinfo['sel_day'];
		}
		// 如果存在接收人
		if ($cinfo['jr_id']) {
			$data[$cinfo['jr_id']] = $cinfo['jr_day'];
		}

		// 如果cinfo为空怎么处理

		foreach ($new_data as $key => $value) {
			// 存在客资 录入
			if ($key == 'customer_number' && $value && $identity == 'record') {
				$res = controller('crm/Systemlist','lib')->dj_customer($data, $cinfo['id'], $hid, $eid);
			}
			// 客资存在手机号 录入
			if ($key == 'customer_tel' && $value && $identity == 'record') {
				$res = controller('crm/Systemlist','lib')->dj_mobile($data, $cinfo['id'], $hid, $eid);
			}
			// 筛客数
			if ($key == 'is_sk' && $value == 1 && $identity == 'filter') {
			// if ($key == 'is_sel' && $value == 1 && $identity == 'filter') {
				$res = controller('crm/Systemlist','lib')->sel_customer($data, $staff_id);
			}
			// 分配客资数
			if ($key == 'is_fp' && $value == 1 && $identity == 'sale') {
				// 人工重新分配，从  已分配  到  已分配
				if ($old_data['is_fp'] == 1) {
					$odata[$old_data['jr_id']]= $old_data['jr_day'];
					// $ndata[$new_data['jr_id']]= $new_data['jr_day'];
					$res = controller('crm/Systemlist','lib')->fp_customer_new($odata);
				}else{
					$res = controller('crm/Systemlist','lib')->fp_customer($data);
				}
			}
			// 手机号相关
			if ($key == 'customer_tel' && $identity == 'sale') {
				// 分配无手机号数
				if (!$old_data['customer_tel'] && !$value) {
					$res = controller('crm/Systemlist','lib')->fp_no_mobile($data);
				}
				// 新增手机号数 客资存在手机号 编辑  // 无 ==> 有  +1
				else if (!$old_data['customer_tel'] && $value) {
					$sta = 'inc';
					$res = controller('crm/Systemlist','lib')->add_mobile($data, $sta);
				} 
				// 有 ==> 无 -1
				else if ($old_data['customer_tel'] && !$value) {
					$sta = 'dec';
					$res = controller('crm/Systemlist','lib')->add_mobile($data, $sta);
				}
			}
			// 有效 客资数  1有效；2：待定；3：无效
			if ($key == 'is_valid' && $value == 1 && $identity == 'sale') {
				// 从无状态（录入）到标记有效
				if ($old_data['is_valid'] == 2) {
					// 有效数+1
                    $sta = 'inc';
					$res = controller('crm/Systemlist','lib')->valid_customer($data, $sta);
				}
				// 从 ‘无’ 效标记为 ‘有’ 效
				else if ($old_data['is_valid'] == 3) {
					// 无效数-1   有效数+1
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->valid_customer($data, $sta);
				}
			}
			// 无效 客资数 1有效；2：待定；3：无效
			if ($key == 'is_valid' && $value == 2 && $identity == 'sale') {
				// 从无状态（录入）到标记无效
				if ($old_data['is_valid'] == 2) {
					// 无效数+1 
                    $sta = 'inc';
                    $res = controller('crm/Systemlist','lib')->no_valid_customer($data, $sta);
				}
				// 从 ‘有’ 效标记为 ‘无’ 效
				else if ($old_data['is_valid'] == 3) {
					// 有效数 -1   无效数+1
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->no_valid_customer($data, $sta);
				}
			}
            // 预约进店数  yjd
            if ($key == 'yjd_day' && $identity == 'sale') {
                // 预约 +1
                if (!$old_data['yjd_day'] && $value) {
                    $sta = 'inc';
                    $res = controller('crm/Systemlist','lib')->yjd($data, $sta);
                }
                // 取消预约 -1
                if ($old_data['yjd_day'] && !$value) {
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->yjd($data, $sta);
                }
            }
            // 实际进店数
            if ($key == 'is_intostore' && $value && $identity == 'sale') {
                // 未进店
                if ($value == 1) {
                    // 由进店进客  转为  未进店
                    if ($old_data['is_intostore'] == 2) {
                        $sta = 'dec';
                        $res = controller('crm/Systemlist','lib')->syjd_jk($data, $sta);
                    }
                    // 由进店非进客  转为  未进店
                    if ($old_data['is_intostore'] == 3) {
                        $sta = 'dec';
                        $res = controller('crm/Systemlist','lib')->syjd_no_jk($data, $sta);
                    }
                }
                // 进店进客  syjd_jk
                if ($value == 2) {
                    // 由未进店  转为  进店进客
                    if ($old_data['is_intostore'] == 1) {
                        $sta = 'inc';
                        $res = controller('crm/Systemlist','lib')->syjd_jk($data, $sta);
                    }
                    // 由进店非进客  转为  进店进客
                    if ($old_data['is_intostore'] == 3) {
                        $sta = 'no';
                        $res = controller('crm/Systemlist','lib')->syjd_jk($data, $sta);
                    }
                }
                // 进店非进客  syjd_no_jk
                if ($value == 3) {
                    // 由未进店  转为  进店非进客
                    if ($old_data['is_intostore'] == 1) {
                        $sta = 'inc';
                        $res = controller('crm/Systemlist','lib')->syjd_no_jk($data, $sta);
                    }
                    // 由进店进客  转为  进店非进客
                    if ($old_data['is_intostore'] == 2) {
                        $sta = 'no';
                        $res = controller('crm/Systemlist','lib')->syjd_no_jk($data, $sta);
                    }
                }
            }
            // 成单数  orders
            if ($key == 'order_status' && $value && $identity == 'sale') {
                // 成单
                if ($old_data['order_status'] !=1 && $value == 1) {
                    $sta = 'inc';
                    $res = controller('crm/Systemlist','lib')->orders($data, $sta);
                }
                // 由成单 ==> 未成单
                else if ($old_data['order_status'] ==1 && $value == 2) {
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->orders($data, $sta);
                }
            }
            // 有效成单数valid_order
            if ($key == 'order_valid' && $value && $identity == 'sale') {
                // 有效
                if ($old_data['order_valid'] != 2 && $value == 2) {
                    $sta = 'inc';
                    $res = controller('crm/Systemlist','lib')->valid_order($data, $sta);
                }
                // 由 有效 ==> 未 无效
                else if ($old_data['order_valid'] == 2 && $value == 1) {
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->valid_order($data, $sta);
                }
            }
            // A客数  a_customer
            if ($key == 'op_signinfo' && $value && $identity == 'sale') {
                if( ($old_data['op_signinfo']!='a'||$old_data['op_signinfo'] !='A')&&($value=='a'||$value=='A') ){
                    $sta = 'inc';
                    $res = controller('crm/Systemlist','lib')->a_customer($data, $sta);
                }
                if( ($old_data['op_signinfo']=='a'||$old_data['op_signinfo']=='A')&&($value!='a'||$value!='A') ){
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->a_customer($data, $sta);
                }
            }
            // 电访量
            if ($key == 'tel_num' && $value && $identity == 'sale') {
            	// $sta = 'inc';
            	$res = controller('crm/Systemlist','lib')->tel_num($data);
            }
		}
		// exit;
		return $res;
	}

	//客资分配 自动 Eric
	public function customerAllot($id, $staff_id){
		// 获取录入人信息  如果是本人录入，分配给本人  符合某个工作类型
		$staffinfo = getStaffInfoById($staff_id);
		$workTypes = 7;
		if (is_array($staffinfo['work_type'])) {
			$is_in = in_array($workTypes, $staffinfo['work_type']);
		}else{
			if ($workTypes == $staffinfo['work_type']) {
				$is_in = true;
			}else{
				$is_in = false;
			}
		}
		// 直接分配给提报人
		if ($is_in) {
			// 获取要分配的员工信息，执行分配动作 , 并发送消息
			// 分配  用数据
			$date = date('Y-m-d H:i:s');
			$data['sales_staff_id']	   = $staff_id;
			$data['sales_staff']	   = $staffinfo['staffname'];
			$data['sales_staff_number']= $staffinfo['staffnumber'];
			$data['fp_day']			   = $date;
			$data['is_fp']			   = 1;

			// 消息  用数据  //send_type:'消息类型:1:短消息(弹窗)；2：通知', 默认接收
			$channel = 'notice';
			$message = array(
				'customer_id' => $id,
				'send_id'	  => '-1',
				'send_name'   => 'system',
				'send_type'   => '1',
				'send_msg'    => '您有一条新客资',
				'send_time'   => $date,
				'receive_id'  => $staffinfo['staff_id'],
				'receive_name'=> $staffinfo['staffname'],
				'receive_status'=> 2,
			);

			// 开启事务
			db()->startTrans();
			try {
				db('crm_c_customerinfo')->where('id', $id)->update($data);
				db('crm_c_message')->insert($message);
				db()->commit();
				// 发消息
				$message['id'] = db()->getLastInsID;
				redisQueue::init()->publish($channel, $message);
				return true;
			} catch (Exception $e) {
				db()->rollback();
				return false;
			}
			// 根据客资id 获取客资详情
			$cInfo = controller("Customer","lib")->getCustomerInfo($id);
			// 进入数据统计队列
			$old = [
				'sales_staff_id'	=> $cInfo['sales_staff_id'],
				'sales_staff'		=> $cInfo['sales_staff'],
				'sales_staff_number'=> $cInfo['sales_staff_number'],
				'fp_day'			=> $cInfo['fp_day'],
				'is_fp'			    => $cInfo['is_fp'],
			];
	        
	        $listName = 'historyDataList';
	        $cinfo = [
	            'id'     => $cInfo['id'],
	            'dj_id'  => $cInfo['dj_staff_id'],
	            'dj_day' => $cInfo['dj_day'],
	            'sel_id' => $cInfo['sk_staff_id'],
	            'sel_day'=> $cInfo['sk_time'],
	            'jr_id'  => $cInfo['sales_staff_id'],
	            'jr_day' => $dataC['jr_day'],
	        ];
	        $message = array(
	            'staff_id'     => $staff_id,
	            'identity'     => 'sale',
	            'cinfo'        => $cinfo,
	            'old_data'     => $old,
	            'new_data'     => $data,
	        );

	        ini_set('default_socket_timeout', '-1');
	        redisQueue::init()->rPush($listName, $message);
			// 重新blpop一次，有就继续，没有就阻塞
			action('Message/fpCustomerRedisList');
			return;
		}else{ // 按规则分配
			// 根据客资id 获取客资详情
			$customerInfo = controller("crm/Customer","lib")->getCustomerInfo($id);
			$shopCode = $customerInfo['shop_code'];
			$cid = $customerInfo['id'];
			// 查看缓存
			// $redis = connectRedis();
			// $rules = $redis->get('fpRule_'.$shopCode);
			$rules = cache('fpRule_'.$shopCode);
			$rules = json_decode($rules, true);
			// var_dump($rules);
			// $rules = '';
			if ($rules) {
				// 按照缓存的分配规则，分配
				foreach ($rules as $key => $value) {
					$rid = $value['id'];
					$member = $value['member'];
					if ($customerInfo[$value['customer_condition']] == $value['customer_value']) {
						// 条件分配
						if ($value['allocationtype'] == 1) {
							$res = controller("crm/Customer","lib")->fpCustomerT($cid, $rid, $member);
							// var_dump($res);
						}else{ // 平均分配
							$res = controller("crm/Customer","lib")->fpCustomerP($cid, $rid, $member);
							// var_dump($res);
						}
						if (!$res) {
							continue;
						}
						break;
					}
				}
			}else{
				// function 2，根据shop_code，获取相应规则，（crm:s_allocation_rule）
				$rules  = controller("crm/Setting","lib")->getRule($shopCode);
				// var_dump($rules);
				// function 4，根据筛选员工规则，筛选所有符合规则的员工
				$staffs = controller("Customer","lib")->getStaffs($rules, $shopCode);
				foreach ($staffs as $key => $value) {
					$rid = $value['id'];
					$member = $value['member'];
					// 分配依据，地区，来源，渠道等
					if ($customerInfo[$value['customer_condition']] == $value['customer_value']) {
						// 条件分配
						if ($value['allocationtype'] == 1) {
							$res = controller("Customer","lib")->fpCustomerT($cid, $rid, $member);
							// var_dump($res);
						}else{ // 平均分配
							$res = controller("Customer","lib")->fpCustomerP($cid, $rid, $member);
							// var_dump($res);
						}
						// 如果在该规则下没有获取到员工，跳出本次循环
						if (!$res) {
							continue;
						}
						break;
					}
				}
			}
			// 获取要分配的员工信息，执行分配动作 , 并发送消息
			// 分配  用数据
			$date = date('Y-m-d H:i:s');
			$data['sales_staff_id']	 = $res['id'];
			$data['sales_staff']		= $res['staffname'];
			$data['sales_staff_number'] = $res['staffnumber'];
			$data['fp_day']			 = $date;
			$data['is_fp']			  = 3;

			// 消息  用数据  //send_type:'消息类型:1:短消息(弹窗)；2：通知',
			$channel = 'notice';
			$message = array(
				'customer_id' => $cid,
				'send_id'	  => '-1',
				'send_name'   => 'system',
				'send_type'   => '1',
				'send_msg'    => '您有一条新客资',
				'send_time'   => $date,
				'receive_id'  => $res['id'],
				'receive_name'=> $res['staffname']
			);

			// 开启事务
			db()->startTrans();
			try {
				db('crm_c_customerinfo')->where('id', $cid)->update($data);
				db('crm_c_message')->insert($message);
				db()->commit();
				// 发消息
				$message['id'] = db()->getLastInsID;
				redisQueue::init()->publish($channel, $message);
				return true;
			} catch (Exception $e) {
				db()->rollback();
				return false;
			}
			// 记日志
			$old = [
				'sales_staff_id'	=> $customerInfo['sales_staff_id'],
				'sales_staff'		=> $customerInfo['sales_staff'],
				'sales_staff_number'=> $customerInfo['sales_staff_number'],
				'fp_day'			=> $customerInfo['fp_day'],
				'is_fp'			    => $customerInfo['is_fp'],
			];
			action_log($data, $old, $cid, '-1', 'system');
			
		}
		// 重新blpop一次，有就继续，没有就阻塞
		action('Message/fpCustomerRedisList');
	}




}