<?php
class indexAction extends baseAction
{
	function index()
	{
        $PjlBase = new PjlBase();
        $res = $PjlBase->get('dl_company left join dl_company_target on dct_dco_id=dco_id', ['dl_company.dco_isyp'], sprintf(' and dco_id=%d and dct_begin <=%d and dct_end >=%d', $_SESSION['_dcoid'], time(), time()), true);
        LibTpl::Set('comArr', $res['data']);
		//查询当前用户是否有CRM机器人
		$B2cBase = new B2cBase();
		$res1 = $B2cBase->get('wx_robot',['wr_id'],sprintf(" AND wr_totype='crm' AND wr_uid=%d",$_SESSION['_userid']),true);
		LibTpl::Set('robotArr', $res1['data']);
		LibTpl::Set('title', mvc::$cfg['TITLE']);
		LibTpl::Put();
	}


	function mywork()
	{
		$Params = mvc::$URL_PARAMS;
		

		$fastTime = [
            '本月'=>date('Y-m').' ~ '.date('Y-m'),
            '上个月'=>date('Y-m', strtotime('-1 month', strtotime(date('Y-m-1')))).' ~ '.date('Y-m', strtotime(date('Y-m-01'))-1),
        ];
		$fastYear = array_reverse(range(2010,date('Y')));
		foreach ($fastYear as $value) {
			$fastYearList[$value] = "{$value}-01 ~ {$value}-12";
		}	
		LibTpl::Set('fastTime', $fastTime);
		LibTpl::Set('fastYear', $fastYearList);
		$Params['plandate']= isset($Params['plandate'])?$Params['plandate']:date('Y-m-d');
		// 目标业绩以及业绩显示
		$CrmContract = new CrmContract();

		$Params['betime'] = empty($Params['betime']) ? $fastTime['本月'] : $Params['betime'];
		if($Params['betime']){
			$temp = explode(' ~ ',$Params['betime']);
			
			$start = strtotime($temp[0]);
			$end = strtotime($temp[1].'-'.date('t',strtotime($temp[1])))+86399;
		}
		else
		{
			$start =  strtotime(date('Y-m-1'));
			$end = strtotime("+1 month",$start)-1;	
		}
		

		$showField = [
			'ywy'=>"业务员",'wz'=>'网站','ldfw'=>'联动服务','ypgg'=>'宜配广告',
			'pdfml'=>'PDF目录','rj'=>'软件','rjdz'=>'软件定制','ypxj'=>'宜配小计','wdxf'=>'网站续费','rjnf'=>'软件年费',
			'rjfwf'=>'软件服务费','ldfwxf'=>'联动服务续费','ypqt'=>'宜配其他','ypzj'=>'宜配总计',
			'sjrz'=>'商家入驻','pchy'=>'PC会员','pjgg'=>'跑街广告','zsjm'=>'招商加盟',
			'jqr'=>'机器人','zyb'=>'资源包','tsfw'=>'推送服务','ddh'=>'打电话','qt'=>'其它','pjxj'=>'跑街小计','zj'=>'总计','mbyj'=>'业绩目标'];
		
		LibTpl::Set('showField',$showField);
		$searchUser = [];
		//没有提成报表的权限
		if(!LibFc::checkDlRule('DL04',false))
		{
			$hasRule = LibFc::checkDlRule('DL16',false);
		
			if ($_SESSION['_usergroup'] == 'shangji') {
				$searchUser = $hasRule ? $_SESSION['_xiajiUid'] : [$_SESSION['_userid']];
				$yjUId = implode(',', $_SESSION['_xiajiUid']);
			} elseif (in_array($_SESSION['_usergroup'], ['yewu', 'kefu'])) {
				$searchUser[] =  $_SESSION['_userid'];
				$yjUId = $_SESSION['_userid'];
			} elseif (in_array($_SESSION['_usergroup'], ['all'])) {
				$yjUId = $this->getSalesUser('', false, true);
				$yjUId = implode(',', array_column($yjUId['data'], 'au_uid'));
				$where = '';
			}
			
		}else{
			$yjUId = $this->getSalesUser('', false, true);
			$yjUId = implode(',', array_column($yjUId['data'], 'au_uid'));
			$where = '';
		}
		if($_SESSION['_usergroup']=='all' && $_SESSION['_userid']==151295){
			$res = $this->getSalesUser('',true,true);
			$key = array_search('选择 [跑街业务员] 所有人', $res['data']['跑街业务员']);
			$Params['ccr_au_uid'] = $Params['ccr_au_uid']??$key;
			$Params['yj_au_uid'] = $Params['yj_au_uid']??$key;
		}
		
		if($Params['yj_au_uid'])  $yjUId = $Params['yj_au_uid'];
		if ($yjUId) {
			$res = $CrmContract->getYeji($start, $end, $yjUId, $showField, 'targetMoney');
			$yjArr = $res['data'];
		}
		
		LibTpl::Set('yjArr',$yjArr);
			

		// 意向客户
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$Params['ccr_au_uid'] = $Params['ccr_au_uid']??$_SESSION['_userid'];
		$table = "crm_customer_rank 
		join crm_label on cla_id=ccr_cla_id AND cla_type='rank'
		join crm_customer on ccr_ctr_id=ctr_id
		left join ypdb_write.yp_user on ctr_uid = u_id";
		
		if($searchUser){
			$where .= sprintf(" AND ccr_au_uid in (%s)",implode(',',$searchUser));
			$oWhere = sprintf(" AND au_uid in (%s)",implode(',',$searchUser));
		}
		if($Params['ccr_cla_id']){
			$where .= sprintf(" AND ccr_cla_id=%d",(int)$Params['ccr_cla_id']);
		}
		if($Params['ccr_au_uid']){
			$where .= sprintf(" AND ccr_au_uid in (%s)",$Params['ccr_au_uid']);
		}
		if($Params['month']){
			$month = $Params['month'];
			$start = strtotime($month);
			$end = strtotime($month.'-'.date('t',strtotime($month)))+86399;
			$where .= sprintf(" AND ccr_etime>=%d AND ccr_etime<=%d",$start,$end);
			//额外的统计
			$sWhere = sprintf(" AND ccr_etime>=%d AND ccr_etime<=%d",$start,$end);

		}
		//支持筛选
		if($Params['sve_id']){
			$where .= sprintf(" AND FIND_IN_SET('%d',ccr_sve_text)",(int)$Params['sve_id']);
		}
		$res = $CrmContract->get('fad_service',['*']);
		$sveArr = array_column($res['data'], 'sve_text', 'sve_id');
		$CrmContract = new CrmContract();
		$tres = $CrmContract->get($table,['count(*) as counts'],$where,true);
		$total = $tres['data']['counts'];

		
		if($total>0){
			
			$res = $CrmContract->get($table,['*'], sprintf(" %s order by ccr_au_uid,ccr_etime desc limit %d,%d ",$where,($page-1)*$perPage, $perPage));

			$listArr = $res['data'];
			$ctrIds = $listArr?array_column($listArr,'ccr_ctr_id'):[];
			$auUIds = $listArr?array_unique(array_column($listArr,'ccr_au_uid')):[];
			if($ctrIds){
			
				$ftable = sprintf("(SELECT cfo_ctr_id,cfo_au_uid, MAX(cfo_id) AS lcfo_id FROM crm_follow 
				where cfo_ctr_id in (%s) and cfo_au_uid in (%s) GROUP BY cfo_ctr_id,cfo_au_uid) AS a 
				JOIN crm_follow AS b ON a.lcfo_id = b.cfo_id AND a.cfo_ctr_id = b.cfo_ctr_id ", implode(',', $ctrIds),implode(',',$auUIds));
				
				$res = $CrmContract->get($ftable, ['a.cfo_au_uid,b.cfo_ctr_id, b.cfo_au_name, b.cfo_atime'], ' order by cfo_atime desc');
				$lfollow = [];
				foreach ($res['data'] as $key => $val) {
					$lfollow[$val['cfo_ctr_id']][$val['cfo_au_uid']] = $val;
				}
				//查是否成交
				$res = $CrmContract->get('crm_customer_admin',['cca_id,cca_ctr_id,cca_au_uid'],sprintf(" AND cca_level_id=5 AND cca_end_time>%d AND cca_ctr_id in (%s)",time(),implode(',',$ctrIds)));
				$dealCust = [];
				foreach ($res['data'] as $key => $val) {
					$dealCust[$val['cca_ctr_id']][$val['cca_au_uid']] = $val;
				}
				//取业务员按添加意向时间所在月份的有效意向跟进记录
				//只要有一天有效就算有效；只有全部为无效(-1)才算无效；存在未审核(0)记录时不判定
				$yxcheckRes = $CrmContract->get(
					'crm_follow f join crm_customer_rank r on f.cfo_ctr_id=r.ccr_ctr_id and f.cfo_au_uid=r.ccr_au_uid',
					['f.cfo_ctr_id,f.cfo_au_uid','COALESCE(MAX(f.cfo_yxcheck), 0) AS cfo_yxcheck'],
					sprintf(" AND f.cfo_ctr_id in (%s) and f.cfo_au_uid in (%s) AND f.cfo_atime between UNIX_TIMESTAMP(DATE_FORMAT(FROM_UNIXTIME(r.ccr_etime),'%%Y-%%m-01')) AND UNIX_TIMESTAMP(DATE_FORMAT(FROM_UNIXTIME(r.ccr_etime),'%%Y-%%m-01') + INTERVAL 1 MONTH - INTERVAL 1 SECOND) group by f.cfo_au_uid,f.cfo_ctr_id",
					implode(',', $ctrIds),implode(',',$auUIds))
				);
				$yxcheckArr = [];
	
				if($yxcheckRes['data']){

					foreach ($yxcheckRes['data'] as $key => $val) {
						//有效(1)；全部为无效(-1)才算无效；存在未审核(0)记录时不判定
						if($val['cfo_yxcheck'] != 0){
							$yxcheckArr[$val['cfo_ctr_id']][$val['cfo_au_uid']] =  (int)$val['cfo_yxcheck'];
						}
					}
					
				}
				
			}
			if($auUIds){
				//每个业务员的意向客户总数 (swhere是一段时间内的意向客户)
				$res = $CrmContract->get('crm_customer_rank',['ccr_au_uid,count(*) as counts'],sprintf(" %s AND ccr_au_uid in (%s) GROUP BY ccr_au_uid",$sWhere,implode(',',$auUIds)));
				if($res['data']){
					$ccrCountArr = [];
					foreach ($res['data'] as $key => $val) {
						$ccrCountArr[$val['ccr_au_uid']] = $val['counts'];
					}
				}
				//算业务员的意向客户 是否成交
				$res = $CrmContract->get('crm_customer_admin join crm_customer_rank on cca_ctr_id=ccr_ctr_id',['ccr_au_uid,count(DISTINCT cca_ctr_id) as counts'],sprintf(" %s AND cca_level_id=5 AND cca_end_time>%d AND ccr_au_uid in (%s) AND cca_au_uid = ccr_au_uid GROUP BY ccr_au_uid",$sWhere,time(),implode(',',$auUIds)));
				if($res['data']){
					$dealCountArr = [];
					foreach ($res['data'] as $key => $val) {
						$dealCountArr[$val['ccr_au_uid']] = $val['counts'];
					}
				}
				//再算出成交率
				foreach ($ccrCountArr as $k => $v) {
					$dealRateArr[$k] = $v>0?round(($dealCountArr[$k]??0)/$v*100,2):0;
				}
			}

			$B2cBase = new B2cBase();
			$res = $B2cBase->get('an_user', ['au_uid', 'au_name']);
			$auArr = array_column($res['data'], 'au_name', 'au_uid');

			$currentAuUid = null;
			$sequenceNumber = 1;
			$lastpage = $page-1;
			$cookielastKey = "page_{$lastpage}_sequence_numbers";
			$cookieKey = "page_{$page}_sequence_numbers";
			// 初始化最后序号数组
			$lastSequenceNumbers = [];

			// 检查是否有对应的 Cookie 数据
			if (isset($_COOKIE[$cookielastKey])) {
				// 从 Cookie 中读取并解码 JSON 数据
				$lastSequenceNumbers = json_decode($_COOKIE[$cookielastKey], true);
			}
			
			foreach($listArr as &$tv)
			{		
				if ($tv['ccr_au_uid'] !== $currentAuUid) {
					// 新的 au_uid，重置序号
					$currentAuUid = $tv['ccr_au_uid'];
					$sequenceNumber =  ($lastSequenceNumbers[$tv['ccr_au_uid']] ?? 0) + 1;
				}
				// 更新最后序号
				$lastSequenceNumbers[$tv['ccr_au_uid']] = $sequenceNumber;
				// 添加序号到当前行
				$tv['sequence_number'] = $sequenceNumber;
				// 序号递增
				$sequenceNumber++;
				$tv['yxcheck'] = $yxcheckArr[$tv['ccr_ctr_id']][$tv['ccr_au_uid']]??'';
				$tv['lfollow'] = $lfollow[$tv['ccr_ctr_id']][$tv['ccr_au_uid']]??[];
				$tv['au_name'] = $auArr[$tv['ccr_au_uid']]??'';
				$tv['sve_name'] = '';
				if($tv['ccr_sve_text']){
					$tv['ccr_sve_text'] = explode(',',$tv['ccr_sve_text']);
					$temp = [];
					foreach ($tv['ccr_sve_text'] as $vv) {
						$temp[] = $sveArr[$vv];
					}
					$tv['sve_name'] = implode(',',$temp);
				}
				//是否成交 2025/11/07
				$tv['is_deal'] = $dealCust[$tv['ccr_ctr_id']][$tv['ccr_au_uid']] ? 1 : 0;
				//成交率
				$tv['deal_rate'] =$tv['is_deal'] && $dealRateArr[$tv['ccr_au_uid']]?$dealRateArr[$tv['ccr_au_uid']].'%':'';
				$tv['ctr_uname'] = $tv['ctr_uname']?:($tv['u_name']?:$tv['u_real_name']);
			}
			unset($tv);	
			// 将最后序号保存到 Cookie
			setcookie($cookieKey, json_encode($lastSequenceNumbers), time() + 3600, "/"); // 有效期1小时
		}
		// $listArr = $this->sortArray($listArr);

		$res  =$CrmContract->get('crm_label',['*'],(" AND cla_type='rank'"));
		LibTpl::Set('rankArr',$res['data']?array_column($res['data'],'cla_name','cla_id'):[]);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
		LibTpl::Set('listArr', $listArr);
		
		if($oWhere&&$hasRule ||$_SESSION['_usergroup']=='all'){
			$res = $this->getSalesUser($oWhere,true,true);
			$saleArr = $res['data'];
		}
	
		LibTpl::Set('sveArr',$sveArr);
		LibTpl::Set('saleArr',$saleArr??[]);
		LibTpl::Set('title', '我的工作台');
		LibTpl::Put();	
	}

