<?php
/**
  * @method API统计
  * @author soul
  * @copyright 2018/10/31
  */
class PjltjReport extends PjltjBase
{
	
	/**
	  * @method 车型库同步到统计库
	  * @author soul
	  * @copyright 2020/6/12
	  * @return 
	  */
	public function updateYpcModelToTjdb()
	{
		$Ypc2Base = new Ypc2Base();
		$this->TjDb->Begin();
		$fastTableArr = [
			'bc_brand'=>['pk'=>'brand_id', 'per'=>1000],
			'bc_make'=>['pk'=>'make_id', 'per'=>1000],
			'bc_model1'=>['pk'=>'mod1_id', 'per'=>1000],
			'bc_model2'=>['pk'=>'mod2_id', 'per'=>600],
			//'bc_model3'=>['pk'=>'mod3_id', 'per'=>600]
		];
		foreach($fastTableArr as $table=>$cfg){
			//不能用 truncate table 不纳入事务
			$this->del($table, ' and 1=1');
			for($page = 1; $page <= 10000; $page++){
				$locRes = $Ypc2Base->get($table, ['*'], sprintf(" order by %s limit %d,%d", $cfg['pk'], ($page-1)*$cfg['per'], $cfg['per']));
				$localArr = $locRes['data'];
				if(!is_array($localArr)) return LibFc::ReturnData(false, $table.' 数据记录有误，同步失败');
				if(!empty($localArr)){	
					$this->addAny($table, array_keys($localArr[0]), $localArr);
				}else{
					break;
				}
			}
		}
		$this->TjDb->End();
		return LibFc::ReturnData(true);
	}

	//自动赋值无解码的车型ID
	function autoBindModIds($tjtable, $beginTime, $endTime)
	{
		$cache = [];
		$LibYpApi = new LibYpApi();
		$res = $this->get('at_tongji_reg', ['tr_act'], " and tr_ismod3 = 1");
		$acts = array_column($res['data'], 'tr_act');
		$where = sprintf(" and tj_act IN ('%s') and tj_time >= %d and tj_time < %d AND JSON_CONTAINS_PATH(tj_param, 'one', '$.mod3_id', '$.mod3Id', '$.m3ids') = 0 AND LENGTH(JSON_UNQUOTE(tj_param->'$.vin')) = 17 group by vin", implode("','", $acts), $beginTime, $endTime);
		$res = $this->get($tjtable, ["UPPER(JSON_UNQUOTE(tj_param->'$.vin')) vin, GROUP_CONCAT(tj_time) tj_times"], $where);
		if($res['data']){
			$vinTimes = array_column($res['data'], 'tj_times', 'vin');
			$vins = array_keys($vinTimes);
			$where = sprintf(" and tj_act IN ('%s') and tj_date >= %d and tj_date <= %d AND JSON_CONTAINS_PATH(tj_param, 'one', '$.mod3_id', '$.mod3Id', '$.m3ids') = 1 AND JSON_UNQUOTE(tj_param->'$.vin') in ('%s')", implode("','", $acts), date('Ymd', $beginTime), date('Ymd', $endTime), implode("','", $vins));
			$res = $this->get($tjtable, ["UPPER(JSON_UNQUOTE(tj_param->'$.vin')) vin, JSON_UNQUOTE(tj_param->'$.m3ids') m3ids, JSON_UNQUOTE(tj_param->'$.mod3Id') mod3Id"], $where);
			$setSql = [];
			$okvins = [];
			foreach($res['data'] as $v){
				$m3ids = [];
				if($v['mod3Id']){
					$m3ids[] = (int) $v['mod3Id'];
				}else if($v['m3ids']){
					foreach(json_decode($v['m3ids'], true) as $vv){
						if($vv) $m3ids[] = (int) $vv;
					}
				}
				if(empty($m3ids)) continue;
				if(empty($vinTimes[trim($v['vin'])])){
					var_dump($v['vin'], $vinTimes);exit;
				}
				$okvins[] = $v['vin'];
				$setSql[] = sprintf("UPDATE %s SET tj_param = JSON_SET(tj_param, '$.m3ids', JSON_ARRAY('%s')) WHERE tj_time in (%s) and JSON_UNQUOTE(tj_param->'$.vin')='%s' AND JSON_CONTAINS_PATH(tj_param, 'one', '$.mod3_id', '$.mod3Id', '$.m3ids') = 0", $tjtable, implode("','", $m3ids), $vinTimes[trim($v['vin'])], $v['vin']);
			}
			
			if($setSql) $this->exeAnySql($setSql, false);
			$novins = array_diff($vins, $okvins);
			//重新解码
			foreach($novins as $vin){
				$m3ids = [];
				if(isset($cacheVin[$vin])){
					$m3ids = $cacheVin[$vin];
				}else{
					$res = $LibYpApi->get('vin/decodeVin', ['vin'=>$vin], [], true);
					if($res['status'] && $res['data']['from'] == 'ypc'){
						$m3ids = array_column($res['data']['model'], 'mod3_id');
					}else{
						$m3ids = [];
					}
					$cacheVin[$vin] = $m3ids;
				}
				echo $vin.'#解码'.implode(',', $m3ids)."\r\n";
				if(empty($vinTimes[trim($vin)])){
					var_dump($vin, $vinTimes);exit;
				}
				$setSql[] = sprintf("UPDATE %s SET tj_param = JSON_SET(tj_param, '$.m3ids', JSON_ARRAY('%s')) WHERE tj_time in (%s) and JSON_UNQUOTE(tj_param->'$.vin')='%s' AND JSON_CONTAINS_PATH(tj_param, 'one', '$.mod3_id', '$.mod3Id', '$.m3ids') = 0", $tjtable, implode("','", $m3ids), $vinTimes[trim($vin)], $vin);
				if(count($setSql)%100 == 0){
					$this->exeAnySql($setSql, false);
					$setSql = [];
				}
			}
			if($setSql) $this->exeAnySql($setSql, false);
		}
		return LibFc::ReturnData(true);
	}

