<?php
class customerAction extends baseAction
{
	function search()
	{
		$Params =  mvc::$URL_PARAMS;
		LibTpl::Set('Params', $Params);

		if (isset($Params['from']) && $Params['from'] == 'ypim') {
			$Params['page'] = 1;
			$Params['per'] = 1;
			$LibCrmApi = new LibCrmApi();
			$res = $LibCrmApi->Get('cus/getCustomerList', $Params);
			$result = $res['data'];
			if (count($result['data']) == 0) {
				LibFc::Go('http://crm2.yiparts.com:86/Admin/index.php/Member/Index?Type=0&account=' . $Params['word']);
				exit();
			}
		}

		$ypwModel = new YpwBase();
		$addressData = $ypwModel->YpwDb->Table(sprintf("select pc_pid,pc_id,pc_name from yp_province_city where pc_pid=0"));
		LibTpl::Set('address', $addressData);
		$LibCrmApi = new LibCrmApi();
		$res = $LibCrmApi->Get('cus/getBrands');
		LibTpl::Set('brandArr', $res['data']);
		$orderArr = [
			'null' => ['默认', ''],
			'pv' => ['浏览数', ' order by ua_pv desc'],
			'vin_count' => ['VIN数', ' order by ua_vin_count desc'],
			'number_count' => ['号码数', ' order by ua_number_count desc'],
			'epc_count' => ['EPC数', ' order by ua_epc_count desc']
		];
		LibTpl::Set('orderArr', $orderArr);
		//所有业务员
		$res = $this->getSalesUser();
		LibTpl::Set('salesArr',$res['data']);
		$endDayArr = [
			7 => '7天内',
			15 => '15天内',
			30 => '30天内',
			60 => '60天内',
			90 => '90天内',
			-7 => '过期7天',
			-15 => '过期15天',
			-30 => '过期30天',
			-60 => '过期60天',
			-365 => '所有过期'
		];
		LibTpl::Set('endDayArr', $endDayArr);
		//客户类型
		$typeArr = [0=>'公海客户',5=>'成交客户',6=>'过期客户'];
		if(LibFc::checkDlRule('DL12',false)){
			$typeArr = [0=>'公海客户',1=>'保护中',5=>'成交客户',6=>'过期客户',-1=>'已忽略'];
		}
		LibTpl::Set('typeArr',$typeArr);
		//服务项目
		$CrmBase = new CrmBase();
		$res = $CrmBase->get('fad_service',['*']);
		LibTpl::Set('sveArr',$res['data']);
		//客服
		$res = $this->getKefu();
		LibTpl::Set('kefuArr',$res['data']);

		$showCol = $this->getShowCol();
		LibTpl::Set('showCol',$showCol);

		LibTpl::Set('title', '客户资源库');
		LibTpl::Put();
	}

	function lists()
	{
		$Params =  mvc::$URL_PARAMS;
		$dataArr = $this->getCustomerList();
		LibTpl::Set('dataArr', $dataArr);
		$showCol = $this->getShowCol();
		LibTpl::Set('showCol',$showCol);
		// LibTpl::set('showCol',$_COOKIE['showCol']?explode(',',$_COOKIE['showCol']):array_keys($this->allCol()));
		LibTpl::Set('title', '客户资源库');
		LibTpl::Put();
	}