	protected function sortArray($array)
	{
		if(!$array) return $array;
		// 分组
		$groups = [];
		foreach ($array as $item) {
			$groups[$item['ccr_au_uid']][] = $item;
		}

		// 对每个分组内的元素根据 cfo_atime 进行降序排序
		foreach ($groups as &$group) {
			usort($group, function($a, $b) {
				return $b['lfollow']['cfo_atime'] <=> $a['lfollow']['cfo_atime'];
			});
		}
		unset($group);
		// 合并所有排序好的分组
		$sortedArray = [];
		foreach ($groups as $group) {
			$sortedArray = array_merge($sortedArray, $group);
		}

		return $sortedArray;
	}

	/**
	 * @method 日计划
	 * @author zhengweihua 
	 * @copyright 2024-08-13
	 */
	public function dayPlan()
	{
		$Params = mvc::$URL_PARAMS;

		$Params['au_id'] = $Params['au_id']?:$_SESSION['_userid'];
		$auUid = $Params['au_id'];
		$listArr = [];
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$where = sprintf(" and cp_ok=0 and cp_au_uid in (%s) ",$auUid);
		$order = " order by cp_ok asc, CASE 
		WHEN cp_from='service' THEN 1
		WHEN cp_from='general' THEN 2 
		WHEN cp_from='register' THEN 3
		ELSE 4
		END,cp_date desc,cp_atime desc";
		$Params['plandate']= !empty($Params['plandate'])?$Params['plandate']:date('Y-m-d');
		$Params['plandate2']= !empty($Params['plandate2'])?$Params['plandate2']:date('Y-m-d').' ~ '.date('Y-m-d');
		foreach ($Params as $key => $val) {
			if(empty($val)) continue;
			switch ($key) {
				case 'keyword':
					$where .=sprintf(" and cp_title like '%%%s%%' or ctr_comname like '%%%s%%' or ctr_uname like '%%%s%%'", $val, $val, $val);
					break;
				case 'status':
					if($val<0) $val = 0;
					$where .=sprintf(" and cp_ok=%d",$val);
					break;
				case 'plandate2':
					$arr = explode('~',$val);
					
					$where .=sprintf(" and cp_date>='%s' and cp_date<='%s'",date('Ymd',strtotime($arr[0])),date('Ymd',strtotime($arr[1])));
					break;
				case 'cp_from':
					$where .=sprintf(" and cp_from='%s'",$val);
					break;
			}
		}

		$table = 'crm_plan 
		left join crm_customer on cp_ctr_id = ctr_id
		left join crm_customer_admin on cca_ctr_id = cp_ctr_id
		left join ypdb_write.yp_user on ctr_uid = u_id
		left join fad_link_fct_sve on fsl_id = cp_from_id
		left join fad_service on fsl_sve_id =sve_id';
		$CrmBase = new CrmBase();
		$res = $CrmBase->get($table,['count(*) as counts'],$where,true);

		$total = $res['data']['counts'];
		if($total>0){
			$res = $CrmBase->get($table,['*'],sprintf("%s %s limit %d,%d",$where,$order, ($page-1)*$perPage, $perPage));
			$listArr = $res['data'];
		}
		//文本类型的
		
		// $res = $CrmBase->get('crm_plan',['*'],sprintf(" AND cp_from='general' AND cp_ctr_id=0 AND cp_au_uid=%d AND cp_date='%s'",$auUid,date('Ymd',strtotime($Params['plandate']))));

		// LibTpl::Set('txtPlanArr',$res['data']);

		$searchUser = [];
		$oWhere = '';
		if ($_SESSION['_usergroup'] == 'shangji') {
			$searchUser = $_SESSION['_xiajiUid'];
			$oWhere = sprintf(" AND au_uid in (%s)",implode(',',$searchUser));
		}
		
		if($oWhere||$_SESSION['_usergroup']=='all'){
			$res = $this->getSalesUser($oWhere,true,true);
			$searchSaleArr = $res['data'];
			LibTpl::Set('searchSaleArr',$searchSaleArr);
		}

		$res = $this->getSalesUser('',false);
		// var_dump($res['data']);die;
		LibTpl::Set('saleArr',$res['data']);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
		LibTpl::Set('listArr', $listArr);

		LibTpl::Set('fromArr',['service'=>'系统提醒','general'=>'自主加入','register'=>'新注册用户']);
		LibTpl::Set('auUid',$auUid);
		LibTpl::Set('title', $res['data'][$auUid]['au_name'].'-工作计划');
		LibTpl::Put();	
	}