	/**
	  * @method 初始化车型相关原始统计
	  * @author soul
	  * @copyright 2020/4/30
	  * @return 
	  */
	public function initModOrgTj()
	{
		//从哪个日期开始
		$Ypc2Base = new Ypc2Base();
		$YpwBase = new YpwBase();
		$YpcVin = new YpcVin();
		$OthPct = new OthPct();
		$LibYpApi = new LibYpApi();
		$minTime = strtotime('20250101');
		$maxTime = time();
		//总表的最大时间
		$tjres = $this->get('at_tongji_all', ["max(tj_time) max_time"], '', true);
		$oldMaxtime = $tjres['data']['max_time'];

		$tjtable = 'at_tongji';
		$res = $this->get('at_tongji_mod', ['max(atm_atime) as atm_atime'], '', true);
		$lastTime = $res['data']['atm_atime']?? $minTime;
		
		$res = $this->get('at_tongji_reg', ['tr_act'], " and tr_ismod3 = 1");
		$acts = array_column($res['data'], 'tr_act');

		$cache = [];
		//车型信息
		$res = $Ypc2Base->get('bc_model3', ['mod3_id', 'mod3_mod2_id', 'mod3_engine', 'mod3_transmission', 'mod3_drive'], '');
		$mod3Arr = array_column($res['data'], null, 'mod3_id');
		while(1){
			$runbtime = time();

			//高峰10分钟
			$per = date('H', $lastTime) < 8 || date('H', $lastTime) > 18? 3600: 600;
			//if($lastTime < $oldMaxtime) $per = 600;
			$endTime = $lastTime + $per;
			if($endTime > $maxTime) $endTime = $maxTime;
			
			//是否需要切换表
			if($lastTime <= $oldMaxtime && $endTime > $oldMaxtime) $endTime = $oldMaxtime+1;
			if($endTime <= $oldMaxtime) $tjtable = 'at_tongji_all';
			
			//自动赋值无解码的车型ID
			$this->autoBindModIds($tjtable, $lastTime, $endTime);
			
			$this->TjDb->Begin();
			//清空历史
			$this->del('at_tongji_mod', ' and atm_atime >= '.$lastTime);

			$where = sprintf(" and tj_act IN ('%s') and tj_time >= %d and tj_time < %d and JSON_CONTAINS_PATH(tj_param, 'one', '$.mod3_id', '$.mod3Id', '$.m3ids') = 1 order by tj_time", implode("','", $acts), $lastTime, $endTime);
			$tjres = $this->get($tjtable.' LEFT JOIN ips ON ip = tj_ip', ["tj_date, tj_uid, tj_ip, tj_shopid, tj_from, tj_param, tj_time, province, city"], $where);
			//echo date('Y-m-d H:i', $endTime).'=>count：'.count($tjres['data'])."\r\n";
			$addArr = [];
			$setSql = [];
			foreach($tjres['data'] as $k=>$v){
				$tj_param = json_decode($v['tj_param'], true);
				$v['vin'] = $tj_param['vin'] && strlen($tj_param['vin']) == 17 ? $tj_param['vin']: '';
				$mod3Id = 0;
				if($tj_param['mod3_id']){
					$mod3Id = $tj_param['mod3_id'];
				}else if($tj_param['mod3Id']){
					$mod3Id = $tj_param['mod3Id'];
				}else if($tj_param['m3ids']){
					$mod3Id = $tj_param['m3ids'][0];
				}
				if(empty($mod3Id) || !isset($mod3Arr[$mod3Id])) continue;
				$mod = $mod3Arr[$mod3Id];

				if(stripos($v['tj_from'], 'WXROBOT') !== false || stripos($v['tj_from'], 'API') !== false){
					$v['tj_ip'] = '';
					$v['province'] = 0;
					$v['city'] = 0;
				}else{
					if($v['province'] === null){
						if($cache['ip'][$v['tj_ip']]){
							$ipinfo = $cache['ip'][$v['tj_ip']];
						}else{
							$res = $OthPct->getIpPCT($v['tj_ip'], 0);
							$ipinfo = $res['data'];
							$cache['ip'][$v['tj_ip']] = $ipinfo;
							if($ipinfo['pctids']){
								$set = ['ip'=>$v['tj_ip'], 'province'=>$ipinfo['pctids'][0], 'city'=>(int) $ipinfo['pctids'][1], 'addr'=>implode('-', $ipinfo['pcts'])];
							}else{
								$set = ['ip'=>$v['tj_ip'], 'addr'=>$ipinfo['country']];
							}
							$this->replace('ips', $set);
						}

						if($ipinfo['pctids']){
							$v['province'] = $ipinfo['pctids'][0];
							$v['city'] = $ipinfo['pctids'][1];
						}
					}
					//尝试用户省市
					if($v['province'] === null && $v['tj_uid'] > 0){
						if($cache['uid'][$v['tj_uid']]){
							$ipinfo = $cache['ip'][$v['tj_ip']];
						}else{
							$res = $YpwBase->get('yp_user_ext', ['ui_province', 'ui_city'], sprintf(" and ui_uid=%d", $v['tj_uid']), true);
							$ipinfo = $res['data'];
							$cache['uid'][$v['tj_uid']] = $ipinfo;
						}
						if($ipinfo['ui_province']){
							$v['province'] = $ipinfo['ui_province'];
							$v['city'] = $ipinfo['ui_city'];
						}
					}
				}

				//规整来源 跑街令PJL 宜配YP 目录SUPER 机器人WXROBOT 接口API
				$v['from'] = 'OTH';
				if(stripos($v['tj_from'], 'PJL') === 0 || in_array($v['tj_from'], ['PJD'])){
					$v['from'] = 'PJL';
				}else if(stripos($v['tj_from'], 'YP') === 0){
					$v['from'] = 'YP';
				}else if(stripos($v['tj_from'], 'SUPER') !== false || stripos($v['tj_from'], 'PJDGZH') !== false){
					$v['from'] = 'SUPER';
				}else if(stripos($v['tj_from'], 'WXROBOT') !== false){
					$v['from'] = 'WXROBOT';
				}else if(stripos($v['tj_from'], 'API') !== false){
					$v['from'] = 'API';
				}
				$v['wxinfo'] = [];
				$v['atm_wxid'] = '';
				if($tj_param['wxid']){
					$v['atm_wxid'] = $tj_param['wxid'];
					$v['wxinfo'] = ['roomid'=>$tj_param['roomid']?? '', 'wxid'=>$tj_param['wxid'], 'nickname'=>$tj_param['nickname']?? ''];
				}
				$addArr[] = [
					'atm_date'=>$v['tj_date'],	
					'atm_mod3_id'=>$mod['mod3_id'],	
					'atm_mod2_id'=>$mod['mod3_mod2_id'],	
					'atm_vin'=>$v['vin'],	
					'atm_engine'=>$mod['mod3_engine'],
					'atm_drive'=>$mod['mod3_drive'],
					'atm_transmission'=>$mod['mod3_transmission'],
					'atm_uid'=>$v['tj_uid'],	
					'atm_wxid'=>$v['atm_wxid'],	
					'atm_wxinfo'=>json_encode($v['wxinfo'], JSON_UNESCAPED_UNICODE),	
					'atm_shop_id'=>$v['tj_shopid'],	
					'atm_shop_id'=>$v['tj_shopid'],	
					'atm_province'=>(int) $v['province'],	
					'atm_city'=>(int) $v['city'],	
					'atm_from'=>$v['from'],	
					'atm_atime'=>$v['tj_time'],	
				];

				if(count($addArr) % 500 === 0){
					$this->addAny('at_tongji_mod', array_keys($addArr[0]), $addArr);
					$addArr = [];
				}
			}
			if($addArr) $this->addAny('at_tongji_mod', array_keys($addArr[0]), $addArr);
			if($setSql) $this->exeAnySql($setSql);

			$this->TjDb->End();
			echo date('Y-m-d H:i', $endTime).'=>count：'.count($tjres['data']).' run：'.(time() - $runbtime)."s\r\n";
			$lastTime = $endTime;
			if($endTime >= $maxTime) break;
		}
		$this->fenpeiModTjCity();
		return LibFc::ReturnData(true);
	}