	/**
	 * @method 客户资源库
	 * @author zhengweihua 
	 * @copyright 2024-01-26
	 */
	public function getCustomerList()
	{
		$Params = mvc::$URL_PARAMS;
		$orderArr = [
			'null'=>['默认', ''],
			'pv'=>['浏览数', ' order by ua_pv desc'],
			'vin_count'=>['VIN数', ' order by ua_vin_count desc'],
			'number_count'=>['号码数', ' order by ua_number_count desc'],
			'epc_count'=>['EPC数', ' order by ua_epc_count desc']
		];
	
		$page = empty($Params['page']) || $Params['page'] < 1? 1: (int) $Params['page'];
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$now = time();
		$order = ' order by ctr_score desc';
		$table = 'crm_customer 
		left join ypdb_write.yp_user on ctr_uid = u_id
		left join ypdb_write.yp_user_act on ctr_uid = ua_uid
		left join yp_paojieling.pl_shop on ctr_uid = shop_id';
		$where = '';
		//是否有忽略客户的权限
		$ingore = LibFc::checkDlRule('DL12',false);
		if(!$ingore){
			$where  = 'and ctr_level_id!=-1';
		}
		LibTpl::Set('ingore',$ingore);
		//是否有更改客服的权限
		$changeKefu =LibFc::checkDlRule('DL13',false);
		LibTpl::Set('changeKefu',$changeKefu);

		//是否有更改业务员的权限
		$changeYwy = LibFc::checkDlRule('DL14',false);
		LibTpl::Set('changeYwy',$changeYwy);
		foreach($Params as $filed=>$val)
		{
			$val = LibFc::Escape($val);
			if($val == '') continue;
			switch($filed)
			{
				case 'score':
					$where .= sprintf(" and ctr_score >= %d", $val);
				break;
				case 'com_style':
					$tArr = [];
					foreach(explode(',', $val) as $tv)
					{
						if(!empty($tv)) $tArr[] = LibFc::Escape($tv);
					}
					if(!empty($tArr))
						$where .= sprintf(" and ctr_com_style in ('%s')", implode("','", $tArr));
				break;
				case 'pct_ids':
					$pctArr = explode(',', $val);
					$where .= sprintf(" and JSON_UNQUOTE(ctr_pct_ids->'$.pid') = %d", $pctArr[0]);
					if(!empty($pctArr[1]))
					{
						$where .= sprintf(" and JSON_UNQUOTE(ctr_pct_ids->'$.cid') = %d", $pctArr[1]);
					}
					$ftable = '(SELECT cfo_ctr_id, MAX(cfo_atime) AS lcfo_atime FROM crm_follow  GROUP BY cfo_ctr_id) as a';
					$table .= sprintf(" left join  %s  ON  ctr_id = a.cfo_ctr_id",$ftable);
					$order = 'order by ctr_score desc, lcfo_atime asc';
				break;
				case 'word':
					$workWhere = [
						sprintf(" ctr_comname like '%%%s%%'", $val),
						sprintf(" ctr_contact like '%%%s%%'", $val),
						sprintf(" ctr_tel like '%%%s%%'", $val),
						sprintf(" ctr_addr like '%%%s%%'", $val),
					];

					$LibYpApi = new LibYpApi();
					$dataArr = [
						'filed'=>['u_id'],
						'where'=>sprintf("and (u_name = '%s' or (u_mobile ='%s' and u_mobile_check='Y'))", $val, $val)
					];
					$res = $LibYpApi->Get('user/getUser', [], $dataArr);
					if(!empty($res['data']))
					{
						$workWhere[] = sprintf(" ctr_uid in (%s)", implode(',', array_column($res['data'], 'u_id')));
					}
					$where .= sprintf(" and (%s)", implode(' or ', $workWhere));
				break;
				case 'label_part': 
				case 'label_make': 
				case 'label_self': 
					$temp = [];
					foreach(explode(',', $val) as $t)
					{
						$t = (int) $t;
						if($t > 0) $temp[] = $t;
					}
					if(!empty($temp))
					{
						//全车件
						if($filed == 'label_part') $temp[] = 15;
						//全部
						if($filed == 'label_make') $temp[] = 21;
						$where .= sprintf(" and ctr_id in (select cul_ctr_id from crm_customer_label where cul_cla_id in (%s))", implode(',', $temp));
					}
				break;
				case 'pjlshop':
					if($val == 1)
					{//使用中
						$where .= sprintf(" and shop_id > 0 and shop_vip_etime > %d", $now);
						$order = ' order by shop_vip_etime asc';
					}
					else if($val == 2)
					{//已过期
						$where .= sprintf(" and shop_id > 0 and shop_vip_etime <=%d and shop_vip_etime > 0", $now);
						$order = ' order by shop_vip_etime desc';
					}
					else if($val == 3)
					{//未缴费
						$where .= ' and shop_id > 0 and IFNULL(shop_vip_etime,0)=0';
					}
					else if($val == 4)
					{//未申请
						$where .= ' and shop_id = 0 and IFNULL(shop_vip_etime,0)=0';
					}
					else if($val == 5)
					{//未入住：包括未缴费、未申请、已过期
						$where .= sprintf(" and IFNULL(shop_vip_etime,0) < %d", $now);
					}else if($val == 6)
					{//已申请
						$where .= ' and shop_id > 0';
						$order = ' order by shop_apply_time desc';
					}
				break;
				case 'brand_id':
					$tArr = [];
					foreach(explode(',', $val) as $tv)
					{
						if(!empty($tv)) $tArr[] =(int) $tv;
					}
					if(!empty($tArr))
					{
						$table .= ' join ypdb_write.yp_user_act_brand on ctr_uid = uab_uid';
						$where .= sprintf(" and uab_brand_id in(%s)", implode("','", $tArr));
						$order = ' order by uab_count desc, ctr_score desc, ctr_id';
					}
				break;
				case 'gz_part':
					$table .= ' join ypdb_write.yp_user_act_part on ctr_uid = uap_uid';
					$where .= sprintf(" and uap_part like '%%%s%%'", $val);
					$order = ' order by uap_count desc, ctr_score desc, ctr_id';
				break;
				case 'pjlshop_etime':
					$val = (int) $val;
					if($val < 0){
						$where .= sprintf(' and shop_id > 0 and shop_vip_etime <=%d and shop_vip_etime > 0', time());
						if($val !== -365) $where .= sprintf(' and shop_vip_etime >=%d', strtotime($val.'day'));	
						$order = ' order by shop_vip_etime desc';
					}else if($val > 0){
						$where .= sprintf(' and shop_id > 0 and shop_vip_etime >= %d and shop_vip_etime <= %d', time(), strtotime('+'.$val.'day'));
						$order = ' order by shop_vip_etime asc';
					}
				break;
				case 'etime':
					$temp = explode('~',$val);
					if(count($temp)>1){
						$where .= sprintf(' and shop_id > 0 and shop_vip_etime between %d and %d', strtotime($temp[0]),strtotime($temp[1])+86399);
					}
				break;
				case 'apply_time':
					$temp = explode('~',$val);
					if(count($temp)>1){
						$where .= sprintf(' and shop_id > 0 and shop_apply_time between %d and %d', strtotime($temp[0]),strtotime($temp[1])+86399);
					}
				break;
				case 'last_follow_name':
					//最后申请人
					$ftable = '(SELECT cfo_ctr_id, MAX(cfo_id) AS lcfo_id FROM crm_follow  GROUP BY cfo_ctr_id) as a 
					join crm_follow as b on a.lcfo_id=b.cfo_id and a.cfo_ctr_id=b.cfo_ctr_id';
					$sql = sprintf("SELECT a.cfo_ctr_id FROM %s WHERE cfo_au_uid = '%s'",$ftable,$val);
					$where .= sprintf(" AND ctr_id IN (%s)",$sql);
					break;
				case 'last_follow_time':
					//最后申请时间
					$temp = explode('~',$val);
					if(count($temp)>1){
						$ftable = '(SELECT cfo_ctr_id, MAX(cfo_id) AS lcfo_id FROM crm_follow  GROUP BY cfo_ctr_id) as a 
						join crm_follow as b on a.lcfo_id=b.cfo_id and a.cfo_ctr_id=b.cfo_ctr_id';
						$sql = sprintf("SELECT a.cfo_ctr_id FROM %s WHERE cfo_atime between %d and %d",$ftable,strtotime($temp[0]),strtotime($temp[1])+86399);
						$where .= sprintf(" AND ctr_id IN (%s)",$sql);
					}
					break;
				case 'level':
					if($val!==''){
						// $sql = sprintf("SELECT DISTINCT cca_ctr_id FROM crm_customer_admin WHERE cca_level_id=%d",$val);
						$where .=sprintf(" AND ctr_level_id = %d",$val);
					}
					break;
				case 'sales':
					$sql = sprintf("SELECT DISTINCT cca_ctr_id FROM crm_customer_admin WHERE cca_au_uid in (%s)",$val);
					$where .= sprintf(" and ctr_id in (%s)",$sql);
					break;
				case 'sve':
					//服务项目
					$sql = sprintf('select distinct fct_ctr_id from fad_link_fct_sve join fad_contract on fct_id = fsl_fct_id where fsl_sve_id = %d',$val);
					$where .= sprintf(" AND ctr_id in (%s)",$sql);
					break;
				case 'pro_count':
					$PjlBase = new PjlBase();
					$productRes = $PjlBase->get('pl_product', ['pro_shop_id'], " group by pro_shop_id having count(*)>0");
					$shopItemCount = array_column($productRes['data'], 'pro_shop_id');
					if($val==1){
						$where .= sprintf(" AND shop_vip_etime>%d AND shop_id in (%s)",time(),implode(',',$shopItemCount));
					}elseif ($val==2) {
						$where .= sprintf(" AND shop_vip_etime>%d AND shop_id>0 AND shop_id not in (%s)",time(),implode(',',$shopItemCount));
					}
					break;
				case 'kefu':
					$where .= sprintf(" AND ctr_kefu=%d",$val);
					break;
			}
		}
		$CrmBase = new CrmBase();
		$res = $CrmBase->get($table, ['count(distinct ctr_id) as count'], $where, true);
		$arr['count'] = $res['data']['count'];
		if($arr['count'] > 0)
		{
			if(!empty($Params['order']) && !empty($orderArr[$Params['order']][1]))
			{
				$order = $orderArr[$Params['order']][1];
			}
			$YpwBase = new YpwBase();
			$filed = ['ctr_id, ctr_uid,ctr_score, ctr_level_id,ctr_uname, ctr_comname, ctr_com_style, ctr_pct_ids, ctr_addr,ctr_contact,shop_id as ctr_pjl_shop_id, IFNULL(shop_vip_etime,0) as shop_vip_etime,IFNULL(shop_enter_time,0) as shop_enter_time,IFNULL(shop_apply_time,0) as shop_apply_time, ctr_tel,ctr_pjl_shop_entertime,ctr_pjl_shop_applytime,ctr_pjl_shop_etime,ua_pv,ua_vin_count,ua_number_count,ua_epc_count,shop_img,shop_tels,u_name,u_real_name'];
			if($Params['export'])
			{
				$where .= sprintf(" group by ctr_id %s", $order);
			}else{
				$where .= sprintf(" group by ctr_id %s limit %d, %d", $order, ($page-1)*$perPage, $perPage);
			}
			

			$res = $CrmBase->get($table, $filed, $where);
			$arr['data'] = array_column($res['data'], null, 'ctr_id');
			
			if(!empty($arr['data']))
			{
				$ctrIdArr = array_keys($arr['data']);
				$pjlShopIdArr = array_unique(array_filter(array_column($res['data'],'ctr_pjl_shop_id')));
				$uidArr = array_unique(array_filter(array_column($res['data'],'ctr_uid')));
				$userArr = [];
				if($uidArr){
					$res = $YpwBase->get('yp_user',['u_id','u_mobile'],sprintf(" and u_id in (%s)",implode(',',$uidArr)));
					$userArr = array_column($res['data'],'u_mobile','u_id');
				}
				//获取当前客户所标识的意向等级
				$table = 'crm_customer_rank join crm_label on cla_id = ccr_cla_id AND cla_type="rank"';
				$res = $CrmBase->get($table,['ccr_ctr_id,cla_name'],sprintf(" AND ccr_ctr_id IN (%s) AND ccr_au_uid=%d",implode(',',$ctrIdArr),$_SESSION['_userid']));
				$rankArr = $res['data']? array_column($res['data'],'cla_name','ccr_ctr_id'):[];
				//获取服务项目
				$table = 'fad_contract 
				join fad_link_fct_sve on fct_id=fsl_fct_id
				join fad_service on sve_id = fsl_sve_id';
				$sveres = $CrmBase->get($table,['fct_ctr_id,sve_id, sve_text'],sprintf(" AND fct_ctr_id IN (%s)",implode(',',$ctrIdArr)));
				$sveArr = [];
				if($sveres['data'])
				{
					foreach ($sveres['data'] as $key => $val) {
						$sveArr[$val['fct_ctr_id']][$val['sve_id']] = $val['sve_text'];
					}
				}
				//店铺
				if(!empty($pjlShopIdArr)){
					$PjlBase = new PjlBase();
					$plShopArr = $PjlBase->get('pl_shop left join pl_tuisong on stu_shop_id=shop_id ',['shop_id','stu_shop_id','shop_tsfw_vin_count','shop_quoted_count'],sprintf(" and shop_id in(%s)",implode(',',$pjlShopIdArr)));
					if(!empty($plShopArr['data'])){
						$plShopArr = array_column($plShopArr['data'],null,'shop_id');
					}
					$callRes = $PjlBase->get('pl_purchase_call', ['puca_by_uid, count(*) as count'], sprintf(" and puca_by_uid in (%s) group by puca_by_uid", implode(',', $pjlShopIdArr)));
					$callCount = array_column($callRes['data'], 'count', 'puca_by_uid');

					$productRes = $PjlBase->get('pl_product', ['pro_shop_id, count(*) as count'], sprintf(" and pro_shop_id in (%s) group by pro_shop_id", implode(',', $pjlShopIdArr)));
					$shopItemCount = array_column($productRes['data'], 'count', 'pro_shop_id');

					$field = ["tpsd_shop_id","sum(tpsd_pv_count) as pv_count"];
					$end = date('Ymd',time());
					$start = date('Ymd',strtotime("-3 month"));
					$list = (new BaseDb(mvc::$cfg['DB']['API_TJ']))->get('tj_pjl_shop_date',$field,sprintf(" and tpsd_shop_id in (%s) and tpsd_date between '%s' and '%s' group by tpsd_shop_id order by pv_count desc limit 200",implode(',', $pjlShopIdArr),$start,$end));
					$nowShow = [];
					if(!empty($list['data'])){
						$nowShow = array_column($list['data'],'pv_count','tpsd_shop_id');
					}
				}
				//获取计划
				$dayPlanArr = [];
				$planres = $CrmBase->get('crm_plan',['cp_ctr_id,cp_ok'],sprintf(" AND cp_date=%d AND cp_ctr_id in (%s)",date('Ymd'),implode(',', $ctrIdArr)));
				if($planres['data']){
					foreach ($planres['data'] as $key => $val) {
						$dayPlanArr[$val['cp_ctr_id']] = $val['cp_ok']?'Y':'N';
					}
				}
				$pctids = [];
				$noSeeArr = [];
				$res = $CrmBase->checkCtrUserRule($_SESSION['_userid'],$ctrIdArr);
				$noSeeArr = $res['data'];
				foreach($arr['data'] as $ctrid=>$v)
				{
					$v['cansee'] = 'Y';
					$v['cansee'] = in_array($ctrid, $noSeeArr) ? 'N': 'Y';	

					if(empty($v['ctr_tel']))
					{
						$v['ctr_tel'] = $userArr[$v['ctr_uid']]??'';
						if(!$v['ctr_tel'] && !empty($v['shop_tels']))
						{
							$telsArr = json_decode($v['shop_tels'],true);	
							$v['ctr_tel'] = $telsArr[0]['val'];
						}
					}
					if($v['cansee'] == 'N') $v['ctr_tel'] = substr_replace($v['ctr_tel'], '****', 3, 4);
					$v['au_name'] = '';
					$v['cca_level_id'] = 0;
					$v['cca_end_time'] = 0;
					$v['weixin_count'] = 0;
					$v['call_count'] = 0;
					$v['follow_count'] = 0;
					$v['lfollow'] = [];
					$v['part'] = [];
					$v['make'] = [];
					$v['self'] = [];
					$v['ctr_pct_ids'] = json_decode($v['ctr_pct_ids'], true);
					$v['day_plan'] = '';
					if(isset($dayPlanArr[$v['ctr_id']])){
						$v['day_plan'] =$dayPlanArr[$v['ctr_id']];
					} 
					$tids = [];
					if(!empty($v['ctr_pct_ids']['pid']))
					{
						$tids[] = (int) $v['ctr_pct_ids']['pid'];
						if(!empty($v['ctr_pct_ids']['cid']))
						{
							$tids[] = (int) $v['ctr_pct_ids']['cid'];
							if(!empty($v['ctr_pct_ids']['tid'])) $tids[] = (int) $v['ctr_pct_ids']['tid'];
						}
					}
					$v['pct_ids'] = $tids;
					$v['pcts'] = [];

					//关注零件
					$res = $YpwBase->get('yp_user_act_part', ['uap_part'], sprintf(" and uap_uid=%d order by uap_count desc limit 3", $v['ctr_uid']));
					$v['act_part'] = array_column($res['data'], 'uap_part');

					//关注品牌
					$per = empty($Params['brand_id'])? 3: 100;
					$res = $YpwBase->get('yp_user_act_brand', ['uab_brand'], sprintf(" and uab_uid=%d order by uab_count desc limit %d", $v['ctr_uid'], $per));
					$v['act_make'] = array_column($res['data'], 'uab_brand');

					$pctids = array_merge($pctids, $v['pct_ids']);
					//推送次数
					$v['tui_song'] = '未开通';
					if(isset($plShopArr[$v['ctr_pjl_shop_id']]) && $plShopArr[$v['ctr_pjl_shop_id']]['stu_shop_id'])
					{
						$v['tui_song'] = $plShopArr[$v['ctr_pjl_shop_id']]['shop_tsfw_vin_count'];
					}
					//最近
					$v['recent_pv_count'] = isset($nowShow[$v['ctr_pjl_shop_id']]) ? $nowShow[$v['ctr_pjl_shop_id']] : 0;
					//报价
					$v['shop_quoted_count'] = isset($plShopArr[$v['ctr_pjl_shop_id']])?$plShopArr[$v['ctr_pjl_shop_id']]['shop_quoted_count']:0;
					//电话次数
					$v['call_count'] = isset($callCount[$v['ctr_pjl_shop_id']])?$callCount[$v['ctr_pjl_shop_id']]:0;
					//配件数
					$v['product_count'] = isset($shopItemCount[$v['ctr_pjl_shop_id']])?$shopItemCount[$v['ctr_pjl_shop_id']]:0;
					//门头照
					$v['shop_img'] = $v['shop_img']?explode(',',$v['shop_img']):[];
					if($v['shop_img'])
					{
						foreach ($v['shop_img'] as &$imgItem) {
							$imgItem = mvc::$cfg['FILE_CENTER']['pjl']['url_get'].'&c=shop&f='.$imgItem.mvc::$cfg['FILE_CENTER']['pjl']['get_uri'];
						}	
						unset($imgItem);
					}
		
					if($v['cfo_atime'])
					{
						$v['lfollow'] = [
							'cfo_ctr_id'=>$v['cfo_ctr_id'],
							'cfo_au_name'=>$v['cfo_au_name'],
							'cfo_atime'=>$v['cfo_atime']
						];
					}
					//服务项目
					$v['sve_name'] =$sveArr[$ctrid]? implode(',',$sveArr[$ctrid]) :'';

					//意向标识
					$v['rank_name'] = $rankArr[$ctrid]??'';
					$arr['data'][$ctrid] = $v;
					
				}

				$CrmContract = new CrmContract();
				$res = $CrmContract->getAddrByIds(implode(',', array_unique($pctids)));
				$pctArr = $res['data'];
				foreach($arr['data'] as $k=>$v)
				{
					foreach($v['pct_ids'] as $pt)
					{
						if(empty($pctArr[$pt])) break;
						$v['pcts'][] = $pctArr[$pt];
					}
					$arr['data'][$k] = $v;
				}

				//获取所有业务员姓名
				$B2cBase = new B2cBase();
				$res = $B2cBase->get('an_user', ['au_uid', 'au_name']);
				$auArr = array_column($res['data'], 'au_name', 'au_uid');
				$lwhere = sprintf(" and cca_ctr_id in (%s) and cca_end_time >%d and cca_level_id > 0", implode(',', array_keys($arr['data'])), time());
				$res = $CrmBase->get('crm_customer_admin', ['cca_ctr_id, cca_au_uid, cca_level_id, cca_end_time'], $lwhere);
				foreach($res['data'] as $tv)
				{
					$arr['data'][$tv['cca_ctr_id']]['au_name'] = $auArr[$tv['cca_au_uid']];
					$arr['data'][$tv['cca_ctr_id']]['cca_level_id'] = $tv['cca_level_id'];
					$arr['data'][$tv['cca_ctr_id']]['cca_end_time'] = $tv['cca_end_time'];
				}
				// 获取是否分享客户
				$lwhere = sprintf(" and ccs_ctr_id in (%s)", implode(',', array_keys($arr['data'])));
				$res = $CrmBase->get('crm_customer_share', ['ccs_ctr_id, ccs_au_uid'], $lwhere);
				foreach($res['data'] as $tv)
				{
					$arr['data'][$tv['ccs_ctr_id']]['share_au'] = $tv['ccs_au_uid'];
				}

				//用户标签
				$lwhere = sprintf(" and cul_ctr_id in (%s) ORDER BY cul_ctr_id, cla_seq", implode(',', array_keys($arr['data'])));
				$res = $CrmBase->get('crm_customer_label JOIN crm_label ON cla_id = cul_cla_id', ['cul_ctr_id, cla_type, cla_id,cla_name'], $lwhere);
				foreach($res['data'] as $tv)
				{
					$arr['data'][$tv['cul_ctr_id']][$tv['cla_type']][] = ['cla_id'=>$tv['cla_id'], 'cla_name'=>$tv['cla_name']];
				}

				//跟进统计
				$lwhere = sprintf(" and cfo_ctr_id in (%s) GROUP BY cfo_ctr_id", implode(',', array_keys($arr['data'])));
				$filed = ["cfo_ctr_id as ctr_id, count(*) as follow_count, sum(case when cfo_type='call' then 1 else 0 end) as call_count, sum(case when cfo_type='weixin' then 1 else 0 end) as weixin_count"];
				$res = $CrmBase->get('crm_follow', $filed, $lwhere);
				foreach($res['data'] as $tv)
				{
					$arr['data'][$tv['ctr_id']] = array_merge($arr['data'][$tv['ctr_id']], $tv);
				}
				$ftable = sprintf("(SELECT cfo_ctr_id, MAX(cfo_id) AS lcfo_id FROM crm_follow where cfo_ctr_id in (%s) GROUP BY cfo_ctr_id) AS a JOIN crm_follow AS b ON a.lcfo_id = b.cfo_id AND a.cfo_ctr_id = b.cfo_ctr_id ", implode(',', array_keys($arr['data'])));
				$res = $CrmBase->get($ftable, ['b.cfo_ctr_id, b.cfo_au_name, b.cfo_atime'], '');
				foreach($res['data'] as $tv)
				{
					$arr['data'][$tv['cfo_ctr_id']]['lfollow'] = $tv;
				}

				$swhere = sprintf(" AND fct_ctr_id IN (%s) group by fct_ctr_id",implode(',', array_keys($arr['data'])));
				if(!in_array($_SESSION['_usergroup'],['all','kefu'])){
					$sql = 'select distinct fct_id from fad_contract 
					join fad_link_fct_usr on duc_fct_id = fct_id and duc_usr_id = 172999
					join fad_link_fct_sve on fsl_fct_id = fct_id and fsl_sve_id in (1,2)';
					$swhere = sprintf(" AND duc_usr_id=%d AND fct_ctr_id IN (%s) AND fct_id not in (%s)  group by fct_ctr_id",$_SESSION['_userid'],implode(',', array_keys($arr['data'])),$sql);
				}
				$table = 'fad_contract 
				join fad_link_fct_usr on duc_fct_id=fct_id';
				$res = $CrmBase->get($table,['count(fct_id) as counts,fct_ctr_id'],$swhere);
				LibTpl::Set('facArr',$res['data']?array_column($res['data'],'counts','fct_ctr_id'):[]);
			}
			$arr['data'] = array_values($arr['data']);
			//导出
			if($Params['export'])
			{	
				$aValues = [];
				foreach ($arr['data'] as $key => $val) 
				{	
					$contact = '';
					if($val['ctr_contact']){
						$contact .= $val['ctr_contact'];
					}
					if($val['ctr_uname']){
						if($val['ctr_contact']){
							$contact .= '-'.$val['ctr_uname'];
						}else{
							$contact .= $val['ctr_uname'];
						}
					}
					$time = '';
					if($val['cansee'])
					{	
						if($val['ctr_pjl_shop_id'] > 0 && $val['shop_vip_etime'] > time()){
							$time =  date('Y-m-d',$val['shop_vip_etime'])."到期 [".ceil(($val['shop_vip_etime']-time())/3600/24)."]";
						}else if($val['ctr_pjl_shop_id'] > 0 && $val['shop_vip_etime'] <= time() && $val['shop_vip_etime'] > 0) {
							$time =  date('Y-m-d',$val['shop_vip_etime'])."到期 [过".ceil((time()-$val['shop_vip_etime'])/3600/24)."]";
						}else if($val['ctr_pjl_shop_id'] > 0 && $val['shop_vip_etime'] == 0){
							$timer = (int) (time() - $val['shop_apply_time']);
							if((int)($timer / 86400) < 1){
								$tips =  '今天';
							}else{
								$tips = floor($timer / 86400).'天前';
							}
							$time =  date('Y-m-d',$val['shop_apply_time'])."申请 [".$tips."]";
						}else if($val['ctr_pjl_shop_id'] == 0 && $val['shop_vip_etime'] == 0){
							$time =  "";
						}
					} 
					$aValues[] = [
						$val['cansee']?implode('',$val['pcts']):'',
						$val['ctr_comname'],
						$val['au_name'],
						$val['sve_name'],
						$val['ctr_addr'],
						$contact,
						$val['ctr_tel'],
						$time,
						$val['ua_pv'],
						$val['ua_vin_count'],
						$val['ua_number_count'],
						$val['ua_epc_count']
					];
				}
				
				$OthExcel = new OthExcel();
				$aValues['fields'] = [
					'省市','公司名称','业务员','服务项目','地址','联系人','联系电话','到期/申请','浏览','VIN','号码','EPC'
				];
				$OthExcel->writer($aValues);exit;
			}
		}
		LibTpl::Set('pageMsg',LibPage::Show($arr['count'],$perPage,true));
		//业务员
		$res = $this->getSalesUser('',false,true);
		LibTpl::Set('ywyArr',$res['data']);
		//客服
		$res = $this->getKefu();	
		LibTpl::Set('kefuArr',$res['data']);
		return $arr['data'];
	}