	/**
	 * @method 日总结
	 * @author zhengweihua 
	 * @copyright 2024-08-13
	 */
	public function daySummary()
	{
		$Params = mvc::$URL_PARAMS;

		$Params['date'] = $Params['date']??date('Y-m-1').' ~ '.date('Y-m-d');
		// 意向客户
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$hasRule =1;
		$searchUser = [];
		if ($_SESSION['_usergroup'] == 'shangji') {
			$searchUser = $_SESSION['_xiajiUid'];
		} elseif (in_array($_SESSION['_usergroup'],['yewu','kefu'])) {
			$searchUser[] =  $_SESSION['_userid'];
			$hasRule =0;
		}elseif(in_array($_SESSION['_usergroup'],['all'])){
			$where = '';
		}
		if($_SESSION['_usergroup']=='all' && $_SESSION['_userid']==151295){
			$res = $this->getSalesUser('',true,true);
			$key = array_search('选择 [跑街业务员] 所有人', $res['data']['跑街业务员']);
			$Params['ccr_au_uid'] = $Params['ccr_au_uid']??$key;
		}else{
			$Params['ccr_au_uid'] =  $Params['ccr_au_uid']??(string)$_SESSION['_userid'];
		}

		if($searchUser){
			// $where .= sprintf(" AND rpt_au_uid in (%s)",implode(',',$searchUser));
			$oWhere = sprintf(" AND au_uid in (%s)",implode(',',$searchUser));
		}
		foreach ($Params as $key => $val) {
			if(!$val) continue;
			switch ($key) {
				case 'date':
					$arr = explode(' ~ ',$val);
					$val1 = date('Ymd',strtotime($arr[0]));
					$val2 = date('Ymd',strtotime($arr[1]));
					$where .= sprintf(" AND rpt_date>=%d AND rpt_date<=%d",$val1,$val2);
				break;
				case 'ccr_au_uid':
					$where .= sprintf(" AND rpt_au_uid IN (%s)",$val);
					break;
			}
		}


		$CrmBase = new CrmBase();

		$res = $CrmBase->get('crm_report',['count(*) as counts'],$where,true);
		$total = $res['data']['counts'];
		$listArr = [];
		if($total>0){
			$res = $CrmBase->get('crm_report',['*'],sprintf(" %s order by rpt_date desc limit %d,%d",$where, ($page-1)*$perPage, $perPage));
			$listArr = $res['data'];

			$B2cBase = new B2cBase();
			$res = $B2cBase->get('an_user', ['au_uid', 'au_name']);
			$auArr = array_column($res['data'], 'au_name', 'au_uid');

			foreach($listArr as &$tv)
			{
				$tv['au_name'] = $auArr[$tv['rpt_au_uid']];
				// 创建一个新的 DateTime 对象，并使用从原始字符串解析出的年、月、日
				$date = substr($tv['rpt_date'], 0, 4) . '-' . substr($tv['rpt_date'], 4, 2) . '-' . substr($tv['rpt_date'], 6, 2);
				$tv['rpt_date'] =$date;
			}
			unset($tv);	

		}

		if($hasRule && $oWhere||$_SESSION['_usergroup']=='all'){
			$res = $this->getSalesUser($oWhere,true,true);
			$saleArr = $res['data'];
		}
		
		LibTpl::Set('saleArr',$saleArr??[]);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
		LibTpl::Set('listArr', $listArr);
		LibTpl::Set('title', '日总结');
		LibTpl::Put();
	}