	//无地区的按照当日跑街令已有地区的比例分配
	function fenpeiModTjCity()
	{
		//截止日期（不能含未完成的部分）
		$res = $this->get('at_tongji_mod', ["max(atm_date) as b_date"], '', true);
		$maxDate = date('Ymd', strtotime($res['data']['b_date']) - 3600*24);
		//需要处理的日期
		$nres = $this->get('at_tongji_mod', ["distinct atm_date"], sprintf(" and atm_date <=%d and atm_city = 0", $maxDate));
		foreach($nres['data'] as $v){
			$date = $v['atm_date'];
			$runbtime = time();
			$this->TjDb->Begin();
			$res = $this->get('at_tongji_mod', ["atm_id"], sprintf(" and atm_date=%d and atm_city = 0", $date));
			$noids = array_column($res['data'], 'atm_id');
			$totalNo = count($noids);
			shuffle($noids);
			$res = $this->get('at_tongji_mod', ["atm_province, atm_city, count(*) city_count"], sprintf(" and atm_date=%d and atm_city > 0 and atm_from in ('PJL','YP') group by atm_city order by count(*) desc", $date));
			$hasArr = $res['data'];
			$totalHas = array_sum(array_column($hasArr, 'city_count'));
			foreach($hasArr as $vv){
				$need = ceil($vv['city_count']/$totalHas*$totalNo);
				$setids = [];
				foreach($noids as $kk=>$aid){
					$setids[] = $aid;
					unset($noids[$kk]);
					$need--;
					if($need == 0) break;
				}
				if($setids){
					$chunkArr = array_chunk($setids, 100);
					foreach($chunkArr as $chunk){
						$this->set('at_tongji_mod', ['atm_province'=>$vv['atm_province'], 'atm_city'=>$vv['atm_city'], 'atm_pcauto'=>1], sprintf(" and atm_id in (%s)", implode(',', $chunk)));
					}
				}
			}
			$this->TjDb->End();
			echo date('Y-m-d H:i').'=>分配城市'.$date.' run：'.(time() - $runbtime)."s\r\n";
		}
		return LibFc::ReturnData(true);
	}