	/**
	 * @method 新增合同
	 * @author zhengweihua 
	 * @copyright 2024-01-27
	 */
	public function addContract()
	{	

		if($_SERVER['REQUEST_METHOD']=='POST'){
			if(!empty($_POST['ctrId']) && !empty($_POST['Con'])  && !empty($_POST['Ser']))
			{	
				$CrmBase = new CrmBase();
				$res = $CrmBase->checkCtrUserRule($_SESSION['_userid'], [$_POST['ctrId']]);
				if(!empty($res['data']))  LibTpl::Error('此客户非你所属，您无权限查看！');
				$conArr = $_POST['Con'];
				$ConSerArr = $_POST['Ser'];
				$CrmFinance =new CrmFinance();
				$PayArr = $_POST['Pay']??[];
				$res = $CrmFinance->addOneContract($_POST['ctrId'], $conArr,$_POST['user']?:$_SESSION['_userid'], $ConSerArr,$PayArr);
				$conId = $res['data'];
	
				$CrmContract = new CrmContract();
				if($_POST['File'])
				{	
					foreach($_POST['File'] as $k=>$val)
					{
						$FileName = 'File_'.$k;
						if(isset($_FILES["$FileName"]['name']) && is_uploaded_file($_FILES["$FileName"]['tmp_name']))
						{
							$val['fcf_iscon'] = empty($val['fcf_iscon']) ? 0: 1;
							$val['name'] = $FileName;
							$CrmContract->uploadCont($val, $conId);
						}
					}
				}
				$CrmFinance->AutoSetConFileStatus($conId);
				LibTpl::Success('添加成功，该合同的ID为'.$conId,mvc::$cfg['SELF_URI'].'customer/contractSet?conId='.$conId);
				exit;
			}

		}
		$Params =  mvc::$URL_PARAMS;
		$CrmBase = new CrmBase();
		$ctr_id = (int)$Params['ctrId'];
		$res = $CrmBase->checkCtrUserRule($_SESSION['_userid'], [$ctr_id]);
		if(!empty($res['data']))  LibTpl::Error('此客户非你所属，您无权限查看！');
		$conTplList = [];
		$res =  $CrmBase->get('fad_contract_tpl',['*'],' order by fcf_seq asc');
		$conTplList = $res['data'];
		$table = sprintf('crm_customer 
		left join crm_customer_admin on ctr_id = cca_ctr_id and cca_end_time>%d and cca_level_id=5 ',time());
		$res = $CrmBase->get($table,['*'],sprintf("and ctr_id=%d",$ctr_id),true);
		$dataArr = $res['data'];
		$au_uid = $_SESSION['_userid'];
		if($dataArr['cca_au_uid']){
			$au_uid = $dataArr['cca_au_uid'];
		}

		// 同时获取分享业务员数据
		$lwhere = sprintf(" and ccs_ctr_id=%d",$ctr_id);
		$res = $CrmBase->get('crm_customer_share', ['ccs_au_uid'], $lwhere);
		$shareUid = $res['data'][0]['ccs_au_uid'];
		$searchUidStr = $shareUid ? sprintf("%s,%d",$shareUid,$au_uid) : $au_uid;
		$B2cBase = new B2cBase();
		$aures =  $B2cBase->get('an_user',['*'],sprintf(" and au_uid in (%s)",$searchUidStr));
		LibTpl::Set('auuserArr', $aures['data']);
		$auuser = [];
		foreach($aures['data'] as $item){
			if($item['au_uid'] == $au_uid){
				$auuser = $item;
			}
		}
		LibTpl::Set('auuser', $auuser);

		if($_SESSION['_usergroup']=='kefu'){
			$aures = $this->getSalesUser('',false);
			LibTpl::Set('salesArr', $aures['data']);
		}
		$this->HEAD_CSSJS['plugin'][] = 'ueditor';
		LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
		$res = $CrmBase->get('fad_service',['*']);
		LibTpl::Set('serviceList',$res['data']);
		LibTpl::Set('conTplList',$conTplList);
		LibTpl::Set('dataArr', $dataArr);
		LibTpl::Set('params', $Params);
		LibTpl::Set('title', '新增合同');
		LibTpl::Put();
	}

	/**
	 * @method 跟进记录
	 * @author zhengweihua 
	 * @copyright 2024-01-26
	 */
	public function follow()
	{
		$Params = mvc::$URL_PARAMS;
		$CrmBase = new CrmBase();
		//审核记录权限
		$hasRule = LibFc::checkDlRule('DL10',false);
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$order = 'order by  CASE cfo_check 
        WHEN 0 THEN 0
        ELSE 1 
    END,cfo_atime desc';

		$oWhere =  '';

		//上级可查看下级的所有跟进记录
		if($_SESSION['_usergroup']=='shangji'){
			$arr = $_SESSION['_xiajiUid'];
			if($arr){
				$where = sprintf(" and cfo_au_uid in (%s) ",implode(',',$arr));
				$oWhere = sprintf(" and au_uid in (%s) ",implode(',',$arr));
			}
		}elseif ($_SESSION['_usergroup']=='yewu') {
			$where = sprintf(" and cfo_au_uid=%d ",$_SESSION['_userid']);
		}
		if($_SESSION['_usergroup']=='all' && $_SESSION['_userid']==151295){
			$res = $this->getSalesUser('',true,true);
			$key = array_search('选择 [跑街业务员] 所有人', $res['data']['跑街业务员']);
			$Params['follow_name'] = $Params['follow_name']??$key;
		}else{
			$Params['follow_name'] = $Params['follow_name']??(string)$_SESSION['_userid'];
		}
		
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if( $v == '') continue;
            switch($k)
            {
				case 'keyword':
					$where .=sprintf(" AND ctr_comname like '%%%s%%'",$v);
					break;
				case 'pass':
					if($v<0) $v=0;
					$where .=sprintf(" AND cfo_pass=%d",$v);
					break;
              	case 'follow_name':
					$where .=sprintf(" AND cfo_au_uid IN (%s)",$v);
					break;
				case 'follow_time':
					$temp = explode('~',$v);
					if(count($temp)>1){
						$where .= sprintf(" AND  cfo_atime between %d and %d",strtotime($temp[0]),strtotime($temp[1])+86399);
					}
					break;
				case 'cfo_type':
					$where .=sprintf(" AND cfo_type='%s'",$v);
					break;
				case 'check':
					if($v==100) $v=0;
					$where .=sprintf(" AND cfo_check=%d",$v);
					break;
            }
        }
		$table = 'crm_follow 
		join crm_customer on cfo_ctr_id = ctr_id
		left join ypdb_write.yp_user on ctr_uid = u_id';
		$countres = $CrmBase->get($table,['count(*) as count'],$where,true);
		$count = $countres['data']['count'];
		$listArr = [];
		if ($count > 0)
		{
			$fields = ['crm_follow.*,ctr_id,ctr_comname,ctr_uname,ctr_contact,ctr_tel,ctr_level_id,u_name,u_real_name'];
			$res = $CrmBase->get($table, $fields,sprintf('%s %s limit %s, %s', $where,$order, ($page-1)*$perPage, $perPage));
			if(!empty($res['data']))
			{
				$listArr = $res['data'];

				//查意向信息
				$yixiangArr = [];
				$ctr_id = array_unique(array_column($listArr,'ctr_id'));
				$cfo_au_uid = array_unique(array_column($listArr,'cfo_au_uid'));
				if($ctr_id && $cfo_au_uid)
				{
					$table = "crm_customer_rank join crm_label on cla_id=ccr_cla_id AND cla_type='rank'";
					$res = $CrmBase->get($table,['*'],sprintf(" AND ccr_ctr_id IN (%s) AND ccr_au_uid IN (%s)",implode(',',$ctr_id),implode(',',$cfo_au_uid)));
					foreach ($res['data'] as $key => $val) {
						$yixiangArr[$val['ccr_ctr_id']][$val['ccr_au_uid']] = $val['cla_name'];
					}
				}
			}
		}
		$res = $this->getSalesUser($oWhere,true,true);
		$salesArr =$res['data'];
		//统计当前用户当前时间跑街有效跟进记录
		if($Params['follow_time']){
			$temp = explode('~',$Params['follow_time']);
			$start = strtotime($temp[0]);
			$end = strtotime($temp[1])+86399;
		}else{
			$start = strtotime(date('Y-m-d'));
			$end = $start+86399;
		}
		$chkUser = $Params['follow_name']?:$_SESSION['_userid'];
		if($chkUser)
		{
			$where = sprintf(" AND cfo_check!=-1 AND cfo_pass=1 AND cfo_au_uid in (%s) AND cfo_atime>=%d AND cfo_atime<=%d",$chkUser,$start,$end);
			$cntres = $CrmBase->get('crm_follow',['count(DISTINCT cfo_au_uid,cfo_ctr_id,FROM_UNIXTIME(cfo_atime, \'%y%m%d\')) as counts'],$where,true);
			$chkUsername = '';
			if($Params['follow_name']){
				foreach ($salesArr as $val) {
					if($val[$Params['follow_name']]){
						$chkUsername = $val[$Params['follow_name']];
						break;
					}
				}
			}
			//统计当前用户当前时间宜配有效跟进记录
			$B2cBase = new B2cBase();
			$res = $B2cBase->get('an_user',['au_uid,au_name'],sprintf(" AND au_uid IN (%s)",$chkUser));
			$unameArr = array_column($res['data'],'au_name');
			$uname = implode("','",$unameArr);
			$CrmsBase = new BaseDb(mvc::$cfg['DB']['CRMS']);
			$where = sprintf(" AND afw_ischeck=1 AND afw_pass=1 AND afw_usr IN ('%s') AND afw_modified>=%d AND afw_modified<=%d",$uname,$start,$end);
			$res = $CrmsBase->get('crm_follow',["count(DISTINCT afw_ctr_id,FROM_UNIXTIME(afw_modified,'%y%m%d')) as counts"],$where,true);
			$todayYpFollow = $res['data']['counts'];

			//有效意向跟进
			$where = sprintf(" AND cfo_yxcheck=1 AND cfo_au_uid in (%s) AND cfo_atime>=%d AND cfo_atime<=%d",$chkUser,$start,$end);
			$yxcntres = $CrmBase->get('crm_follow',['count(DISTINCT cfo_au_uid,cfo_ctr_id,FROM_UNIXTIME(cfo_atime, \'%y%m%d\')) as counts'],$where,true);
			$todayYxFollow = $yxcntres['data']['counts'];
		}
		LibTpl::Set('yixiangArr',$yixiangArr??[]);
		LibTpl::Set('chkUsername',$chkUsername);
		LibTpl::Set('todayFollow',$cntres['data']?$cntres['data']['counts']:0);
		LibTpl::Set('todayYpFollow',$todayYpFollow);
		LibTpl::Set('todayYxFollow',$todayYxFollow);
		LibTpl::Set('Params',$Params);	
		LibTpl::Set('hasRule',$hasRule??0);
		LibTpl::Set('salesArr',$salesArr);
		LibTpl::Set('cfoTypeArr',['qq'=>'QQ','call'=>'电话','weixin'=>'微信','other'=>'其他']);
		LibTpl::Set('pageMsg', LibPage::Show($count, $perPage, true));
		LibTpl::Set('listArr', $listArr);
		LibTpl::Set('title', '我的客户');
		LibTpl::Put();	
	}

	/**
	 * @method 添加跟进记录
	 * @author zhengweihua 
	 * @copyright 2024-01-27
	 */
	public function addFollow()
	{	
		if(empty($_POST['ctr_id'])) LibFc::ReturnJson(false, '客户ID不存在');

		$CrmBase = new CrmBase();
		$res = $CrmBase->checkCtrUserRule($_SESSION['_userid'], [$_POST['ctr_id']]);
		if(!empty($res['data']))  LibFc::ReturnJson(false, '此客户非你所属，您无权限查看！');

		$dataArr=  $_POST;
		$dataArr['cfo_au_uid'] = $_SESSION['_userid'];
		$dataArr['cfo_au_name'] = $_SESSION['_username'];
		$CrmContract = new CrmContract();
		$res  = $CrmContract->addFollow($dataArr,$_SESSION['_usergroup']);
		
		LibFc::ajaxJsonEncode($res);
	}

	/**
	 * @method 删除跟进记录
	 * @author zhengweihua 
	 * @copyright 2024-03-25
	 */
	public function delFollow()
	{
		if($_SERVER['REQUEST_METHOD']=='POST' && $_POST)
		{
			$cfoId = (int)$_POST['cfoId'];
			$CrmBase = new CrmBase();
			$res = $CrmBase->del('crm_follow',sprintf(" AND cfo_id=%d",$cfoId));
			LibFc::ajaxJsonEncode($res);
		}
	}