	/**
	 * @method 完成计划
	 * @author zhengweihua 
	 * @copyright 2024-01-29
	 */
	public function finshPlan()
	{
		if($_SERVER['REQUEST_METHOD']=='POST'){
			$cpId= (int)$_POST['cp_id'];
			if($cpId){
				$CrmBase = new CrmBase();
				$data = ['cp_ok'=>1,'cp_ok_time'=>time(),'cp_ok_au_id'=>$_SESSION['_userid']];
				$res = $CrmBase->set('crm_plan',$data , sprintf(' and cp_id=%d', $cpId));
				LibFc::ajaxJsonEncode($res);
			}
		}
	}

	function main()
	{
		$PjlBase = new PjlBase();
		$where = sprintf(" and dwi_dco_id=%d  and dwi_dwo_uid =%d order by dwi_invcode", $_SESSION['_dcoid'], $_SESSION['_userid']);
		$res = $PjlBase->get('dl_worker_invcode', ['*'], $where);
		$invArr = $res['data'];
		LibTpl::Set('invArr', $invArr);

		$res = $PjlBase->get('dl_company left join dl_company_target on dct_dco_id=dco_id', ['*'], sprintf(' and dco_id=%d and dct_begin <=%d and dct_end >=%d', $_SESSION['_dcoid'], time(), time()), true);
		$comArr = $res['data'];

		//代理区域
		$res = $PjlBase->get('dl_company_target_pcts JOIN yp_province_city ON pc_id=dctp_pc_id', ['pc_name'], sprintf(' and dctp_dct_id=%d', $comArr['dct_id']));
		$comArr['pc_names'] = array_column($res['data'], 'pc_name');

		LibTpl::Set('comArr', $comArr);

		//我的提成
		$tjTimeArr = [
			'thism'=>date('Y-m-01').' ~ '.date('Y-m-d'),
			'lastm'=>date('Y-m-01', strtotime('-1 month')).' ~ '.date('Y-m-d', strtotime(date('Y-m-01'))-1),
			'thisy'=>date('Y-01-01').' ~ '.date('Y-m-d'),
			'total'=>''
		];

		$tjArr = [];

		$rule04 = LibFc::checkDlRule('DL04', false);
		$tjType = ['self'=>sprintf(" and dml_dco_id=%d  and dml_dwo_uid =%d", $_SESSION['_dcoid'], $_SESSION['_userid'])];
		if($rule04) $tjType['com'] = sprintf(" and dml_dco_id=%d", $_SESSION['_dcoid']);

		foreach($tjTimeArr as $k=>$v)
		{
			foreach($tjType as $kk=>$where)
			{
				if(!empty($v))
				{
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and dml_atime >= %d and dml_atime <= %d", strtotime($t[0]), strtotime($t[1].' 23:59:59'));
				}
				$res = $PjlBase->get('dl_order_list', ['sum(dml_money_pay) as dml_money_pay, sum(dml_money_selftc) as dml_money_selftc, sum(dml_money_ywytc) as dml_money_ywytc'], $where, true);
				$tjArr[$kk][$k] = $res['data'];
			}
		}
		LibTpl::Set('tjTimeArr', $tjTimeArr);
		LibTpl::Set('tjArr', $tjArr);
		LibTpl::Set('title',  '工作台-'.mvc::$cfg['TITLE']);
		LibTpl::Put();
	}