	/**
	  * @method 行业报表-（不含当日）
	  * @author soul
	  * @copyright 2020/4/30
	  * @return 
	  */
	public function initReportIndustry()
	{
		$this->fenpeiModTjCity();
		$YpwBase = new YpwBase();
		$res = $YpwBase->getKeyVal('at_report_rate');
		$hotRate = $res['data']? $res['data']: 1.5;
		//从哪个日期开始
		$firstDate = '20250101';
		$res = $this->get('at_report_industry_day', ['max(ari_date) as b_date'], '', true);
		if(!empty($res['data']['b_date'])){
			$firstDate = date('Ymd', strtotime($res['data']['b_date'])+3600*24);
		}else{
			$res = $this->get('at_tongji_mod', ["min(atm_date) as b_date"], '', true);
			if(!empty($res['data']['b_date'])){
				$firstDate = $res['data']['b_date'];
			}
		}

		$res = $this->get('at_tongji_mod', ["max(atm_date) as b_date"], '', true);
		$maxDate = date('Ymd', strtotime($res['data']['b_date']) - 3600*24);
		
		$dateArr = [];
		$dateArr = array_map( function ($n) { return date('Ymd', $n);}, range(strtotime($firstDate), strtotime($maxDate)-24*3600, 24 * 3600));
		asort($dateArr);
		foreach($dateArr as $date){
			if($date == date('Ymd')) break;
			$this->TjDb->Begin();
			//清空历史
			$this->del('at_report_industry_day', ' and ari_date = '.$date);
			$addSql = sprintf("INSERT INTO at_report_industry_day(ari_date, ari_mod2_id, ari_province, ari_city, ari_from, ari_count)
				SELECT atm_date, atm_mod2_id, atm_province, atm_city, atm_from, COUNT(*) pv_count
				FROM at_tongji_mod where atm_date=%d GROUP BY atm_mod2_id, atm_province, atm_city, atm_from ORDER BY COUNT(*) DESC", $date);
			$this->exeAnySql([$addSql]);
			$this->TjDb->End();
		}

		//月报表
		$firstDate = '202501';
		$res = $this->get('at_report_industry_month', ['max(ari_date) as b_date'], '', true);
		if(!empty($res['data']['b_date'])){
			$firstDate = $res['data']['b_date'];
		}else{
			$res = $this->get('at_report_industry_day', ["min(ari_date) as b_date"], '', true);
			if(!empty($res['data']['b_date'])){
				$firstDate = date('Ym', strtotime($res['data']['b_date']));
			}
		}
		if($firstDate){
			$res = $this->get('at_report_industry_day', ["max(ari_date) as b_date"], '', true);
			$maxDate = date('Ym', strtotime($res['data']['b_date']));
			
			$current = strtotime($firstDate.'01');
			$endTime = strtotime($maxDate.'01');
			while ($current <= $endTime) {
				$month = date('Ym', $current);
				$current  = strtotime('+1 month', $current);
				$this->TjDb->Begin();
				//清空历史
				$this->del('at_report_industry_month', ' and ari_date = '.$month);
				$addSql = sprintf("INSERT INTO at_report_industry_month(ari_date, ari_mod2_id, ari_province, ari_city, ari_from, ari_count, art_hotpv)
				SELECT %d, ari_mod2_id, ari_province, ari_city, ari_from, SUM(ari_count), CEIL(SUM(ari_count)*%s) FROM at_report_industry_day
				WHERE ari_date >= %d AND ari_date < %d GROUP BY ari_mod2_id, ari_province, ari_city, ari_from", $month, $hotRate, $month.'01', date('Ymd', $current));
				$this->exeAnySql([$addSql]);
				$this->TjDb->End();
			}
		}
		//多维度月报表 品牌:brand 品牌_车系:brand_model1 品牌_车代:brand_model2 省份:province 品牌_省份:brand_province  省_市:province_city
		$typeArr = ['brand','brand_model1','brand_model2','province','brand_province','province_city'];
		foreach($typeArr as $type){
			$firstDate = '202501';
			$res = $this->get('at_report_industry_item', ['max(ari_date) as b_date'], sprintf(" and ari_type = '%s'", $type), true);
			if(!empty($res['data']['b_date'])){
				$firstDate = $res['data']['b_date'];
			}else{
				$res = $this->get('at_report_industry_month', ["min(ari_date) as b_date"], '', true);
				if(!empty($res['data']['b_date'])){
					$firstDate = $res['data']['b_date'];
				}
			}
			if($firstDate){
				$res = $this->get('at_report_industry_month', ["max(ari_date) as b_date"], '', true);
				$maxDate = $res['data']['b_date'];
				
				$current = strtotime($firstDate.'01');
				$endTime = strtotime($maxDate.'01');
				while ($current <= $endTime) {
					$month = date('Ym', $current);
					$current  = strtotime('+1 month', $current);
					$this->TjDb->Begin();
					//清空历史
					$this->del('at_report_industry_item', sprintf(" and ari_type = '%s'  and ari_date = %d", $type, $month));
					$addSql = '';
					if($type == 'brand'){
						$addSql = sprintf("INSERT INTO at_report_industry_item(ari_date, ari_type, ari_keyid, ari_count, art_hotpv)
						SELECT %d, '%s', mod2_brand_id, SUM(ari_count), SUM(art_hotpv) FROM at_report_industry_month join bc_model2 on mod2_id = ari_mod2_id
						WHERE ari_date = %d GROUP BY mod2_brand_id", $month, $type, $month);
					}else if($type == 'brand_model1'){
						$addSql = sprintf("INSERT INTO at_report_industry_item(ari_date, ari_type, ari_keyid, ari_keyid2, ari_count, art_hotpv)
						SELECT %d, '%s', mod2_brand_id, mod2_mod1_id, SUM(ari_count), SUM(art_hotpv) FROM at_report_industry_month join bc_model2 on mod2_id = ari_mod2_id
						WHERE ari_date = %d GROUP BY mod2_mod1_id", $month, $type, $month);
					}else if($type == 'brand_model2'){
						$addSql = sprintf("INSERT INTO at_report_industry_item(ari_date, ari_type, ari_keyid, ari_keyid2, ari_count, art_hotpv)
						SELECT %d, '%s', mod2_brand_id, ari_mod2_id, SUM(ari_count), SUM(art_hotpv) FROM at_report_industry_month join bc_model2 on mod2_id = ari_mod2_id
						WHERE ari_date = %d GROUP BY ari_mod2_id", $month, $type, $month);
					}else if($type == 'province'){
						$addSql = sprintf("INSERT INTO at_report_industry_item(ari_date, ari_type, ari_keyid, ari_count, art_hotpv)
						SELECT %d, '%s', ari_province, SUM(ari_count), SUM(art_hotpv) FROM at_report_industry_month WHERE ari_date = %d GROUP BY ari_province", $month, $type, $month);
					}else if($type == 'brand_province'){
						$addSql = sprintf("INSERT INTO at_report_industry_item(ari_date, ari_type, ari_keyid, ari_keyid2, ari_count, art_hotpv)
						SELECT %d, '%s', mod2_brand_id, ari_province, SUM(ari_count), SUM(art_hotpv) FROM at_report_industry_month join bc_model2 on mod2_id = ari_mod2_id
						WHERE ari_date = %d GROUP BY mod2_brand_id, ari_province", $month, $type, $month);
					}else if($type == 'province_city'){
						$addSql = sprintf("INSERT INTO at_report_industry_item(ari_date, ari_type, ari_keyid, ari_keyid2, ari_count, art_hotpv)
						SELECT %d, '%s', ari_province, ari_city, SUM(ari_count), SUM(art_hotpv) FROM at_report_industry_month WHERE ari_date = %d GROUP BY ari_province, ari_city", $month, $type, $month);
					}else{
						return LibFc::ReturnData(false, $type.'类型尚未定义SQL');
					}
					$this->exeAnySql([$addSql]);
					$this->TjDb->End();
				}
			}
		}
		return LibFc::ReturnData(true);
    }


	/**
	  * @method 店铺报表-（不含当日）
	  * @author soul
	  * @copyright 2020/4/30
	  * @return 
	  */
	public function initReportShop()
	{
		//从哪个日期开始
		$firstDate = '20251001';
		$res = $this->get('at_report_shop_day', ['max(ars_date) as b_date'], '', true);
		if(!empty($res['data']['b_date'])){
			$firstDate = date('Ymd', strtotime($res['data']['b_date'])+3600*24);
		}/*else{
			$res = $this->get('at_tongji_mod', ["min(atm_date) as b_date"], '', true);
			if(!empty($res['data']['b_date'])){
				$firstDate = $res['data']['b_date'];
			}
		}*/

		$res = $this->get('at_tongji_mod', ["max(atm_date) as b_date"], '', true);
		$maxDate = date('Ymd', strtotime($res['data']['b_date']) - 3600*24);
		
		$dateArr = [];
		$dateArr = array_map( function ($n) { return date('Ymd', $n);}, range(strtotime($firstDate), strtotime($maxDate)-24*3600, 24 * 3600));
		asort($dateArr);
		foreach($dateArr as $date){
			if($date == date('Ymd')) break;
			$this->TjDb->Begin();
			//清空历史
			$this->del('at_report_shop_day', ' and ars_date = '.$date);
			$addSql = sprintf("INSERT INTO at_report_shop_day(ars_shop_id, ars_date, ars_mod2_id, ars_engine, ars_drive, ars_transmission, ars_province, ars_city, ars_from, ars_count)
				SELECT atm_shop_id, atm_date, atm_mod2_id, atm_engine, atm_drive, atm_transmission, case when atm_pcauto = 1 then 0 else atm_province end province, case when atm_pcauto = 1 then 0 else atm_city end city, atm_from, COUNT(*) pv_count
				FROM at_tongji_mod where atm_shop_id > 0 and atm_date=%d GROUP BY atm_shop_id, atm_mod2_id, atm_engine, atm_drive, atm_transmission, province, city, atm_from ORDER BY COUNT(*) DESC", $date);
			$this->exeAnySql([$addSql]);
			$this->TjDb->End();
		}

		//月报表
		$firstDate = '202510';
		$res = $this->get('at_report_shop_month', ['max(ars_date) as b_date'], '', true);
		if(!empty($res['data']['b_date'])){
			$firstDate = $res['data']['b_date'];
		}else{
			$res = $this->get('at_report_shop_day', ["min(ars_date) as b_date"], '', true);
			if(!empty($res['data']['b_date'])){
				$firstDate = date('Ym', strtotime($res['data']['b_date']));
			}
		}
		if($firstDate){
			$res = $this->get('at_report_shop_day', ["max(ars_date) as b_date"], '', true);
			$maxDate = date('Ym', strtotime($res['data']['b_date']));
			
			$current = strtotime($firstDate.'01');
			$endTime = strtotime($maxDate.'01');
			while ($current <= $endTime) {
				$month = date('Ym', $current);
				$current  = strtotime('+1 month', $current);
				$this->TjDb->Begin();
				//清空历史
				$this->del('at_report_shop_month', ' and ars_date = '.$month);
				$addSql = sprintf("INSERT INTO at_report_shop_month(ars_shop_id, ars_date, ars_mod2_id, ars_engine, ars_drive, ars_transmission, ars_province, ars_city, ars_from, ars_count)
				SELECT ars_shop_id, %d, ars_mod2_id, ars_engine, ars_drive, ars_transmission, ars_province, ars_city, ars_from, SUM(ars_count) FROM at_report_shop_day
				WHERE ars_date >= %d AND ars_date < %d GROUP BY ars_shop_id, ars_mod2_id, ars_engine, ars_drive, ars_transmission, ars_province, ars_city, ars_from", $month, $month.'01', date('Ymd', $current));
				$this->exeAnySql([$addSql]);
				$this->TjDb->End();
			}
		}
		return LibFc::ReturnData(true);
    }
}