	/**
	 * @method 获取跟进记录
	 * @author zhengweihua 
	 * @copyright 2024-01-30
	 */
	public function getFollowList()
	{	
		//如果是客服 

		$arr = ['total'=>0, 'data'=>[]];
		$Params = mvc::$URL_PARAMS;
		$Params['page'] = empty($Params['page']) || $Params['page'] < 1? 1: (int) $Params['page'];
		$Params['per'] = empty($Params['per']) || $Params['per'] < 1 ? 20: (int) $Params['per'];
		$where = '';
	
		$CrmBase = new CrmBase();
		if(!empty($Params['ctr_id']))
		{
			//此客户现在有业务员，只能看自己的跟进记录
			$res = $CrmBase->get('crm_customer_admin', ['cca_au_uid'], sprintf(" and cca_ctr_id=%d and cca_end_time >%d and cca_au_uid !=%d", $Params['ctr_id'], time(), $_SESSION['_userid']));
			if(!empty($res['data'])) $Params['onlyme'] = 1;
			$where .= sprintf(" and cfo_ctr_id = %d", $Params['ctr_id']);
		}
		if(!empty($Params['onlyme']))
		{	
			if($_SESSION['_usergroup']=='yewu'){
				$where .= sprintf(" and cfo_au_uid = %d", $_SESSION['_userid']);
			}elseif ($_SESSION['_usergroup']=='shangji') {
				$where .= sprintf(" and cfo_au_uid in (%s)", implode(',',$_SESSION['_xiajiUid']));
			}
		}
		$table = 'crm_follow join crm_customer on ctr_id = cfo_ctr_id';
		$res = $CrmBase->get($table, ['count(*) as count'], $where, true);
		$total = $res['data']['count'];
		$listArr = [];
		if($total > 0)
		{
			$where .= sprintf(" order by cfo_id desc limit %d, %d", ($Params['page']-1)*$Params['per'], $Params['per']);
			$res = $CrmBase->get($table, ['ctr_id, ctr_uname, ctr_comname, ctr_contact, ctr_tel, cfo_id, cfo_txt, cfo_au_name, cfo_au_uid, cfo_au_name, cfo_atime'], $where);
			
			$listArr = $res['data'];
		}	
		LibFc::ReturnJson(true,$listArr);
	}


	/**
	 * @method 审核跟进记录
	 * @author zhengweihua 
	 * @copyright 2024-01-26
	 */
	public function auditFollow()
	{
		LibFc::checkDlRule('DL10');
		if($_SERVER['REQUEST_METHOD']=='POST'){
			$CrmBase = new CrmBase();
			$dataArr = [
				'cfo_check'=>(int)$_POST['cfo_check'],
				'cfo_checktime'=>time(),
			];
			$where = '';
			if($_POST['cfo_ids']){
				$where = " and cfo_id in (".$_POST['cfo_ids'].")";
			}
			$res = $CrmBase->set('crm_follow',$dataArr,$where);
			LibFc::ajaxJsonEncode($res);
		}
	}