	function pjlReport()
	{
		exit('暂停公开');
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->get('index/getTjReportUrl', ['site'=>'PJL', 'uid'=>$_SESSION['_userid']]);
		header("Location: ".$res['data']);
	}

	/**
	 * @method 获取最近一个月统计数据
	 * @author zhengweihua 
	 * @copyright 2023-05-22
	 */
	public function getRecentTjList()
	{	
		$Params =  mvc::$URL_PARAMS;
		$end = date('Ymd',time());
		$start = date('Ymd',strtotime("-1 month"));
		$shopId = LibFc::Int($Params['shop_id']);
		$showRes = (new BaseDb(mvc::$cfg['DB']['API_TJ']))->get('tj_pjl_shop_date',['tpsd_date','tpsd_devcode_count','tpsd_pv_count'],sprintf(" and tpsd_shop_id = %d and tpsd_date between '%s' and '%s' order by tpsd_date desc",$shopId,$start,$end));
		LibFc::ajaxJsonEncode($showRes);
	}

	/**
	 * @method 业务员目标
	 * @author zhengweihua 
	 * @copyright 2024-08-08
	 */
	public function userTarget()
	{
		LibFc::checkDlRule('DL15');
		$Params = mvc::$URL_PARAMS;
		if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['months']){

			$dataAr = [
				'months'=>$_POST['months'],
				'year'=>$_POST['year']
			];
			$CrmContract = new CrmContract();
			$res = $CrmContract->setUserTarget($dataAr);
			LibTpl::Success('操作成功');
		}
		if(!isset($Params['year'])){
			$Params['year'] = date('Y');
		}
		$startYears = 2024;
		$months = range(1,12);
		$monthsArr = [];
		foreach ($months as $val) {
			$key = str_pad($val,2,0,STR_PAD_LEFT);
			$monthsArr[$key] = $val.'月';
		}
		$yearsArr = range($startYears,date('Y')+1);
		$arr = [];
		if(in_array($_SESSION['_usergroup'],['shangji','all'])){

			if($_SESSION['_usergroup']=='all' && $_SESSION['_userid']==151295){
				
				$res = $this->getSalesUser('',true,true);
				$key = array_search('选择 [跑街业务员] 所有人', $res['data']['跑街业务员']);
				$Params['usr_id'] = $Params['usr_id']??$key;
			}
			$oWhere = '';
			$sWhere = '';
			if($Params['usr_id']){
				$sWhere .= sprintf(" AND au_uid in (%s)",$Params['usr_id']);
			}
			if($_SESSION['_usergroup']=='shangji')
			{
				$userids = implode(',',$_SESSION['_xiajiUid']);
				$oWhere .= sprintf(" AND au_uid in (%s)",$userids);

				$B2cBase = new B2cBase();
				$res = $B2cBase->get('an_user',['au_uid,au_name'],sprintf(" %s AND au_status=1 AND au_uid in (%s)",$sWhere,$userids));
				$userArr = $res['data'];

				$where = sprintf(' AND ust_au_uid in (%s)',$userids);
			}else{
				$res = $this->getSalesUser($sWhere,false,true);
				$userArr = $res['data'];
			}
			if($Params['year']){
				$start1 = $Params['year'].'01';
				$end1 = $Params['year'].'12';
				$where .= sprintf(" AND ust_month>=%d AND ust_month<=%d",(int)$start1,(int)$end1);
			}
		
			$CrmBase = new CrmBase();
			$res = $CrmBase->get('user_sales_target',['*'],$where);
			$targetArr = [];
			foreach ($res['data'] as $key => $val) {
				
				$targetArr[$val['ust_au_uid']][$val['ust_month']] = $val['ust_money'];
			}
		
			foreach ($userArr as $key => $val) {
				$val['month'] = $targetArr[$val['au_uid']]??[];
				$arr[] = $val;
			}
		
		}
		$res = $this->getSalesUser($oWhere,true,true);
		$salesArr =$res['data'];
		LibTpl::Set('salesArr',$salesArr);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('yearsArr',$yearsArr);
		LibTpl::Set('monthsArr',$monthsArr);
		LibTpl::Set('arr',$arr);
		LibTpl::Put();
	}

	/**
	 * @method 意向客户
	 * @author zhengweihua 
	 * @copyright 2024-08-08
	 */
	public function yixiangCtr()
	{
		
		LibTpl::Put();
	}

	/**
	 * @method 保存文本计划
	 * @author zhengweihua 
	 * @copyright 2024-08-08
	 */
	public function saveTxtPlan()
	{
		if($_SERVER['REQUEST_METHOD']=='POST')
		{
			$CrmBase = new CrmBase();

			$date = date('Ymd',strtotime($_POST['plandate']));
			foreach ($_POST['txt'] as $key => $val) {
				if ($val) {
					if ($key > 0) {
						$dataArr = ['cp_title' => $val, 'cp_date' => $date, 'cp_by_uid' => $_SESSION['_userid'], 'cp_atime' => time()];
						$CrmBase->set('crm_plan', $dataArr, sprintf(" AND cp_id=%d", $key));
					} else {
						$dataArr = [
							'cp_au_uid' => $_SESSION['_userid'],
							'cp_title' => $val,
							'cp_date' => $date,
							'cp_by_uid' => $_SESSION['_userid'],
							'cp_atime' => time()
						];
						$CrmBase->add('crm_plan', $dataArr);
					}
				} else {
					if ($key > 0) {
						$CrmBase->del('crm_plan', sprintf(" AND cp_id=%d", $key));
					}
				}
			}

			LibFc::ReturnJson(true,'操作成功');
		}
	}

	/**
	 * @method 搜索客户
	 * @author zhengweihua 
	 * @copyright 2024-08-12
	 */
	public function searchCustom()
	{
		$Params = mvc::$URL_PARAMS;
		$CrmBase = new CrmBase();
		if(!$Params['word'])
		{
			LibFc::ReturnJson(true,[]);
		}
		$res = $CrmBase->get('crm_customer',['ctr_id,ctr_comname'],sprintf(" AND ctr_comname like '%%%s%%' limit 10",LibFc::Escape($Params['word'])));

		LibFc::ReturnJson(true,$res['data']);
		
	}

	/**
	 * @method 添加日记事
	 * @author zhengweihua 
	 * @copyright 2024-08-13
	 */
	public function addReport()
	{
		if($_SERVER['REQUEST_METHOD']=='POST')
		{

			if(!$_POST['rpt_date']||!$_POST['rpt_text']){
				LibFc::ReturnJson(false,'参数缺失');
			}
			$CrmBase = new CrmBase();

			$date = date('Ymd',strtotime($_POST['rpt_date']));
			$rpt_text = LibFc::Escape($_POST['rpt_text']);
			$rpt_id = (int)$_POST['rpt_id'];
			$rpt_au_uid = (int)$_POST['rpt_au_uid'];
			$data = [
				'rpt_text'=>$rpt_text,
				'rpt_date'=>$date,
				'rpt_au_uid'=>$rpt_au_uid?:$_SESSION['_userid'],	
				'rpt_time'=>time(),
			];
			
			if($rpt_id){
				$res = $CrmBase->set('crm_report',$data,sprintf(" AND rpt_id=%d",$rpt_id));
			}else{
				$res = $CrmBase->add('crm_report',$data);
			}
			LibFc::ajaxJsonEncode($res);
		}
	}

	public function delReport()
	{
		if($_SERVER['REQUEST_METHOD']=='POST')
		{
			$rpt_id = (int)$_POST['rpt_id'];

			$CrmBase = new CrmBase();
			
			$res = $CrmBase->del('crm_report',sprintf(" AND rpt_id=%d",$rpt_id));
			LibFc::ajaxJsonEncode($res);
		}
	}


	/**
	 * @method CRM机器人管理
	 * @author zhengweihua 
	 * @copyright 2026-05-25
	 */
	public function robotSet()
	{
		$Params = mvc::$URL_PARAMS;
        $B2cBase = new B2cBase();
       
        //获取当前用户机器人
        $res = $B2cBase->get('wx_robot left join wx_robot_token on wr_wrt_id= wrt_id', ['*',"MD5(CONCAT('Y@', wrt_id, '@P', DATE_FORMAT(NOW(), '%Y-%m-%d'))) as md5key"], sprintf(" and wr_totype='crm' and wr_uid=%d and wr_id=%d",$_SESSION['_userid'], $Params['wr_id']),true);
        if(empty($res['data'])) return LibFc::ReturnJson(false,'参数错误');
      
        //微信号信息
        $wxinfo = $res['data']['wrt_wxinfo']?json_decode($res['data']['wrt_wxinfo'], true):[];
        LibTpl::Set('wxinfo',$wxinfo);
       
        $robotArr = $res['data'];
            
        //请求总接口
        if($res['data']['wrt_id'])
        {
            $LibYpApi = new LibYpApi();
            $LibYpApi->Get('index/chkRobotStatus',['wrt_id'=>$res['data']['wrt_id']]);
        }
		if(!empty($robotArr['wr_uid']))
		{
			$LibYpApi = new LibYpApi();
			$getData = ['uid' => $robotArr['wr_uid']];
			$res  = $LibYpApi->Get('user/getUserById',$getData);
			$robotArr['user_name'] = $res['data']['u_name'];
		}
        LibTpl::Set('title', '机器人管理');
        LibTpl::Set('robotArr', $robotArr);  
        LibTpl::Put();
	}
}