	/**
	 * @method 成交项目
	 * @author zhengweihua 
	 * @copyright 2024-01-26
	 */
	public function myself()
	{
		$Params =  mvc::$URL_PARAMS;	
		
		$dataArr = [];
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$where = '';

		$searchUser = [];
		if ($_SESSION['_usergroup'] == 'shangji') {
			$searchUser = $_SESSION['_xiajiUid'];
		} elseif ($_SESSION['_usergroup'] == 'yewu') {
			$searchUser[] =  $_SESSION['_userid'];
		}
		if(!in_array($_SESSION['_usergroup'],['all','kefu'])){
			$table = sprintf('fad_link_fct_sve
			JOIN fad_service ON sve_id = fsl_sve_id
			JOIN fad_contract ON fct_id = fsl_fct_id
			JOIN fad_link_fct_usr ON fct_id = duc_fct_id and duc_usr_id in (%s)
			LEFT JOIN crm_customer ON fct_ctr_id = ctr_id',implode(',',$searchUser));
		}else{
			$table = 'fad_link_fct_sve
			JOIN fad_service ON sve_id = fsl_sve_id
			JOIN fad_contract ON fct_id = fsl_fct_id
			JOIN fad_link_fct_usr ON fct_id = duc_fct_id
			LEFT JOIN crm_customer ON fct_ctr_id = ctr_id';
		}

		$order = 'order by fsl_etime asc';
		foreach ($Params as $key => $val) {
			if(empty($val)) continue;
			switch($key)
			{
				case 'word':
					$val = LibFc::Escape($val);
					$where .= sprintf(" and ctr_uname like '%%%s%%' or ctr_comname like '%%%s%%' ",$val,$val,$val);
					break;
				case 'sveId':
					$where .= sprintf(" and fsl_sve_id = %d",$val);
					break;
				case 'tftime':
					$arr = explode('~',$val);
					if($arr){
						$where  .= sprintf(" and fsl_etime>=%d and fsl_etime<%d",strtotime($arr[0]),strtotime($arr[1])+86400);
					}
					break;
				
			}
		}

		$CrmBase = new CrmBase();
		
		$res =  $CrmBase->get($table,['count(*) as counts'],$where,true);
		$total = $res['data']['counts'];
		if($total>0){
			$fields = ['fad_link_fct_sve.*,fct_id,fct_modified,sve_text,ctr_id,ctr_comname,ctr_uname'];
			$res = $CrmBase->get($table,$fields,sprintf(" %s %s limit %d,%d",$where,$order, ($page-1)*$perPage, $perPage));
			
			$dataArr = $res['data'];
		}
		$CrmBase = new CrmBase();
		$res = $CrmBase->get('fad_service',['*'],'');
		LibTpl::Set('sveList',$res['data']);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
		LibTpl::Set('dataArr', $dataArr);
		LibTpl::Set('title', '我的客户');
		LibTpl::Put();	
	}


	/**
	 * @method 合同管理
	 * @author zhengweihua 
	 * @copyright 2024-01-26
	 */
	public function contract()
	{
		$Params =  mvc::$URL_PARAMS;	
		$hasRule = LibFc::checkDlRule('DL09',false);
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$where = '';
		$serTimeWhere = '';
		$oWhere = '';
		$searchUser = [];
		if(!$hasRule){
			if($_SESSION['_usergroup'] == 'shangji') {
				$searchUser = $_SESSION['_xiajiUid'];
			} elseif ($_SESSION['_usergroup'] == 'yewu') {
				$searchUser[] =  $_SESSION['_userid'];
				// $where .= sprintf(" AND duc_usr_id =%d", $_SESSION['_userid']);
			}
			if($searchUser){
				$CrmFinance = new CrmFinance();
				$res = $CrmFinance->getFinance(array('DISTINCT fae_fct_id'),  sprintf(' AND fae_create_usr_id in (%s) ',implode(',',$searchUser)));
				if(!empty($res['data']))
				{
					$temp = array_column($res['data'],'fae_fct_id');
					$where .= sprintf(" AND (fct_id IN (%s) OR duc_usr_id in (%s))",implode(',', $temp), implode(',',$searchUser));
				}else{
					$where .=sprintf(" AND duc_usr_id in (%s)",implode(',',$searchUser));
				}
	
				$oWhere = sprintf(" AND au_uid in (%s)",implode(',',$searchUser));
				
			}
			//业务员不可看 跑街令的商家入驻、PC会员合同
			$sql = 'select distinct fct_id from fad_contract 
			join fad_link_fct_usr on duc_fct_id = fct_id and duc_usr_id = 172999
			join fad_link_fct_sve on fsl_fct_id = fct_id and fsl_sve_id in (1,2)';
			if(!in_array($_SESSION['_usergroup'],['kefu','all'])){
				$where .= sprintf(" AND fct_id not in (%s)",$sql);
			}	
		}
		
		LibTpl::Set('hasRule',$hasRule);
		foreach($Params as $key=>$val)
		{
			if(empty($val)) continue;
			switch($key)
			{
				case 'status':
					$val = (int) $val;
					$where .= $val > -2 ? ' AND fct_status = '.$val : '';
					break;
				case 'isCon':
					$val = (int) $val;
					$where .= $val > -1 ? ' AND fct_has_con_file = '.$val : '';
					break;
				case 'ctime':
					if($val){
						$timeArr =explode(' ~ ',$val);
						$where .=sprintf(" AND  fct_modified >= %d AND fct_modified <=%d ",strtotime($timeArr[0]),strtotime($timeArr[1])+24*3600-1);
					}
					
					break;
				case 'ctrId':
					$where .= $val > 0 ? ' AND fct_ctr_id = '.$val : '';
					break;
				case 'keyword':
					$where .=sprintf(" and (ctr_comname like '%%%s%%' or fct_title like '%%%s%%')",$val,$val);
					break;
				case 'sveId':
						if($val>0){
							$sql = sprintf("select DISTINCT fsl_fct_id from fad_link_fct_sve where fsl_sve_id=%d",$val);
							$where .= sprintf(" AND fct_id in (%s)",$sql);
							$serTimeWhere .= sprintf(' AND fsl_sve_id = %d',$val);
						}	
					
					break;
				case 'stime':
					if($val){
						$timeArr = explode('~',$val);
						$sql = sprintf("select DISTINCT fsl_fct_id from fad_link_fct_sve where fsl_etime>=%d AND fsl_etime <=%d",strtotime($timeArr[0]),strtotime($timeArr[1])+24*3600-1);
						$where .= sprintf(" AND fct_id in (%s)",$sql);
						$serTimeWhere .= sprintf(' AND fsl_etime>=%d AND fsl_etime <=%d',strtotime($timeArr[0]),strtotime($timeArr[1])+24*3600-1);
					}
					break;
				case 'usr_id':
					$where .= sprintf(" AND duc_usr_id in (%s)",$val);	
					break;
				
			}
		}

		$CrmBase = new CrmBase();
		$CrmFinance = new CrmFinance();
		$table = "fad_contract AS a
		JOIN fad_link_fct_usr AS b ON a.fct_id=b.duc_fct_id
		JOIN crm_customer AS d ON d.ctr_id=a.fct_ctr_id";
		$res = $CrmBase->get($table,['count(*) as count'],$where,true);
		$conArr = [];
		if($res['data']['count']>0){
			$count = $res['data']['count'];
			$res = $CrmBase->get($table,['*'],sprintf('%s  ORDER BY fct_status ASC,fct_modified DESC  LIMIT %d, %d',$where,($page-1)*$perPage,$perPage));
			$conArr = $res['data'];
			if($conArr){
				$ctrIdArr = [];
				foreach($conArr as $k=> &$v)
				{
					$ctrIdArr[$v['fct_ctr_id']] = $v['fct_ctr_id'];
					//合同是否完成付款
					$table = 'fad_link_pay as a
					JOIN fad_contract as b ON a.fff_fct_id=b.fct_id
					JOIN fad_finance as c ON c.fae_id=a.fff_fae_id';
					$res = $CrmBase->get($table,['sum(fff_pay_money) as has_pay'],' AND fff_fct_id='.$v['fct_id']);
					
					$v['has_pay'] = (int) $res['data'][0]['has_pay'];
					$v['need_pay'] = $v['fct_money'] - $v['has_pay'];

					//支付计划完成率
					$table1 = 'fad_pay_money AS a 
					JOIN fad_contract AS b ON a.pay_fct_id = b.fct_id';

					//未完成的最近支付计划
					$res = $CrmBase->get($table1,['pay_id', 'pay_pay_time', 'pay_money'],' AND pay_fct_id='.$v['fct_id'].' AND pay_status < 1 ORDER BY pay_pay_time',true);
					$v['now_pay_plan'] = $res['data'];
					if(!empty($v['now_pay_plan']['pay_id']))
					{	
						$res = $CrmBase->get($table,['sum(fff_pay_money) as has_pay'],' AND fff_pay_id='.$v['now_pay_plan']['pay_id']);
						$v['now_pay_plan']['need_pay'] = $v['now_pay_plan']['pay_money'] - $res['data'][0]['has_pay'];
					}

					$res = $CrmBase->get($table1,array('count(*) as count'), ' AND pay_fct_id='.$v['fct_id'], true);
					$v['pay_plan_count'] = (int) $res['data']['count'];
					$res = $CrmBase->get($table1,array('count(*) as count'), ' AND pay_fct_id='.$v['fct_id'].' AND pay_status = 1', true);
					$v['pay_plan_count_ok'] = (int) $res['data']['count'];

					
					$v['btime'] = 0;
					$v['etime'] = -1;
					//服务期
					$res = $CrmFinance->getConSer(array('sve_text','fsl_id', 'fsl_des_id','fsl_money', 'fsl_btime', 'fsl_etime'), sprintf(' %s AND fsl_fct_id='.$v['fct_id'],$serTimeWhere));
					foreach($res['data'] as $vv)
					{
						$v['con_ser'][] = $vv;
						$v['btime'] = empty($v['btime']) || $vv['fsl_btime'] < $v['btime'] ? $vv['fsl_btime']: $v['btime'];
						$v['etime'] = ($vv['fsl_etime'] > $v['etime'] && $v['etime'] != 0) || $vv['fsl_etime'] == 0 ? $vv['fsl_etime']: $v['etime'];
					}
					
				}
				unset($v);
			}
		}
		$B2cBase = new B2cBase();
		$aures =  $B2cBase->get('an_user',['au_uid,au_name']);
		LibTpl::Set('salesArr',array_column($aures['data'],'au_name','au_uid'));
		$res = $this->getSalesUser($oWhere,true,true);
		LibTpl::Set('salesUser',$res['data']);
		$conStatusArr = array(-1=>'无效',0=>'等待审核', 1=>'付款中', 2=>'付款完成');
		LibTpl::Set('conStatusArr',$conStatusArr);

		//合同附件
		$conFileArr = array(1=>'有', 0=>'无');
		LibTpl::Set('conFileArr',$conFileArr);
		$CrmBase = new CrmBase();
		$res = $CrmBase->get('fad_service',['*'],'');
		LibTpl::Set('sveList',$res['data']);
		$pageMsg = LibPage::show($count,$perPage,true);
		LibTpl::Set('pageMsg', $pageMsg);
		LibTpl::Set('conArr', $conArr);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('title', '合同管理');
		LibTpl::Put();
	}
	/**
	 * @method 合同模板
	 * @author zhengweihua 
	 * @copyright 2024-01-26
	 */
	public function contractTpl()
	{
		$Params =  mvc::$URL_PARAMS;
		if ($_SERVER['REQUEST_METHOD']=='POST') {
			$CrmContract  = new CrmContract();

			$where = !empty($_POST['File']) ? sprintf(" AND fcf_id NOT IN (%s)", implode(',', array_keys($_POST['File']))): ' and 1=1';
			$CrmContract->delCon([],$where);
			foreach ($_POST['File'] as $k => $v) {
				$FileName = 'File_' . $k;
				if (isset($_FILES["$FileName"]['name']) && is_uploaded_file($_FILES["$FileName"]['tmp_name'])) { 
					//删除、添加
					if ($k > 0) {
						$CrmContract->delCon([$k]);
					}
					$v['name'] = $FileName;
					$res = $CrmContract->uploadCont($v);
					if(!$res['status']){
						LibTpl::Error('出错了！');
					}
				} else if ($k > 0) { //update
					$CrmContract->set('fad_contract_tpl',$v,sprintf(" AND fcf_id=%d",$k));
				}
			}
			LibTpl::Success('保存成功');
		}
		$dataArr = [];

		$CrmContract = new CrmContract();
		$res = $CrmContract->get('fad_contract_tpl',['*'],' order by fcf_seq asc');
		$dataArr = $res['data'];
		LibTpl::Set('dataArr', $dataArr);
		LibTpl::Set('title', '合同模板');
		LibTpl::Put();
	}

	/**
	 * @method 合同编辑
	 * @author zhengweihua 
	 * @copyright 2024-01-30
	 */
	public function contractSet()
	{
		$Params =  mvc::$URL_PARAMS;
		$conId = (int) $Params['conId']?:($_POST['conId']?:0);
		if ($conId < 1) {
			LibTpl::Error('获取合同ID数据失败！');
			exit;
		}
		$hasRule = LibFc::checkDlRule('DL09',false);
		LibTpl::Set('hasRule',$hasRule);
		$CrmBase = new CrmBase();
		$table = 'fad_contract 
		JOIN fad_link_fct_usr ON fct_id=duc_fct_id
		JOIN crm_customer ON ctr_id=fct_ctr_id ';
		$res = $CrmBase->get($table,['*'],sprintf(" and fct_id=%d",$conId),true);
		if(empty($res['data'])){
			LibTpl::Error('合同不存在！');
			exit;
		}
		$conArr = $res['data'];

		$res = $CrmBase->checkCtrUserRule($_SESSION['_userid'], [$conArr['ctr_id']]);
		if(!empty($res['data']))  LibTpl::Error('此客户非你所属，您无权限查看！');

		if($_SERVER['REQUEST_METHOD']=='POST' && $_POST){
			$CrmFinance = new CrmFinance();

			$CrmFinance->setOneContract($conId, $_POST['Con'], $_POST['Ser'],$_POST['user']);
			
			//附件
			$where = !empty($_POST['File']) ? sprintf(" AND fcf_fct_id =%d AND fcf_id NOT IN (%s)", $conId, implode(',', array_keys($_POST['File']) ) ): sprintf(" AND fcf_fct_id =%d", $conId);
			$CrmContract = new CrmContract();
			$CrmContract->delCon([],$where,2);

			if($_POST['File']){
				foreach($_POST['File'] as $k=>$v)
				{
					$v['fcf_iscon'] = empty($v['fcf_iscon']) ? 0: 1;
					$FileName = 'File_'.$k;
					if(isset($_FILES["$FileName"]['name']) && is_uploaded_file($_FILES["$FileName"]['tmp_name']))
					{//删除、添加
						if($k > 0)
						{
							$CrmContract->delCon([],' AND fcf_id='.$k);
						}
						$v['name'] = $FileName;
						$aQuery = $CrmContract->uploadCont($v, $conId);
					}
					else if ($k > 0)
					{//update
						$CrmContract->set('fad_contract_file',$v,' AND fcf_id='.$k);
					}
				}
			}
			$CrmFinance->autoSetConFileStatus($conId);
			
			LibTpl::Success('成功');
			exit;

		}

		$B2cBase = new B2cBase();
		$res = $B2cBase->get('an_user',['au_uid,au_name'],sprintf("and au_uid=%d",$conArr['duc_usr_id']),true);
		$conArr['au_name'] = $res['data']['au_name'];
		$conArr['au_uid'] = $res['data']['au_uid'];
		//已支付
		$table = 'fad_link_pay
		JOIN fad_contract ON fff_fct_id=fct_id
		JOIN fad_finance ON fae_id=fff_fae_id';
		$res =$CrmBase->get($table,['fff_pay_id', 'fff_pay_money', 'fff_pay_time', 'fae_proof'],sprintf(' AND fff_fct_id=%d ORDER BY fff_pay_time DESC',$conId));
		$conArr['pay_money'] = 0;
		$PayPlanMoneyArr = [];
		foreach ($res['data'] as $key => $val) {
			$HasPayArr[] = $val;
			if(empty($PayPlanMoneyArr[$val['fff_pay_id']]))
			{
				$PayPlanMoneyArr[$val['fff_pay_id']] = $val['fff_pay_money'];
			}
			else
			{
				$PayPlanMoneyArr[$val['fff_pay_id']] += $val['fff_pay_money'];
			}
			$conArr['pay_money'] += $val['fff_pay_money'];
		}


		//支付计划
		$table = 'fad_pay_money AS a 
		JOIN fad_contract AS b ON a.pay_fct_id = b.fct_id';
		$res = $CrmBase->get($table,array('pay_id', 'pay_status', 'pay_pay_time', 'pay_remark', 'pay_money'), ' AND pay_fct_id = '.$conId);
		$conArr['pay_plan'] = array();
		$conArr['pay_plan_end_count'] = 0;
		foreach($res['data'] as $val)
		{
			$val['pay_pay_time'] = date('Y-m-d', $val['pay_pay_time']);
			$val['has_pay'] = $PayPlanMoneyArr[$val['pay_id']];
			$conArr['pay_plan'][] = $val;
			if($val['pay_money'] == $PayPlanMoneyArr[$val['pay_id']])
			{
				$conArr['pay_plan_end_count']++;
			}
		}


		if($_SESSION['_usergroup']=='kefu'||$_SESSION['_usergroup']=='all'){
			$aures = $this->getSalesUser('',false);
			LibTpl::Set('salesArr', $aures['data']);
		}

		//等待审核付款记录
		$CrmFinance = new CrmFinance();
		$Res = $CrmFinance->getFinance(array('DISTINCT fae_id', 'fae_status', 'fae_text', 'fae_money', 'fae_spare_money', 'fae_create_time', 'fae_proof', 'fae_create_usr','au_name'), ' AND fae_fct_id='.$conId.' ORDER BY fae_create_time DESC');
		$ChkMoneyArr = $Res['data'];
		LibTpl::Set('ChkMoneyArr', $ChkMoneyArr);
		//合同模板
		$CrmBase = new CrmBase();
		$res = $CrmBase->get('fad_contract_tpl', ['*'],'order by fcf_seq asc');
		LibTpl::Set('ConTplArr',$res['data']);
		$res = $CrmBase->get('fad_contract_file', ['*'], sprintf(" AND fcf_fct_id = %d  ORDER BY fcf_seq", $conId));
		LibTpl::Set('ConFileArr',$res['data']);
		$ConStatusArr = array(-1=>'无效',0=>'等待审核', 1=>'付款中', 2=>'付款完成');
		LibTpl::Set('ConStatusArr', $ConStatusArr);
		$statusArr = [-1=>'无效',0=>'待审核',1=>'已审核', 2=>'付款完成'];
		LibTpl::Set('statusArr',$statusArr);
		$res = $CrmBase->get('fad_service',['*']);
		LibTpl::Set('serviceList',$res['data']);
		$this->HEAD_CSSJS['plugin'][] = 'ueditor';
		LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
		LibTpl::Set('ConArr',$conArr);
		LibTpl::Set('title', '合同编辑-'.$conArr['fct_title']);
		LibTpl::Put();
	}

	/**
	 * @method 删除合同
	 * @author zhengweihua 
	 * @copyright 2024-04-27
	 */
	public function delContract()
	{	
		if($_SERVER['REQUEST_METHOD']=='POST'&&$_POST['conId']){
			$CrmFinance = new CrmFinance();
			$res = $CrmFinance->getContract(['ctr_id'],sprintf(" AND fct_id =%d", $_POST['conId']),true);
			$conArr = $res['data'];

			$res = $CrmFinance->delContract($_POST['conId']);
			if($res['status'])
			{
				//变更客户状态
				$LibYpApi = new LibYpApi();
				$getArr = ['ctr_id'=>$conArr['ctr_id']];
				$LibYpApi->Get('crm/initCtrStatus', $getArr, []);
			}
			LibFc::ajaxJsonEncode($res);
		}
		
	}


	/**
	 * @method 	获取服务项目
	 * @author zhengweihua 
	 * @copyright 2024-01-29
	 */
	public function getConSer()
	{
		$Params = mvc::$URL_PARAMS;
		$arr = [];
		$copy = (int) $Params['copy'];
		$conId = (int) $Params['conId'];
		if($conId > 0)
		{
			$CrmFinance = new CrmFinance();
			$res = $CrmFinance->GetConSer(array('*'), ' AND fsl_fct_id='.$conId);
			$serArr = $res['data'];
			$adsArr = [];
			foreach($serArr as $v)
			{
				$v['fsl_id'] =  $copy == 1 ? 0: $v['fsl_id'];
				$v['fsl_btime'] = $copy == 1 ?'': date('Y-m-d', $v['fsl_btime']);
				$v['fsl_etime'] = $copy == 1 ?'': date('Y-m-d', $v['fsl_etime']);
				if($v['fsl_sve_id'] == 7 && $v['fsl_des_id'] > 0)
				{
					$adsArr[] = $v['fsl_des_id'];
				}
				$arr[] = $v;
			}
			if($adsArr){

				$AdsBase = new AdsBase();
				$ypcBase = new YpcBase();
				$res = $ypcBase->get('yp_brand', ['b_id,b_name'], ' order by b_initial');
				$brand = array_column($res['data'], 'b_name', 'b_id');

				$res =$AdsBase->Get('yp_province_city', ['pc_id as id','pc_name as name'], '');
				$pcArr = array_column($res['data'], 'name', 'id');

				$AdsPla = new AdsPla();
				$table = 'pj_place_ads 
				join pj_place on pa_id=pla_pa_id 
				JOIN pj_user_ads ON pla_ads_id = ads_id
				JOIN pj_place_ads_time ON pat_pla_id = pla_id';
				$res = $AdsPla->get($table,['pla_id,pa_name,ads_title,ads_name,pj_place_ads_time.*'], sprintf(" and pla_id in (%s)", implode(',',$adsArr)));

				if($res['data']){
					$makeIds = array_column($res['data'],'pat_make_id');
					$ComBase = new ComBase();
					$makeres = $ComBase->get('bc_make',['make_id','make_name'],sprintf(" AND make_id in (%s)", implode(',',$makeIds)));
					$makeArr = array_column($makeres['data'],'make_name','make_id');
				}
	
				foreach ($res['data'] as $key => $val) {
					$adsArr[$val['pla_id']]['name'][$key] = $val['pa_name'];
					
					if($val['pat_keyword']){
						
						if($val['pat_make_id'] && $makeArr){
							$adsArr[$val['pla_id']]['name'][$key] .='-'. $makeArr[$val['pat_make_id']];
						}else{
							$adsArr[$val['pla_id']]['name'][$key] .='-'. $brand[$val['pat_keyword']];
						}
						if($val['pat_modpc'] && $val['pat_modcv']){
							$temp = '[乘|商]';
						}elseif ($val['pat_modpc']) {
							$temp = '乘用车';
						}elseif ($val['pat_modcv']) {
							$temp = '商用车';
						}
						$adsArr[$val['pla_id']]['name'][$key] .='-'.$temp;
					}elseif ($val['pat_pc_id']) {
						$adsArr[$val['pla_id']]['name'][$key] .='-'. ($val['pat_pc_id']? $pcArr[$val['pat_pc_id']]:'全球');
					}
					
					$adsArr[$val['pla_id']]['name'][$key] .='-'. ($val['ads_name']?:$val['ads_title']);
					$adsArr[$val['pla_id']]['time']= [date('Y-m-d',$val['pat_btime']) ,date('Y-m-d',$val['pat_etime'])];

				}
			}
			foreach ($arr as $key => &$val) {
				if($val['fsl_des_id'] && $adsArr[$val['fsl_des_id']]){
					$val['serDes'] = $adsArr[$val['fsl_des_id']]['name']?array_values($adsArr[$val['fsl_des_id']]['name']):'';
					$val['serDesTime'] = $copy == 1 ?'': ($adsArr[$val['fsl_des_id']]['time']?'广告时间：'.implode('至',$adsArr[$val['fsl_des_id']]['time']):'');
				}
			}
			unset($val);
		}
		echo json_encode($arr);
	}

	/**
	 * @method 添加付款计划
	 * @author zhengweihua 
	 * @copyright 2024-01-30
	 */
	public function applyPayAdd()
	{
		$Params = mvc::$URL_PARAMS;
		

		if($_SERVER['REQUEST_METHOD']=='POST' && $_POST)
		{
			$ctrId = !empty($_POST['ctrId']) ? LibFc::Int($_POST['ctrId']): 0;
			$conId = !empty($_POST['conId']) ? LibFc::Int($_POST['conId']): 0;
			if($ctrId > 0 && $conId > 0 && !empty($_POST['Pay']['fae_text']))
			{	
				
				$PayDataArr = $_POST['Pay'];
	
				$PayDataArr['fae_create_usr'] = $_SESSION['_username'];
				$PayDataArr['fae_create_time'] = time();
				$PayDataArr['fae_status'] = 0;
				$PayDataArr['fae_ctr_id'] = $ctrId;
				$PayDataArr['fae_fct_id'] = $conId;
				$PayDataArr['fae_spare_money'] = !empty($PayDataArr['fae_spare_money']) ? (int) $PayDataArr['fae_spare_money']: 0;
				$CrmFinance = new CrmFinance();
				$Res = $CrmFinance->addPayMoney($PayDataArr);
				LibTpl::Success('添加成功，该打款的ID为'.$Res['data']);
			}
			else
			{
				LibTpl::Error('获取数据失败！');
			}	
		}
		$conId = (int) $Params['conId'];
		if($conId <= 0)
		{
			LibTpl::Error('获取数据失败，或者合同不存在！');	
		}
		
		$CrmFinance = new CrmFinance();
		$Res = $CrmFinance->GetContract(array('*'), sprintf(" AND fct_id =%d", $conId),true );
		if(empty($Res['data'])){
			LibTpl::Error('获取数据失败，或者合同不存在！');	
		}
		$ConArr = $Res['data'];
		$CrmBase =new CrmBase();
		$Status = 0;
		$res = $CrmBase->checkCtrUserRule($_SESSION['_userid'],[$ConArr['ctr_id']]);
		if(!empty($res['data'])){
			$Status = LibFc::checkDlRule('DL09',false);
			// LibTpl::Error('此客户非你所属，您无权限查看！');	
		} else{
			$Status = 1;
		}
		//权限  
		LibTpl::Set('Status', $Status);

		$ConStatusArr = array(-1=>'无效',0=>'等待审核', 1=>'付款中', 2=>'付款完成');
		LibTpl::Set('ConStatusArr', $ConStatusArr);

		
		$Res = $CrmFinance->get('fad_link_fct_usr',['DISTINCT duc_usr_id'],' AND duc_fct_id='.$conId);
		$ConArr['user'] = $Res['data']? array_column($Res['data'],'duc_usr_id'):[];
		$Res = $this->getSalesUser('',false);
		LibTpl::Set('SalesUser',$Res['data']? array_column($Res['data'],'au_name','au_uid'):[]);

		//服务项目
		$Res = $CrmFinance->GetConSer(array('fsl_money', 'fsl_btime', 'fsl_etime', 'sve_text', 'fsl_remark','fsl_id','fsl_sve_id','fsl_des_id'), ' AND fsl_fct_id='.$conId);
		
		$desIdArr =	array_map(function($item){
			if($item['fsl_sve_id']==7 && $item['fsl_des_id']){
				return $item['fsl_des_id'];
			}
		},$Res['data']);
		$desIdArr = array_filter($desIdArr);
		//获取服务项目的上一期服务时间
		$AdsBase = new AdsBase();
		$arr = [];
		if($desIdArr)
		{
			$ypcBase = new YpcBase();
			$res1 = $ypcBase->get('yp_brand', ['b_id,b_name'], ' order by b_initial');
			$brand = array_column($res1['data'], 'b_name', 'b_id');

			$res2 =$AdsBase->Get('yp_province_city', ['pc_id as id','pc_name as name'], '');
			$pcArr = array_column($res2['data'], 'name', 'id');

			$table = 'pj_place_ads 
			join pj_place on pa_id = pla_pa_id
			join pj_place_ads_time on pla_id=pat_pla_id';
			$res = $AdsBase->get($table,['*'],sprintf(" AND pla_id IN (%s)",implode(',',$desIdArr)));

			if($res['data']){
				$makeIds = array_column($res['data'],'pat_make_id');
				$ComBase = new ComBase();
				$makeres = $ComBase->get('bc_make',['make_id','make_name'],sprintf(" AND make_id in (%s)", implode(',',$makeIds)));
				$makeArr = array_column($makeres['data'],'make_name','make_id');
			}
			foreach ($res['data'] as $key => $val) {
				
				$arr[$val['pla_id']][$key] =$val['pa_name'];
				if($val['pat_keyword']){
					
					if($val['pat_make_id'] && $makeArr){
						$arr[$val['pla_id']][$key] .='-'.$makeArr[$val['pat_make_id']];
					}else{
						$arr[$val['pla_id']][$key] .='-'.$brand[$val['pat_keyword']];
					}
					if($val['pat_modpc'] && $val['pat_modcv']){
						$temp = '[乘|商]';
					}elseif ($val['pat_modpc']) {
						$temp = '乘用车';
					}elseif ($val['pat_modcv']) {
						$temp = '商用车';
					}
					$arr[$val['pla_id']][$key] .='-'. $temp;
				}elseif ($val['pat_pc_id']) {
					$arr[$val['pla_id']][$key] .='-'. $val['pat_pc_id']? $pcArr[$val['pat_pc_id']]:'全球';
				}
				$arr[$val['pla_id']][$key] .='-'. date('Y-m-d',$val['pat_btime']) .'~'.date('Y-m-d',$val['pat_etime']);
				
			}
		}
		
		
		foreach ($Res['data'] as $key => &$val) 
		{
			$val['las_etime'] = '';
			if ($val['fsl_sve_id'] == 7) 
			{
				$val['adsInfo'] = $arr[$val['fsl_des_id']]?implode("<br>",$arr[$val['fsl_des_id']]):'';

				$table = 'pj_place_ads join pj_user_ads on ads_id=pla_ads_id';
				//找同一个广告位置的上一次服务时间
				$res = $AdsBase->get($table, ['pla_id,pla_pa_id,pla_atime,ads_u_id'], sprintf(" and pla_con_id =%d and pla_ser_link_id=%d ", $ConArr['fct_id'], $val['fsl_id']), true);
				if ($res['data']) 
				{
					$res1 = $AdsBase->get($table, ['pla_con_id,pla_ser_link_id'], sprintf(" and pla_con_id!='' and pla_ser_link_id!='' and ads_u_id=%d and pla_pa_id=%d and pla_id!=%d and pla_atime<%d order by pla_atime desc", $res['data']['ads_u_id'], $res['data']['pla_pa_id'], $res['data']['pla_id'], $res['data']['pla_atime']), true);
					if ($res1['data']) 
					{
						$table = sprintf('fad_link_fct_sve join fad_contract on fsl_fct_id = fct_id and fct_ctr_id=%d', $ConArr['ctr_id']);
						$res2 = $CrmFinance->get($table, ['*'], sprintf(" and fsl_id=%d", $res1['data']['pla_ser_link_id']), true);
						$val['las_etime'] = date('Y-m-d', $res2['data']['fsl_btime']) . '-' . date('Y-m-d', $res2['data']['fsl_etime']);
					}
				}
			} 
			else 
			{
				$table = sprintf('fad_link_fct_sve join fad_contract on fsl_fct_id = fct_id and fct_ctr_id=%d', $ConArr['ctr_id']);
				$res = $CrmFinance->get($table, ['*'], sprintf(" and fsl_sve_id=%d and fsl_etime<%d order by fsl_etime desc", $val['fsl_sve_id'], $val['fsl_btime']), true);
				if ($res['data']) {
					$val['las_etime'] = date('Y-m-d', $res['data']['fsl_btime']) . '-' . date('Y-m-d', $res['data']['fsl_etime']);
				}
			}
		}
		unset($val);
		$ConArr['con_ser'] = $Res['data'];

		//等待审核付款记录
		$Res = $CrmFinance->getFinance(array('DISTINCT fae_id', 'fae_status', 'fae_text', 'fae_money', 'fae_spare_money', 'fae_create_time', 'fae_proof', 'fae_create_usr','au_name'), ' AND fae_fct_id='.$conId.' ORDER BY fae_create_time DESC');
		$ChkMoneyArr = $Res['data'];
		LibTpl::Set('ChkMoneyArr', $ChkMoneyArr);
		
		//已完成支付
		$Res = $CrmFinance->getPayLnkByWhere(array('fff_pay_id', 'fff_pay_money', 'fff_pay_time', 'fae_proof'), ' AND fff_fct_id='.$conId.' ORDER BY fff_pay_time DESC');
		$HasPayArr = $Res['data'];
		LibTpl::Set('HasPayArr', $HasPayArr);

		//总需要支付金额
		$ConArr['need_pay'] = $ConArr['fct_money'];
		foreach($HasPayArr as $v)
		{
			$ConArr['need_pay'] -= $v['fff_pay_money'];
		}

		//支付计划
		$Res = $CrmFinance->getPayMoney(array('pay_id', 'pay_status', 'pay_pay_time', 'pay_remark', 'pay_money'), ' AND pay_fct_id = '.$conId);
		$ConArr['pay_plan'] = $Res['data'];
		foreach($ConArr['pay_plan'] as $k=>$v)
		{
			$ConArr['pay_plan'][$k]['has_pay'] = 0;
			foreach($HasPayArr as $vv)
			{
				if($v['pay_id'] == $vv['fff_pay_id'])
				{
					$ConArr['pay_plan'][$k]['has_pay'] += $vv['fff_pay_money'];
				}
			}
		}


		$Res = $CrmFinance->get('fad_contract_file', array('*'), ' AND fcf_fct_id='.$conId.' ORDER BY fcf_seq');
		LibTpl::Set('ConFileArr', $Res['data']);
		
		LibTpl::Set('ConArr', $ConArr);
		LibTpl::Set('PageTitle', '合同明细');
		$this->HEAD_CSSJS['plugin'][] = 'ueditor';
	
		LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
		LibTpl::Put();
	

	}

	/**
	 * @method 审核合同
	 * @author zhengweihua 
	 * @copyright 2024-01-30
	 */
	public function chkContract()
	{
		LibFc::checkDlRule('DL09');
		$conId = !empty($_POST['conId']) ? LibFc::Int($_POST['conId']): 0;
		if($conId > 0)
		{
			$CrmFinance = new CrmFinance();
			//该合同关联项目中的广告是否超额
			$CrmFinance->chkAdsConflict($conId);

			$res = $CrmFinance->setConStatus($conId, true);

			if($res['data']){
				//如果仅有一期付款记录且未完成付款
				$cres = $CrmFinance->getFinance(['*'], ' AND fae_fct_id=' . $conId);
				if(count($cres['data'])==1 && $cres['data'][0]['fae_status']==0){
					$CrmFinance->chkApplyPay($cres['data'][0]['fae_id']);
				}
				LibFc::ReturnJson(true,'操作成功');
			}else{
				LibFc::ReturnJson(false,'操作失败');
			}
		}
	}

	/**
	 * @method 付款计划
	 * @author zhengweihua 
	 * @copyright 2024-01-30
	 */
	public function applyPaySet()
	{
		$Params = mvc::$URL_PARAMS;
		$CrmFinance = new CrmFinance();
		$faeId = !empty($Params['faeId']) ? (int) $Params['faeId']: 0;
		if(!empty($_POST['faeId']) && !empty($_POST['Pay']))
		{
			$faeId = (int) $_POST['faeId'];
			$PayDataArr = $_POST['Pay'];
			unset($PayDataArr['fae_spare_money']);
			$Res = $CrmFinance->getFinance(array('fae_status'), ' AND fae_id='.$faeId, true);
			if($Res['data']['fae_status'] == 1)
			{
				unset($PayDataArr['fae_money']);
			}
			else if($PayDataArr['fae_status'] == 1)
			{
				$CrmFinance->chkApplyPay($faeId);
			}
			unset($PayDataArr['fae_status']);

			if(!empty($_POST['OldTime']))
			{
				$PayDataArr['fae_create_time'] = strtotime($PayDataArr['fae_create_time']);
				if($PayDataArr['fae_create_time'] > time())
				{
					$PayDataArr['fae_create_time'] = time();
				}
				else if ($PayDataArr['fae_create_time'] <= $_POST['OldTime']-3600*24*60)
				{
					$PayDataArr['fae_create_time'] = $_POST['OldTime']-3600*24*60;
				}
				if($_POST['OldTime'] != $PayDataArr['fae_create_time'])
				{
					$PayDataArr['fae_set_time'] = 1;
				}
			}
			$CrmFinance->set('fad_finance',$PayDataArr, ' AND fae_id='.$faeId);
			LibTpl::Success('修改成功');
		}
		if($faeId > 0)
		{
			$Res = $CrmFinance->getFinance(array('*'), ' AND fae_id='.$faeId, true);
			LibTpl::Set('FaeArr', $Res['data']);
			LibTpl::Set('PageTitle', '打款记录修改');
			$this->HEAD_CSSJS['plugin'][] = 'ueditor';
			LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
			LibTpl::Put();
			exit;
		}
		else
		{
			LibTpl::Error('获取数据失败！');
		}
	}

	/**
	 * @method 客户详情
	 * @author zhengweihua 
	 * @copyright 2024-01-31
	 */
	public function detail()
	{
		$Params = mvc::$URL_PARAMS;
		$Params['order'] = 'detail';
		LibTpl::Set('Params',$Params);
		$ctrId = (int)$Params['ctrId'];
		if(!$ctrId) LibTpl::Error('获取数据失败！');

		$CrmBase = new CrmBase();
		$res = $CrmBase->checkCtrUserRule($_SESSION['_userid'],[$ctrId]);
		if(!empty($res['data'])){
			LibTpl::Error('此客户非你所属，您无权限查看！');
		}
		
	
		$CrmBase = new CrmBase();
		$res = $CrmBase->getCustomerDetail($ctrId);
		
		if(!$res['data']) LibTpl::Error('获取客户数据失败！');
		$ctrArr = $res['data'];
		$CrmBase = new CrmBase();

		$sveList = [];
		$table = 'fad_contract 
		join fad_link_fct_usr on fct_id = duc_fct_id 
		join fad_link_fct_sve on fct_id= fsl_fct_id
		join fad_service on fsl_sve_id = sve_id';
		$res = $CrmBase->get($table, ['fct_id,fct_ctr_id,fct_title,duc_usr_id,sve_text,fsl_id,fsl_sve_id,fsl_des_id,fsl_btime,fsl_remark,fsl_etime,fsl_money'], sprintf(" AND fct_ctr_id=%d order by fsl_etime desc", $ctrId));
		if ($res['data']) {
			$AdsBase = new AdsBase();
			$commonArr = [];
			//正常项目
			foreach ($res['data'] as $key => $val) {
				if($val['fsl_etime']>=time()){
					$commonArr[$val['fsl_id']] = $val['fsl_sve_id'].'_'.$val['fsl_remark'];
				}
			}
			foreach ($res['data'] as $key => $val) {
				$val['shoufei']=1;
				$val['zs']=0;
				$tempCommon = $commonArr;
				unset($tempCommon[$val['fsl_id']]);
				if($tempCommon && $val['fsl_sve_id']!=7 && in_array($val['fsl_sve_id'].'_'.$val['fsl_remark'],$tempCommon)){
					$val['zs']=1;
				}

				
				if($val['fsl_sve_id']==7 && $val['fsl_des_id']){
					$rss = $AdsBase->get('pj_place_ads',['pla_id,pal_shoufei'],sprintf(" and pla_id=%d",$val['fsl_des_id']),true);
					$val['shoufei']=$rss['data']['pal_shoufei']==-1?0:1;
				}
				
				if(isset($sveList[$val['fct_id']])){
					$sveList[$val['fct_id']]['sveArr'][] = [
						'sve_text'=>$val['sve_text'],
						'fsl_btime'=>$val['fsl_btime'],
						'fsl_etime'=>$val['fsl_etime'],
						'shoufei'=>$val['shoufei'],
						'zs'=>$val['zs']
					];
				}else{
					$sveList[$val['fct_id']] = [
						'fct_id'=>$val['fct_id'],
						'fct_title'=>$val['fct_title'],
						'duc_usr_id'=>$val['duc_usr_id'],
						'sveArr'=>[
							['sve_text'=>$val['sve_text'],'fsl_money'=>$val['fsl_money'],'fsl_btime'=>$val['fsl_btime'],'fsl_etime'=>$val['fsl_etime'],'shoufei'=>$val['shoufei'],'zs'=>$val['zs']]
						]
					];
				}
			}
			$usrIds = array_filter(array_column($res['data'], 'duc_usr_id'));
			$B2cBase = new B2cBase();
			$res = $B2cBase->get('an_user', ['au_uid,au_name'], sprintf(" and au_uid in (%s)", implode(',', $usrIds)));
			LibTpl::Set('salesArr', array_column($res['data'], 'au_name', 'au_uid'));
		}
		LibTpl::Set('sveList',$sveList);


		$table = 'crm_customer_rank join crm_label on cla_id = ccr_cla_id AND cla_type="rank"';
		$res = $CrmBase->get($table,['ccr_id,ccr_ctr_id,cla_name'],sprintf(" AND ccr_ctr_id=%d AND ccr_au_uid=%d",$ctrId,$_SESSION['_userid']),true);
		$ctrArr['rank_name'] = $res['data']['cla_name'];
		$ctrArr['ccr_id'] = $res['data']['ccr_id'];

		$res =  $CrmBase->get('fad_link_fct_sve',['min(fsl_btime) as min_btime'],sprintf(" and fsl_fct_id=%d",$ctrId),true);
		$ctrArr['min_btime'] = $res['data']['min_btime']?date('Y-m-d',$res['data']['min_btime']):''; 
		$res =  $CrmBase->get('fad_link_fct_sve',['max(fsl_etime) as max_etime'],sprintf(" and fsl_fct_id=%d",$ctrId),true);
		$ctrArr['max_etime'] =$res['data']['max_etime']?date('Y-m-d',$res['data']['max_etime']):''; 

		LibTpl::Set('comStyleArr',[1=>'工厂',2=>'贸易',3=>'门店',4=>'维修厂',5=>'保险',6=>"4S店",7=>'个人',9=>'其他']);
		LibTpl::Set('title','客户详情');
		LibTpl::Set('ctrArr',$ctrArr);
		LibTpl::Set('Params',$Params);
		LibTpl::Put();
	}

	/**
	 * @method 付款记录
	 * @author zhengweihua 
	 * @copyright 2024-01-31
	 */
	public function applyPayList()
	{
		$Params = mvc::$URL_PARAMS;
		$hasRule= LibFc::checkDlRule('DL11',false);
		LibTpl::Set('hasRule',$hasRule);
		
		$where = '';
		if(!$hasRule){
			if ($_SESSION['_usergroup'] == 'shangji') {
				$Params['user'] = $_SESSION['_xiajiUid'];
			} elseif ($_SESSION['_usergroup'] == 'yewu') {
				$Params['user'] = $_SESSION['_userid'];
			}
		}
		
		$page = empty($Params['page']) || $Params['page'] < 1? 1: (int) $Params['page'];
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		foreach($Params as $k=>$v)
		{	
			if(empty($v)) continue;
			switch($k)
			{
				case 'status':
					if($v<0){
						$v=0;
					}
					$where .= sprintf(' AND fae_status = %d',$v);
					break;
				case 'atime':
					$arr = explode('~',$v);
					if($arr){
						$where .= sprintf(' AND fae_create_time >= %d and fae_create_time<= %d ',strtotime($v),strtotime($v)+24*3600-1);
					}
					break;
			
				case 'user':
					if(!is_array($v)){
						$where .=sprintf(' AND fae_create_usr_id in (%s)',$v);	
					}else{
						$where .=sprintf(' AND fae_create_usr_id in (%s)',implode(',',$v));	
					}
					
					break;
				case 'keyword':
					if (trim($v) != '') {
						$where .= sprintf(" and ctr_comname like '%%%s%%' or fae_text like '%%%s%%' ", $v, $v);
					}
					break;
				case 'ctrId':
					$where .= $v > 0 ? ' AND fae_ctr_id = '.$v : '';	
					break;
			}
		}
		$CrmFinance = new CrmFinance();
		$res = $CrmFinance->getFinance(array('count(*) as count'), $where.' GROUP BY fae_id ');

		$count = count($res['data']);
		$pageMsg = LibPage::show($count,$perPage,true);
		LibTpl::Set('pageMsg', $pageMsg);
		if($count > 0)
		{
			$res = $CrmFinance->GetFinance(array('*'), sprintf(" %s GROUP BY fae_id ORDER BY fae_status ASC, fae_create_time DESC  LIMIT %d, %d", $where, ($page-1)*$perPage, $perPage));
			$list = $res['data'];
			LibTpl::Set('listArr', $list);
		}

		$res = $this->getSalesUser();
		LibTpl::Set('salesArr', $res['data']);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('PageTitle', '财务审核');
		LibTpl::Put();
	}

	/**
	 * @method 删除付款记录
	 * @author zhengweihua 
	 * @copyright 2024-01-31
	 */
	public function delApplyPay()
	{
		$faeId = !empty($_POST['faeId']) ? LibFc::Int($_POST['faeId']): 0;
		if($faeId > 0)
		{
			$CrmFinance = new CrmFinance();
			$res =  $CrmFinance->delFinance($faeId);
			LibFc::ajaxJsonEncode($res);
		}
	}

	/**
	 * @method 审核付款记录
	 * @author zhengweihua 
	 * @copyright 2024-02-01
	 */
	public function chkApplyPay()
	{	
		LibFc::checkDlRule('DL11');
		$faeId = !empty($_POST['faeId']) ? LibFc::Int($_POST['faeId']): 0;
		if($faeId > 0)
		{
			$CrmFinance = new CrmFinance();
			$res = $CrmFinance->chkApplyPay($faeId);
			LibFc::ajaxJsonEncode($res);
		}
	}

	/**
	 * @method 添加客户
	 * @author zhengweihua 
	 * @copyright 2024-02-19
	 */
	public function addCust()
	{	
		if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['mobile']){
			$LibYpApi = new LibYpApi();

			$res = $LibYpApi->Get('crm/checkMobileSales',['mobile' => $_POST['mobile']]);

			$B2cBase = new B2cBase();
			
			if($res['data'] && $res['data']['au_uid'] && $res['data']['au_uid']!=$_SESSION['_userid']){
				$user = $B2cBase->get('an_user',['au_uid','au_name'],sprintf(" AND au_uid=%d",$res['data']['au_uid']),true);
				LibTpl::Error($_POST['mobile'].'手机号码已归属：'.$user['data']['au_name']);
			}
			$getArr = [
				'mobile'=>$_POST['mobile'],
				'au_uid'=>$_SESSION['_userid']
			];
			$res = $LibYpApi->Get('crm/addCtrByMobile',$getArr);
			if($res['status']){
				LibTpl::Success('添加成功',mvc::$cfg['SELF_URI'].'customer/editCustomer?ctr_id='.$res['data']);
				exit;
			} 
		}
		LibTpl::Put();
	}

	/**
	 * @method 编辑客户
	 * @author zhengweihua 
	 * @copyright 2024-02-19
	 */
	public function editCustomer()
	{
		$Params = mvc::$URL_PARAMS;
		$arr = [];
		$hasShareAurule = LibFc::checkDlRule('DL18',false);
		if(!empty($Params['ctr_id']))
		{
			$CrmBase = new CrmBase();
			$res = $CrmBase->getCustomerDetail($Params['ctr_id']);
			$arr = $res['data'];
			
		}	
		$getArr  = [
			'type'=>'part,make,self,style'
		];
		$LibCrmApi = new LibCrmApi();
		$res = $LibCrmApi->Get('cus/getLabels', $getArr, $_POST);
		LibTpl::Set('labelArr',$res['data']);
		LibTpl::Set('hasShareAurule',$hasShareAurule?'Y':'N');
		LibTpl::Set('ctrArr',$arr);
		LibTpl::Put();
	}

	/**
	 * @method 更改客户类型
	 * @author zhengweihua 
	 * @copyright 2024-03-04
	 */
	public function changeCtrStatus()
	{
		LibFc::checkDlRule('DL12');
		if($_SERVER['REQUEST_METHOD']=='POST'){
			$CrmBase = new CrmBase();
			$ctrIds = $_POST['ctr_ids'];
			$status = $_POST['status'];
			$where = '';
			switch ($status) {
				case -1:
					//公海以及过期用户支持忽略
					$where = 'AND ctr_level_id in (0,6)';
					break;
				case 0:
					//取消忽略用户
					$where = 'AND ctr_level_id=-1';
					break;
			}
			$res = $CrmBase->get('crm_customer',['ctr_id'],sprintf(" %s AND ctr_id IN (%s)",$where,$ctrIds));
			if($res['data']){
				$ctrIdArr = array_column($res['data'],'ctr_id');
				$res = $CrmBase->set('crm_customer',['ctr_level_id'=>$status],sprintf(" AND ctr_id IN(%s)",implode(',',$ctrIdArr)));
				LibFc::ajaxJsonEncode($res);
			}else{
				LibFc::ReturnJson(false,'操作失败，仅公海/过期客户支持忽略操作');
			}
			
		}
	}

	/**
	 * @method 客户的跟进记录
	 * @author zhengweihua 
	 * @copyright 2024-03-05
	 */
	public function custFollow()
	{
		$Params = mvc::$URL_PARAMS;

		$ctrId = $Params['ctrId'];
		if(!$ctrId) LibTpl::Error('参数错误');
		$cfoId = (int)$Params['cfoId'];
		$CrmBase = new CrmBase();

		if($cfoId)
		{
			$cfores = $CrmBase->get('crm_follow',['*'],sprintf(" AND cfo_id =%d",$cfoId),true);
			$cfoArr = $cfores['data'];
			LibTpl::Set('cfoArr',$cfoArr);
		}

		$page = empty($Params['page']) || $Params['page'] < 1? 1: (int) $Params['page'];
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$where = sprintf(" and cfo_ctr_id = %d",$ctrId);
		
		$res = $CrmBase->get('crm_customer',['ctr_id,ctr_tel,ctr_kefu'],sprintf(" and ctr_id=%d",$ctrId),true);
		$ctrArr = $res['data'];
		LibTpl::Set('ctrArr',$ctrArr);
		//此客户现在有业务员，只能看自己的跟进记录
		$res = $CrmBase->get('crm_customer_admin', ['cca_au_uid'], sprintf(" and cca_ctr_id=%d and cca_end_time >%d ", $ctrId, time()),true);
		$isdeal=0;
		if(!empty($res['data']))
		{
			if($res['data']['cca_au_uid']!= $_SESSION['_userid'])
			{	
				if($_SESSION['_usergroup']=='yewu'){
					$where .= sprintf(" and cfo_au_uid = %d", $_SESSION['_userid']);
				}elseif ($_SESSION['_usergroup']=='shangji') {
					$where .= sprintf(" and cfo_au_uid in (%s)", implode(',',$_SESSION['_xiajiUid']));
				}
				
			}
			$isdeal=1;
		}


		$table = 'crm_follow join crm_customer on ctr_id = cfo_ctr_id';
		$res = $CrmBase->get($table, ['count(*) as count'], $where, true);
		$total = $res['data']['count'];
		$listArr = [];
		if($total > 0)
		{
			$where .= sprintf(" order by cfo_id desc limit %d, %d", ($page-1)*$perPage, $perPage);
			$res = $CrmBase->get($table, ['ctr_id,cfo_type,cfo_pass,cfo_check, ctr_uname, ctr_comname, ctr_contact, ctr_tel, cfo_id, cfo_txt, cfo_au_name, cfo_au_uid, cfo_au_name, cfo_atime,cfo_yxcheck,cfo_yxchecktime'], $where);
			
			//查离职员工的au_uid
			$auUid = [];
			$B2cBase = new B2cBase();
			$aures = $B2cBase->get('an_user', ['au_uid'], " and au_status=0");
			if ($aures['data']) {
				$auUid = array_column($aures['data'], 'au_uid');
			}
			foreach ($res['data'] as $key =>&$val) {
				//未成交且属于离职员工可直接查看
				if($isdeal==0)
				{	
					if($auUid && in_array($val['cfo_au_uid'],$auUid))continue;
					
					if($_SESSION['_usergroup']=='shangji' && !in_array($val['cfo_au_uid'],$_SESSION['_xiajiUid'])) $val['cfo_txt'] = '不可查看';
	
					if(($_SESSION['_usergroup']=='yewu' || $_SESSION['_usergroup'] == 'kefu') && $val['cfo_au_uid'] !=$_SESSION['_userid']){
						$val['cfo_txt'] = '不可查看';
					}
				}
			}
			unset($val);
			$listArr = $res['data'];
		}	
		LibTpl::Set('followArr',$listArr);
		LibTpl::Set('Pages',LibPage::Show($total,$perPage));
		$Params['order'] = 'custFollow';
		LibTpl::Set('Params',$Params);
		$invalidArr = ['电话打不通','听到跑街令就挂了','直接挂掉了'];
		if($cfoId && $cfoArr['cfo_pass']){
			$invalidArr = ['call'=>'电话','weixin'=>'微信','qq'=>'QQ','other'=>'其他'];
		}
		LibTpl::Set('invalidArr',$invalidArr);

		$res = $CrmBase->get('crm_plan',['*'],sprintf(" AND cp_from='general' AND cp_ctr_id=%d AND cp_au_uid=%d",$ctrId,$_SESSION['_userid']));
		LibTpl::Set('planArr',$res['data']);
		
		LibTpl::Set('typeArr',['call'=>'电话','weixin'=>'微信','qq'=>'QQ','other'=>'其他']);
		$this->HEAD_CSSJS['plugin'][] = 'ueditor';
		LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
		LibTpl::Put();
	}


	/**
	 * @method 批量更改跟进状态
	 * @author zhengweihua 
	 * @copyright 2024-04-12
	 */
	public function changeFollowPass()
	{
		LibFc::checkDlRule('DL10');
		if($_SERVER['REQUEST_METHOD']=='POST'){
			$CrmBase = new CrmBase();
			$cfoIds = $_POST['cfo_ids'];
			$pass = (int)$_POST['cfo_pass'];
			$res = $CrmBase->set('crm_follow',['cfo_pass'=>$pass],sprintf(" AND cfo_id IN(%s)",$cfoIds));
			LibFc::ajaxJsonEncode($res);
		}
	}
	
	/**
	 * 更多客户信息
	 */
	public function moreCustInfo()
	{
		$Params = mvc::$URL_PARAMS;
		$ctrId = (int)$Params['ctrId'];
		
		$filed = ['ctr_id,ctr_kefu, ctr_uid,ctr_score, ctr_level_id,ctr_uname, ctr_comname, ctr_com_style, ctr_pct_ids, ctr_addr,ctr_contact,shop_id as ctr_pjl_shop_id, IFNULL(shop_vip_etime,0) as shop_vip_etime,IFNULL(shop_enter_time,0) as shop_enter_time,IFNULL(shop_apply_time,0) as shop_apply_time, ctr_tel,ctr_pjl_shop_entertime,ctr_pjl_shop_applytime,ctr_pjl_shop_etime,ua_pv,ua_vin_count,ua_number_count,ua_epc_count,shop_img,shop_tels'];
		$where = sprintf(" AND ctr_id=%d",$ctrId);
		$CrmBase = new CrmBase();
		$table = 'crm_customer 
		left join ypdb_write.yp_user_act on ctr_uid = ua_uid
		left join yp_paojieling.pl_shop on ctr_uid = shop_id';
		$res = $CrmBase->get($table, $filed, $where,true);
		if($res['data'])
		{
			$data = $res['data'];
			$ctr_uid = $res['data']['ctr_uid'];
			if($res['data']['ctr_pjl_shop_id'])
			{
				$PjlBase = new PjlBase();
				$plShopArr = $PjlBase->get('pl_shop left join pl_tuisong on stu_shop_id=shop_id ',['shop_id','stu_shop_id','shop_tsfw_vin_count','shop_quoted_count'],sprintf(" and shop_id=%d",$res['data']['ctr_pjl_shop_id']));
				if(!empty($plShopArr['data'])){
					$plShopArr = array_column($plShopArr['data'],null,'shop_id');
				}
			}
			$YpwBase = new YpwBase();


			$data['ctr_pct_ids'] = json_decode($data['ctr_pct_ids'], true);
			$tids = [];
			if(!empty($data['ctr_pct_ids']['pid']))
			{
				$tids[] = (int) $data['ctr_pct_ids']['pid'];
				if(!empty($data['ctr_pct_ids']['cid']))
				{
					$tids[] = (int) $data['ctr_pct_ids']['cid'];
					if(!empty($data['ctr_pct_ids']['tid'])) $tids[] = (int) $data['ctr_pct_ids']['tid'];
				}
			}
			$data['pct_ids'] = $tids;
			$data['pcts'] = [];
			$CrmContract = new CrmContract();
			$res = $CrmContract->getAddrByIds(implode(',', $data['pct_ids']));
			$pctArr = $res['data'];
			foreach($data['pct_ids'] as $pt)
			{
				if(empty($pctArr[$pt])) break;
				$data['pcts'][] = $pctArr[$pt];
			}
			//关注零件
			$res = $YpwBase->get('yp_user_act_part', ['uap_part'], sprintf(" and uap_uid=%d order by uap_count desc limit 3", $ctr_uid));
			$data['act_part'] = array_column($res['data'], 'uap_part');

			//关注品牌
			$per = empty($Params['brand_id'])? 3: 100;
			$res = $YpwBase->get('yp_user_act_brand', ['uab_brand'], sprintf(" and uab_uid=%d order by uab_count desc limit %d", $ctr_uid, $per));
			$data['act_make'] = array_column($res['data'], 'uab_brand');

			// $pctids = array_merge($pctids, $data['pct_ids']);
			//推送次数
			$data['tui_song'] = '未开通';
			if(isset($plShopArr[$data['ctr_pjl_shop_id']]) && $plShopArr[$data['ctr_pjl_shop_id']]['stu_shop_id'])
			{
				$data['tui_song'] = $plShopArr[$data['ctr_pjl_shop_id']]['shop_tsfw_vin_count'];
			}
			//最近
			$data['recent_pv_count'] = isset($nowShow[$data['ctr_pjl_shop_id']]) ? $nowShow[$data['ctr_pjl_shop_id']] : 0;
			//报价
			$data['shop_quoted_count'] = isset($plShopArr[$data['ctr_pjl_shop_id']])?$plShopArr[$data['ctr_pjl_shop_id']]['shop_quoted_count']:0;
			//电话次数
			$data['call_count'] = isset($callCount[$data['ctr_pjl_shop_id']])?$callCount[$data['ctr_pjl_shop_id']]:0;
			//配件数
			$data['product_count'] = isset($shopItemCount[$data['ctr_pjl_shop_id']])?$shopItemCount[$data['ctr_pjl_shop_id']]:0;
			//门头照
			$data['shop_img'] = $data['shop_img']?explode(',',$data['shop_img']):[];
			if($data['shop_img'])
			{
				foreach ($data['shop_img'] as &$imgItem) {
					$imgItem = mvc::$cfg['FILE_CENTER']['pjl']['url_get'].'&c=shop&f='.$imgItem.mvc::$cfg['FILE_CENTER']['pjl']['get_uri'];
				}	
				unset($imgItem);
			}
			//跟进客服
			$data['ctr_kefu_name'] = '';
			if($data['ctr_kefu']){
				$kefures = 	$this->getKefu();
				$kefuArr =  $kefures['data']?array_column($kefures['data'],'au_name','au_uid'):[];
				$data['ctr_kefu_name'] = $kefuArr[$data['ctr_kefu']];
			}
		}
		LibTpl::Set('dataArr',$data);
		LibTpl::Put();
	}

	/**
	 * @method 导出跟进记录
	 * @author zhengweihua 
	 * @copyright 2024-04-26
	 */
	public function exportFollow()
	{
		$Params = mvc::$URL_PARAMS;
		if(!$Params['export_time']||!$Params['au_ids'])
		{
			LibTpl::Error('参数错误');
		}
		$temp = explode('~',$Params['export_time']);
		if(count($temp) == 2){
			$start = strtotime($temp[0]);
			$end = strtotime($temp[1]) + 86399;
			$auIds = $Params['au_ids'];
			$CrmContract = 	new CrmContract();
			$CrmContract->exportFollow($start,$end,$auIds);
		}
	}

	/**
	 * @method 批量更新客户的跟进客服
	 * @author zhengweihua 
	 * @copyright 2024-06-17
	 */
	public function changeCtrKefu()
	{
		if($_SERVER['REQUEST_METHOD']=='POST')
		{
			$ctrArr = 	explode(',', $_POST['ctr_ids']);
			$ctrKefu = $_POST['kefu'];
			$CrmBase =	new CrmBase();
			$table = 'crm_customer join crm_customer_admin on cca_ctr_id =ctr_id';
			$ctrIds = implode(',', $ctrArr);
			$res = $CrmBase->get($table,['*'],sprintf(" AND ctr_id IN (%s) AND cca_au_uid=172999",$ctrIds));
			if($res['data'])
			{
				$newIds = implode(',',array_column($res['data'],'ctr_id'));
				$res = $CrmBase->set('crm_customer', ['ctr_kefu' => $ctrKefu], sprintf(" AND ctr_id IN (%s)",$newIds));
				LibFc::ajaxJsonEncode($res);
			}else{
				LibFc::ReturnJson(true);
			}
		}
	}

	/**
	 * @method 业绩统计导出
	 * @author zhengweihua 
	 * @copyright 2024-07-16
	 */
	public function exportYj()
	{
		$Params = mvc::$URL_PARAMS;
		if(!$Params['export_time']||!$Params['au_ids'])
		{
			LibTpl::Error('参数错误');
		}
		$temp = explode('~',$Params['export_time']);
		if(count($temp) == 2){
			$start = strtotime($temp[0]);
			$end =  strtotime('+1 month',strtotime($temp[1]))  -1;
			$auIds = $Params['au_ids'];
			$CrmContract = 	new CrmContract();
			$CrmContract->exportYj($start,$end,$auIds);
		}
	}

	/**
	 * @method 批量变更客户业务员
	 * @author zhengweihua 
	 * @copyright 2024-08-07
	 */
	public function changeCtrYwy()
	{
		if($_SERVER['REQUEST_METHOD']=='POST')
		{	
			$ctrArr = 	explode(',', $_POST['ctr_ids']);
			$ctrYwy = (int)$_POST['ywy'];

			if(!$ctrArr || !$ctrYwy) return LibFc::ReturnJson(false,'参数错误');
			
			$CrmFinance = new CrmFinance();
			$res = $CrmFinance->changeCtrYwy($_SESSION['_userid'],$ctrArr,$ctrYwy);
			LibFc::ajaxJsonEncode($res);
		}
	}

	/**
	 * @method
	 * @author zhengweihua 
	 * @copyright 2024-08-07
	 */
	public function yixiangCtr()
	{
		if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['ctr_id']){
			$ctr_id =(int)$_POST['ctr_id'];

			$CrmContract = new CrmContract();
			$res = $CrmContract->setYixiangCtr($_SESSION['_userid'],$_POST);
			LibFc::ajaxJsonEncode($res);
		}	
		$Params = mvc::$URL_PARAMS;
		$ctr_id =(int)$Params['ctr_id'];
		$ccr_id =(int)$Params['ccr_id'];
		$CrmBase = new CrmBase();
		if($ccr_id){
			$table = 'crm_customer 
			join crm_customer_rank on ctr_id = ccr_ctr_id';
			$res  = $CrmBase->get($table,['*'],sprintf(" AND ccr_id=%d AND ctr_id = %d",$ccr_id,$ctr_id),true);
		}else{
			$table = sprintf('crm_customer
			left join crm_customer_rank on ctr_id = ccr_ctr_id AND ccr_au_uid=%d',$_SESSION['_userid']);
			$res  = $CrmBase->get($table,['*'],sprintf(" AND ctr_id = %d",$ctr_id),true);
		}
		$ctrArr = $res['data'];
	
		//获取标签
		$res = $CrmBase->get('crm_label',['*'],sprintf(" AND cla_type='rank' ORDER BY cla_seq asc"));
		LibTpl::Set('labelArr',$res['data']);

		//获取服务项目
		$res = $CrmBase->get('fad_service',['sve_id as cla_id,sve_text as cla_name']);
		LibTpl::Set('serviceList',$res['data']);
		$sveArr = array_column($res['data'],null,'cla_id');
		$ctrArr['sve_name'] = '';
		if($ctrArr['ccr_sve_text']){
			$ctrArr['ccr_sve_text'] = explode(',',$ctrArr['ccr_sve_text']);
			foreach ($ctrArr['ccr_sve_text'] as $vv) {
				$ctrArr['sveArr'][] = $sveArr[$vv];
			}
			$ctrArr['sve_name'] = implode(',',array_column($ctrArr['sveArr'],'cla_name'));
		}else{
			$ctrArr['sveArr'] = [];
		}
	
		LibTpl::Set('ctrArr',$ctrArr);


		// $content = LibTpl::Fetch();
		// LibFc::ReturnJson(true,$content);
		LibTpl::Put();

	}

	/**
	 * @method 获取显示的字段
	 * @author zhengweihua 
	 * @copyright 2024-01-02
	 */
	protected function getShowCol()
	{
		$colArr = [
			'score'=>['chk'=>'','name'=>'活跃度'],
			'name'=>['chk'=>'','name'=>'公司名称'],
			'day_plan'=>['chk'=>'','name'=>'日计划'],
            'status'=>['chk'=>'','name'=>'状态'],
            'type'=>['chk'=>'','name'=>'类型'],
            'rel_name'=>['chk'=>'','name'=>'联系人'],
            'rel_tel'=>['chk'=>'','name'=>'联系电话'],
            'sales_name'=>['chk'=>'','name'=>'业务员'],
            'sve_name'=>['chk'=>'','name'=>'服务项目'],
            'last_follow'=>['chk'=>'','name'=>'最后跟进'],
            'province_city'=>['chk'=>'','name'=>'省市'],
            'address'=>['chk'=>'','name'=>'地址'], 
            'pic'=>['chk'=>'','name'=>'门头照'],   
            'shopinfo'=>['chk'=>'','name'=>'商铺'],
            'time'=>['chk'=>'','name'=>'到期/申请'],
            'ua_pv'=>['chk'=>'','name'=>'浏览'],
            'ua_vin_count'=>['chk'=>'','name'=>'VIN'],
            'ua_number_count'=>['chk'=>'','name'=>'号码'],
            'ua_epc_count'=>['chk'=>'','name'=>'EPC'],
            'call_count'=>['chk'=>'','name'=>'电话'],
            'product_count'=>['chk'=>'','name'=>'配件'],   
            'shop_quoted_count'=>['chk'=>'','name'=>'报价'],
            'recent_pv_count'=>['chk'=>'','name'=>'最近'],
            'tui_song'=>['chk'=>'','name'=>'推送'],
            'act_part'=>['chk'=>'','name'=>'关注零件'], 
            'act_make'=>['chk'=>'','name'=>'关注品牌'],
            'make'=>['chk'=>'','name'=>'主营品牌'],
            'part'=>['chk'=>'','name'=>'主营类别'],    
		];
		$allChk = $_COOKIE['showCol']?explode(',',$_COOKIE['showCol']):array_keys($colArr);
		$chkArr = [];
		foreach ($allChk as $val) 
		{	
			//先赋值待会儿合并不会变更值
			$colArr[$val]['chk'] = 'checked';
			$chkArr[$val] = $colArr[$val];
		}
		$colArr = array_merge($chkArr,$colArr);
		return $colArr;
	}

	/**
	 * @method 联系人修改历史
	 * @author zhengweihua 
	 * @copyright 2025-06-07
	 */
	public function contactChangeLog()
	{
		$Params = mvc::$URL_PARAMS;
	
		$page = empty($Params['page']) || $Params['page'] < 1? 1: (int) $Params['page'];
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;

		$where = '';
		foreach($Params as $k=>$v)
		{	
			if(empty($v)) continue;
			switch($k)
			{
				case 'ctrId':
					$where .= $v > 0 ? ' AND ccl_ctr_id = '.$v : '';	
					break;
			}
		}

		$CrmBase = new CrmBase();
		$res = $CrmBase->get('crm_contact_log',['count(*) as counts'],$where,true);
		$count = $res['data']['counts'];
		$pageMsg = LibPage::show($count,$perPage,true);
		LibTpl::Set('pageMsg', $pageMsg);
		if($count > 0)
		{
			$res = $CrmBase->get('crm_contact_log join crm_customer on ctr_id=ccl_ctr_id',['crm_contact_log.*','ctr_uname','ctr_comname'],sprintf(" %s ORDER BY ccl_etime DESC",$where));
			$list = $res['data'];
			foreach ($list as $key => &$val) {
				$val['ccl_data'] = json_decode($val['ccl_data'], true);
			}
			unset($val);
			LibTpl::Set('listArr', $list);
		}
		//获取所有业务员姓名
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('an_user', ['au_uid', 'au_name']);
		$auArr = array_column($res['data'], 'au_name', 'au_uid');
		LibTpl::Set('auArr',$auArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('PageTitle', '');
		LibTpl::Put();
	}

	/**
	 * @method 意向审核
	 * @author zhengweihua 
	 * @copyright 2026-04-14
	 */
	public function yxCheck()
	{	
		if($_SERVER['REQUEST_METHOD']=='POST' && $_POST)
		{

			$cfoId = (int)$_POST['cfoId'];
			$status = $_POST['status'];
			$CrmBase = new CrmBase();
			$res = $CrmBase->set('crm_follow',['cfo_yxcheck'=>$status,'cfo_yxchecktime'=>time()],sprintf(" AND cfo_id=%d",$cfoId));
			LibFc::ajaxJsonEncode($res);
		}
	}

	/**
	 * @method 修改意向状态
	 * @author 2026-08-06
	 */
	public function modifyYxCheck()
	{	
		if($_SERVER['REQUEST_METHOD']=='POST' && $_POST)
		{
			if($_SESSION['_userid'] != 151295){
				LibFc::ReturnJson(false, '无权限修改意向状态');
			}
			$cfoId = (int)$_POST['cfoId'];
			$status = (int)$_POST['status'];
			if(!$cfoId){
				LibFc::ReturnJson(false, '记录ID不存在');
			}
			if(!in_array($status, [0,1,-1])){
				LibFc::ReturnJson(false, '意向状态参数不正确');
			}
			$CrmBase = new CrmBase();
			$res = $CrmBase->set('crm_follow',['cfo_yxcheck'=>$status,'cfo_yxchecktime'=>time()],sprintf(" AND cfo_id=%d",$cfoId));
			LibFc::ajaxJsonEncode($res);
		}
	}
}
