<?php

require '../admin/vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use servers\baseModel;

//品牌目录
class tjAction extends baseAction
{
	//访问统计
	function base()
	{
		$Params = mvc::$URL_PARAMS;
		//条件限制
		$dateArr = [
			'-7 days' => '7天',
			'-15 days' => '15天',
			'-1 month' => '1个月'
		];
		LibTpl::Set('dateArr', $dateArr);

		if (!empty($Params['limit']) && !empty($dateArr[$Params['limit']])) {
			$Params['bdate'] = date('Y-m-d', strtotime($Params['limit']));
			$Params['edate'] = date('Y-m-d');
		} else {
			if (empty($Params['bdate'])) $Params['bdate'] = date('Y-m-d', strtotime('-15 days'));
			if (empty($Params['edate'])) $Params['edate'] = date('Y-m-d');
		}

		$tjArr = [];
		$dateCount = (strtotime($Params['edate']) - strtotime($Params['bdate'])) / 24 / 3600;
		for ($i = 0; $i <= $dateCount; $i++) {
			$t = date('Ymd', strtotime($Params['edate']) - $i * 24 * 3600);
			$tjArr[$t] = [
				'sub_date' => $t,
				'sub_client' => 0,
				'sub_pv' => 0,
				'sub_ip' => 0,
				'sub_itemlist' => 0,
				'sub_item' => 0
			];
		}

		$where = sprintf(" and sub_shop_id=%d and sub_date>= '%s' and sub_date<= '%s'", $_SESSION['_shopid'], date('Ymd', strtotime($Params['bdate'])), date('Ymd', strtotime($Params['edate'])));
		$OthBase = new OthBase();
		$res = $OthBase->get('tj_super_date', ['*'], $where . ' group by sub_date order by sub_date desc');
		foreach ($res['data'] as $v) {
			$tjArr[$v['sub_date']] = $v;
		}
		LibTpl::Set('tjArr', $tjArr);

		//组装统计图数据
		ksort($tjArr);
		$tjtArr = [
			'date' => array_column($tjArr, 'sub_date'),
			'filed' => [
				'sub_client' => '访客数',
				'sub_pv' => '浏览量',
				//'sub_ip'=>'IP数',
				'sub_itemlist' => '查询列表',
				'sub_item' => '配件浏览'
			],
			'data' => []
		];

		foreach ($tjtArr['filed'] as $filed => $name) {
			$tjtArr['data'][] = [
				'name' => $name,
				'type' => 'line',
				'stack' => '总计',
				'data' => array_column($tjArr, $filed)
			];
		}
		LibTpl::Set('tjtArr', $tjtArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '访问统计');
		LibTpl::Put();
	}

	//品牌统计条件
	function brandTjLeft()
	{
		$Params = mvc::$URL_PARAMS;
		//$B2cPart = new B2cPart();
		//$res = $B2cPart->getShopSuperSPart($_SESSION['_shopid']);
		//LibTpl::Set('supPartArr', $res['data']);
		//店铺全车件品牌
		$B2cShop  = new B2cShop();
		$brandRes = $B2cShop->getShopBrand($_SESSION['_shopid']);
		$lWhere = '';
		if ($brandRes['data']) {
			$lWhere = sprintf(" AND b_id in (%s)", implode(',', $brandRes['data']));
		}
		$YpcModel = new YpcModel();
		$res = $YpcModel->Get('yp_brand', ['b_id', 'b_name', 'b_initial'], $lWhere . ' order by b_initial');
		LibTpl::Set('brandArr', $res['data']);

		LibTpl::Set('title', '品牌覆盖统计');
		$this->HEAD_CSSJS['plugin'][] = 'zTree';
		LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
		LibTpl::Put();
	}

	//品牌统计
	function brandTjList()
	{
		$Params = $_GET;
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 25;
		$perPage = $perPage > 50 ? 50 : $perPage;

		$itemWhere = sprintf(' and pro_shop_id=%d', $_SESSION['_shopid']);
		$total = 0;

		$B2cPart = new B2cPart();
		// $res = $B2cPart->getShopSuperSPart($_SESSION['_shopid']);
		$res = $B2cPart->getProductPart($_SESSION['_shopid']);
		$proSpartIdArr = array_unique(array_column($res['data'], 'spart_id'));
		$supPartArr = array_column($res['data'], null, 'spart_id');
		$spartIdArr = empty($Params['spartid']) || !is_array($Params['spartid']) ? $proSpartIdArr : $Params['spartid'];

		$YpcBase = new YpcBase();
		$YpcModel = new YpcModel();

		$where = '';
		foreach ($Params as $filed => $val) {
			if (!is_array($val)) {
				$val = trim($val);
				if ($val == '') continue;
			} else if (empty($val)) {
				continue;
			}
			switch ($filed) {
				case 'brandid':
					foreach ($val as $kk => $vv) {
						$val[$kk] = (int) $vv;
					}
					if (!empty($val)) $where .= sprintf(" AND b_id in (%s)", implode(',', $val));
					break;
			}
		}

		if ($Params['allbrand']) {
			$B2cShop  = new B2cShop();
			$brandRes = $B2cShop->getShopBrand($_SESSION['_shopid']);
			if ($brandRes['data']) {
				$where .= sprintf(" AND b_id in (%s)", implode(',', $brandRes['data']));
			}
		}

		$Res = $YpcBase->Get('yp_brand', ['count(*) as count'], $where, true);
		$total = $Res['data']['count'];
		$brandPartArr = [];
		$brandArr = [];

		//下载
		if (!empty($Params[''])) {
			$perPage = $total;
			$page = 1;
		}


		if ($total > 0) {
			$tres = $YpcModel->GetModel(3, ['b_id, b_name, count(*) as m3_count'], sprintf("%s group by b_id order by b_initial LIMIT %d,%d", $where, ($page - 1) * $perPage, $perPage));
			if (!empty($tres['data'])) {
				$B2cBase = new B2cBase();
				foreach ($tres['data'] as $v) {
					$v['bcount'] = [];
					$res = $YpcModel->GetModel(3, ['m3_id'], ' and b_id=' . $v['b_id']);
					$v['m3_ids'] = array_column($res['data'], 'm3_id');
					if (!empty($v['m3_ids'])) {
						// $table = 'bc_product_model3_link join bc_product on pro_id = pml3_pro_id join sh_super_part on sup_shop_id = pro_shop_id and sup_part_id = pro_part_id';
						$table = 'bc_product_model3_link join bc_product on pro_id = pml3_pro_id';
						$twhere = $itemWhere . sprintf(" and pml3_mod3_id in (%s) and concat(pro_part_id, '_', pro_pas_id) in ('%s') group by pro_part_id, pro_pas_id", implode(',', $v['m3_ids']), implode("','", $spartIdArr));
						$pres = $B2cBase->get($table, ["count(distinct pml3_mod3_id) as m3_count, pro_part_id, pro_pas_id, concat(pro_part_id, '_', pro_pas_id) spartid"], $twhere);
						foreach ($pres['data'] as $vv) {
							//if($vv['pro_pas_id'] > 0) $v['bcount'][$vv['pro_part_id'].'_0'] += $vv['m3_count'];
							$v['bcount'][$vv['spartid']] = $vv['m3_count'];
						}
					}
					$brandArr[$v['b_id']] = $v;
				}
			}
		}


		if (!empty($Params['export'])) {
			$rowArr = [];
			$row = ['汽车品牌', '车型数'];
			foreach ($spartIdArr as $spid) {
				$row[] = $supPartArr[$spid]['name'];
			}
			$rowArr[] = $row;

			foreach ($brandArr as $k => $v) {
				$row = [$v['b_name'], $v['m3_count']];
				foreach ($spartIdArr as $spid) {
					$row[] = empty($v['bcount'][$spid]) ? '' : sprintf("%.2f%%", $v['bcount'][$spid] / $v['m3_count'] * 100);
				}
				$rowArr[] = $row;
			}
			$OthExcel = new OthExcel();
			$OthExcel->writer($rowArr, 'Excel5', '目录品牌覆盖' . date('Ymd') . '.xls');
			exit;
		}


		LibTpl::Set('spartIdArr', $spartIdArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('supPartArr', $supPartArr);
		LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
		LibTpl::Set('brandArr', $brandArr);
		LibTpl::Set('title', '品牌覆盖统计');
		LibTpl::Put();
	}

	/**
	 * @method 车架号每日统计
	 * @author zhengweihua 
	 * @copyright 2022-08-17
	 */
	public function vinTjList()
	{
		$Params = mvc::$URL_PARAMS;
		$OthBase = new OthBase();
		$mainBase = new MainBase();
		//条件限制
		$dateArr = [
			'-7 days' => '7天',
			'-15 days' => '15天',
			'-1 month' => '1个月'
		];
		if (!empty($Params['limit']) && !empty($dateArr[$Params['limit']])) {
			$Params['bdate'] = date('Y-m-d', strtotime($Params['limit']));
			$Params['edate'] = date('Y-m-d');
		} else {
			if (empty($Params['bdate'])) $Params['bdate'] = date('Y-m-d', strtotime('-1 month'));
			if (empty($Params['edate'])) $Params['edate'] = date('Y-m-d');
		}
		// 最早不能早于2022-07-24
		$mintime = strtotime('2022-07-24');
		$Params['bdate'] = $mintime > strtotime($Params['bdate']) ? date('Y-m-d', $mintime) : $Params['bdate'];
		$Params['edate'] = $mintime > strtotime($Params['edate']) ? date('Y-m-d', $mintime) : $Params['edate'];
		$SQLEndDate = $Params['edate'];
		$fromArr = ['total'];
		$vinTjArr = [];
		//由于当天统计数据更新有延时 所以如果需要查当天数据 则直接从api_search_history获取
		if ($Params['edate'] === date('Y-m-d')) {
			$SQLEndDate = date('Y-m-d', strtotime('-1 day'));
			$whereToday = sprintf(" and ash_uid = %d and ash_date = '%s' and ash_from !='superpjl'", (int)$_SESSION['_shopid'], date('Ymd'));
			$whereToday .= 'group by ash_unikey';
			$feildToday = ['ash_date as suv_date,ash_from as suv_from'];
			$resToday = $mainBase->get('api_search_history', $feildToday, $whereToday);
			foreach ($resToday['data'] as $v) {
				if (stripos($v['suv_from'], 'robot') !== false) {
					$v['suv_from'] = 'robot';
				};
				$vinTjArr[$v['suv_date']][$v['suv_from']] += 1;
				$vinTjArr[$v['suv_date']]['total'] += 1;
				$fromArr[] = $v['suv_from'];
			}
		}



		$where  = sprintf(" and suv_shop_id = %d and suv_date >= '%s' and suv_date <= '%s' and suv_from !='superpjl'
		order by suv_date desc", (int)$_SESSION['_shopid'], date('Ymd', strtotime($Params['bdate'])), date('Ymd', strtotime($SQLEndDate)));

		$field = ["suv_count,suv_date,suv_from"];
		$res = $OthBase->get('tj_shop_vin', $field, $where);

		foreach ($res['data'] as $v) {
			if (stripos($v['suv_from'], 'robot') !== false) {
				$v['suv_from'] = 'robot';
				$vinTjArr[$v['suv_date']][$v['suv_from']] += $v['suv_count'];
			} else {
				$vinTjArr[$v['suv_date']][$v['suv_from']] = $v['suv_count'];
			}
			$vinTjArr[$v['suv_date']]['total'] += $v['suv_count'];
			$fromArr[] = $v['suv_from'];
		}
		$fromArr =	array_unique($fromArr);
		$nameArr = [
			'total' => '总计',
			'api' => 'API接口',
			'super' => '公众号目录',
			'superpjl' => '品牌目录',
			'gzh' => '商城版目录',
			'robot' => '机器人'
		];
		LibTpl::Set('fromArr', $fromArr);
		LibTpl::Set('dateArr', $dateArr);
		LibTpl::Set('nameArr', $nameArr);
		LibTpl::Set('vinTjArr', $vinTjArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', 'VIN统计');
		LibTpl::Set('shopId', $_SESSION['_shopid']);
		LibTpl::Put();
	}

	/**
	 * @method VIN明细
	 * @author hongzhang 
	 * @copyright 2025-09-28
	 */
	public function vinDetail()
	{
		$Params = mvc::$URL_PARAMS;
		$queryDate = date('Ymd', strtotime($Params['date']));
		$oneMonthAgo = date('Ymd', strtotime('-1 month'));
		if ($queryDate < $oneMonthAgo) {
			LibFc::ajaxJsonEncode(['status' => false, 'data' => '只能查询最近一个月的明细']);
		}
		$mainBase = new MainBase();
		$html = '';
		$fromArr = [
			'api' => 'API接口',
			'super' => '公众号目录',
			'superpjl' => '品牌目录',
			'gzh' => '商城版目录',
			'robot' => '机器人'
		];
		$agentArr = [
			'wxgr' => '微信群聊',
			'wxgzh' => '微信公众号',
			'wxkf' => '企微客服',
		];
		//查找店铺会员
		$b2cDb = mvc::$cfg['DB']['B2C']['db_name'];
		$ypWriteDb = mvc::$cfg['DB']['YP_WRITE']['db_name'];
		$mainDb = mvc::$cfg['DB']['MAIN']['db_name'];
		$table = sprintf("{$b2cDb}.sh_shop_user
		left join {$b2cDb}.sh_member_link  on sus_uid=meml_uid and meml_shop_id = %d
		join {$ypWriteDb}.yp_user on sus_uid = u_id
		join {$ypWriteDb}.yp_user_ext on sus_uid = ui_uid", $Params['shopId']);
		$where1 = sprintf(" and sus_shop_id = %d", $Params['shopId']);
		$YpwBase = new YpwBase();
		$res1 = $YpwBase->get($table, ['sus_uid'], $where1);
		$uidArr = array_column($res1['data'], 'sus_uid');

		//分页查找对应明细
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 25;
		$table = sprintf("{$mainDb}.api_search_history ash 
		left join {$ypWriteDb}.yp_user yu on ash.ash_uid_by=yu.u_id
		left join {$b2cDb}.wx_acount wa1 on ash.ash_wxid_by=wa1.wa_id
		left join {$b2cDb}.wx_acount wa2 on ash.ash_wx_room=wa2.wa_id");
		$where2 = sprintf(" and ash.ash_uid = %d and ash.ash_date = '%s' and ash.ash_from !='superpjl'", $Params['shopId'], $Params['date']);
		$res = $mainBase->get($table, ['count(DISTINCT ash.ash_unikey) as count'], $where2, true);
		$total = $res['data']['count'];
		if ($total > 0) {
			// 直接使用GROUP BY根据ash_unikey去重，并添加分页
			$where2 .= sprintf(' group by ash.ash_unikey ORDER BY MAX(ash.ash_atime) DESC LIMIT %d,%d', ($page - 1) * $perPage, $perPage);
			$field = ['MAX(ash.ash_atime) as ash_atime', 'ash.ash_val', 'ash.ash_uid_by', 'yu.u_name', 'yu.u_mobile', 'ash.ash_wx_room', 'ash.ash_wxid_by', 'wa1.wa_nickname as wx_name', 'wa2.wa_nickname as wx_room_name', 'ash.ash_from', 'ash.ash_agent'];
			$res = $mainBase->get($table, $field, $where2);
			foreach ($res['data'] as $k => $v) {
				//处理时间
				$res['data'][$k]['ash_atime'] = date('Y-m-d H:i', $v['ash_atime']);
				//处理查询用户名
				$isMember = in_array($v['ash_uid_by'], $uidArr);
				if ($isMember) {
					$res['data'][$k]['u_name'] = $v['u_mobile'];
				}
				//处理查询微信信息
				$res['data'][$k]['ash_wx_room'] = $v['wx_room_name'] ? $v['wx_room_name'] : $v['ash_wx_room'];
				$res['data'][$k]['ash_wxid_by'] = $v['wx_name'] ? $v['wx_name'] : $v['ash_wxid_by'];
				//处理查询来源
				if (strpos($v['ash_from'], 'robot') !== false) {
					$v['ash_from'] = 'robot';
				}
				$res['data'][$k]['ash_from'] = $fromArr[$v['ash_from']];
				//处理查询客户端
				$res['data'][$k]['ash_agent'] = $agentArr[$v['ash_agent']];
			}
			$vinDetailList = $res['data'];
		}
		LibTpl::Set('vinDetailList', $vinDetailList);
		LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
		$html = LibTpl::Fetch();
		LibFc::ajaxJsonEncode(['status' => true, 'data' => $html]);
	}

	/**
	 * @method 车型统计
	 * @author zhengweihua 
	 * @copyright 2025-09-28
	 */
	public function modelTj()
	{
		$Params = mvc::$URL_PARAMS;

		$group =  !empty($_GET['group']) ? $_GET['group'] : ['brand_id'];
		$BaseDb = new BaseDb(mvc::$cfg['DB']['API_TJ']);

		$where  = ' AND ars_shop_id=' . (int)$_SESSION['_shopid'];
		//查最大和最小可查年份
		$limitYearRes = $BaseDb->get('at_report_shop_month', ['min(ars_date) as minYear', 'max(ars_date) as maxYear'], $where, true);

		$minYear = substr($limitYearRes['data']['minYear'], 0, 4) . '-' . substr($limitYearRes['data']['minYear'], 4, 2);
		$maxYear = substr($limitYearRes['data']['maxYear'], 0, 4) . '-' . substr($limitYearRes['data']['maxYear'], 4, 2);

		LibTpl::Set('limitYear', ['minYear' => $minYear . '-01', 'maxYear' => $maxYear . '-01']);
		if (!$Params['betime']) {

			$Params['betime'] = date('Y') . '01' >= $limitYearRes['data']['minYear'] ? date('Y-01') : $minYear;
			$Params['betime'] = $Params['betime'] . ' ~ ' . (date('Ym') <= $limitYearRes['data']['maxYear'] ? date('Y-m') : $maxYear);
		}
		// $Params['betime'] = !empty($Params['betime'])?$Params['betime']:date('Y-01').' ~ '.date('Y-m');
		//转换一下
		$fromNameArr = ['PJL' => '跑街令', 'SUPER' => '目录', 'WXROBOT' => '机器人', 'API' => '接口'];
		$selectIdArr = [];
		foreach ($Params as $key => $val) {
			if (!$val && !in_array($key, ['province_id', 'city_id'])) continue;
			switch ($key) {
				case 'betime':
					$dateArr = explode('~', $val);
					if (count($dateArr) == 2) {
						$where .= sprintf(" and ars_date >= '%s' ", date('Ym', strtotime(trim($dateArr[0]))));
						$where .= sprintf(" and ars_date <= '%s' ", date('Ym', strtotime(trim($dateArr[1]))));
					}
					break;
				case 'brand':
					$where .= sprintf(" and mod1_brand_id in (%s) ", implode(',', explode(',', $val)));
					//回显品牌
					$missingRes = $BaseDb->get(
						'bc_brand',
						['brand_id as value', 'brand_name as name'],
						sprintf(" and brand_id in (%s)", implode(',', explode(',', $val)))
					);
					$selectIdArr['brandIds'] = $missingRes['data'];
					break;
				
				case 'province_id':
					$provinceIds = array_filter(explode(',', $val), function ($item) {
						return is_numeric($item);
					});
					if(!$provinceIds) continue;
					$selectIdArr['provinceIds']  = [];
					$validProvinceIds = $provinceIds;
					if ($validProvinceIds) {
						$where .= sprintf(" and ars_province in (%s)", implode(',', $validProvinceIds));
						$Ypw = new YpwBase();
						$missingRes = $Ypw->get(
							'yp_province_city',
							['pc_id as value', 'pc_name as name'],
							sprintf(" and pc_id in (%s)", implode(',', $validProvinceIds))
						);
						$selectIdArr['provinceIds'] = $missingRes['data'];
					}
					if (in_array(0, $provinceIds)) {
						array_push($selectIdArr['provinceIds'], ['value' => 0, 'name' => '其他']);
					}

					break;
			}
		}
		// 构建分组字段（不包含ars_date）
		$groupFields = [];
		$selectFields = [];
		if (in_array('brand_id', $group)) {
			$groupFields[] = 'brand_id';
			$selectFields[] = 'brand_id,brand_name';
		}
		if (in_array('mod2_mod1_id', $group)) {
			$groupFields[] = 'mod2_mod1_id';
			$selectFields[] = 'brand_id,brand_name,mod2_mod1_id,mod1_name';
		}
		if (in_array('ars_mod2_id', $group)) {
			$groupFields[] = 'ars_mod2_id';
			$selectFields[] = 'brand_id,brand_name,mod2_mod1_id,mod1_name,ars_mod2_id,mod2_name,mod2_start_year,mod2_end_year';
		}
		if (in_array('ars_province', $group)) {
			$groupFields[] = 'ars_province';
			$selectFields[] = 'ars_province';
		}
		if (in_array('ars_city', $group)) {
			$groupFields[] = 'ars_city';
			$selectFields[] = 'ars_city';
		}

		if (in_array("ars_drive", $group)) {
			$groupFields[] = "ars_drive";
			$selectFields[] = "ars_drive";
		}
		if (in_array("ars_engine", $group)) {
			$groupFields[] = "ars_engine";
			$selectFields[] = "ars_engine";
		}
		if (in_array("ars_transmission", $group)) {
			$groupFields[] = "ars_transmission";
			$selectFields[] = "ars_transmission";
		}

		$groupby = '';
		if (!empty($groupFields)) {
			$groupby = 'group by ' . implode(',', $groupFields);
		}

		//获取分页参数
		$page = isset($Params['page']) ? max(1, (int)$Params['page']) : 1;
		$perPage = isset($_COOKIE['perPage']) ? (int)$_COOKIE['perPage'] : 20;
		$offset = ($page - 1) * $perPage;

		// 获取所有时间范围内的月份
		$startDate = date('Ym', strtotime(trim($dateArr[0])));
		$endDate = date('Ym', strtotime(trim($dateArr[1])));
		$months = [];
		$current = $startDate;
		while ($current <= $endDate) {
			$months[] = $current;
			$current = date('Ym', strtotime('+1 month', strtotime($current . '01')));
		}
		$months = array_reverse($months);
		$table = 'at_report_shop_month as tj
		join bc_model2 as mod2 on mod2_id=ars_mod2_id
		join bc_model1 as mod1 on mod1_id=mod2_mod1_id
		join bc_brand as brand on brand_id=mod1_brand_id';


		// 先获取去重后的分组总数（用于分页）
		$table1 = "(
			SELECT " . implode(',', $groupFields) . "
			FROM $table
			WHERE 1=1 $where
			$groupby
		) as tmp";

		$countRes = $BaseDb->get($table1, ['count(*) as count'], '', true);
		$total = $countRes['data']['count'];

		if($total>0)
		{
			// 计算总销量 -查询所有数据的总和
			$totalRes = $BaseDb->get($table, ['SUM(ars_count) as totalCounts'], $where, true);
			$totalCounts = $totalRes['data']['totalCounts'];

			// 获取当前页的分组数据
			$field = array_unique($selectFields);
			$res = $BaseDb->get($table, $field, sprintf(" %s  %s ORDER BY sum(ars_count) DESC LIMIT $offset, $perPage", $where, $groupby));

			if($res['data'])
			{
				
				// 获取省份和城市数据
				$cityIds = array_merge(array_column($res['data'], 'ars_city'),array_column($res['data'], 'ars_province'));
				if($cityIds){
					$pcRes = $BaseDb->get('yp_province_city',['pc_id', 'pc_name'],sprintf(" AND pc_id IN (%s)",implode(',', $cityIds)));
					$pcNameArr = array_column($pcRes['data'], 'pc_name', 'pc_id');
					$pcNameArr[0] = '其他';
				}
				$result = [];
				foreach ($res['data'] as $row) {
					// 构建详细查询条件
					$detailWhere = $where;
					if (isset($row['brand_id'])) {
						$detailWhere .= " AND brand_id = " . $row['brand_id'];
					}
					if (isset($row['mod2_mod1_id'])) {
						$detailWhere .= " AND mod2_mod1_id = " . $row['mod2_mod1_id'];
					}
					if (isset($row['ars_mod2_id'])) {
						$detailWhere .= " AND ars_mod2_id = " . $row['ars_mod2_id'];
					}
					if (isset($row['ars_province'])) {
						$detailWhere .= " AND ars_province = " . $row['ars_province'];
					}
					if (isset($row['ars_city'])) {
						$detailWhere .= " AND ars_city = " . $row['ars_city'];
					}

					if (isset($row['ars_engine'])) {
						$detailWhere .= " AND ars_engine = '" . $row['ars_engine'] . "'";
					}
					if (isset($row['ars_drive'])) {
						$detailWhere .= " AND ars_drive = '" . $row['ars_drive'] . "'";
					}
					if (isset($row['ars_transmission'])) {
						$detailWhere .= " AND ars_transmission = '" . $row['ars_transmission'] . "'";
					}

					// 获取该分组的月份统计数据

					$detailRes = $BaseDb->get($table, ['ars_date', 'SUM(ars_count) as totalcount'], $detailWhere . ' GROUP BY ars_date');
					$years = (!empty($row['mod2_start_year']) || !empty($row['mod2_end_year'])) ?
						((!empty($row['mod2_start_year']) && $row['mod2_start_year'] > 0 ? $row['mod2_start_year'] : '') .
							'-' .
							(!empty($row['mod2_end_year']) && $row['mod2_end_year'] > 0 ? $row['mod2_end_year'] : '')) :
						'';
					// 构建结果
					$item = [
						'brand_id' => $row['brand_id'] ?? '',
						'brand' => $row['brand_name'] ?? '',
						'mod1_id' => $row['mod2_mod1_id'] ?? '',
						'mod1' => $row['mod1_name'] ?? '',
						'mod2_id' => $row['ars_mod2_id'] ?? '',
						'mod2' => $row['mod2_name'] ?? '',
						'engine' => $row['ars_engine'] ?? '',
						'drive' => $row['ars_drive'] ?? '',
						'transmission' => $row['ars_transmission'] ?? '',
						'province' => $pcNameArr[$row['ars_province']] ?? '',
						'city' => $pcNameArr[$row['ars_city']] ?? '',
						'years' => $years,
						'counts' => [],
						'total' => 0
					];

					// 填充月份数据
					$monthDetailArr = array_column($detailRes['data'], 'totalcount', 'ars_date');

					foreach ($months as $month) {
						$item[$month] = $monthDetailArr[$month] ?? 0;
					}

					$item['total'] = array_sum($monthDetailArr);
					// 计算占比
					$item['percent'] = $item['total'] > 0 ? round(($item['total'] / $totalCounts) * 100, 2) : 0;


					$result[] = $item;
				}
			}
		}
		
		// 品牌  车系  车代   省份  城市
		$groupTypeArr = ['brand_id' => '品牌', 'mod2_mod1_id' => '车系', 'ars_mod2_id' => '车代', 'ars_engine' => '发动机', 'ars_drive' => '驱动', 'ars_transmission' => '变速箱', 'ars_province' => '省份', 'ars_city' => '城市'];
		LibTpl::Set('groupTypeArr', $groupTypeArr);
		//看看哪些列要显示
		$selectedGroup = $group ?? [];
		$showCols = [
			'brand' => in_array('brand_id', $selectedGroup) || in_array('mod2_mod1_id', $selectedGroup) || in_array('ars_mod2_id', $selectedGroup),
			'mod1' => in_array('mod2_mod1_id', $selectedGroup) || in_array('ars_mod2_id', $selectedGroup),
			'mod2' => in_array('ars_mod2_id', $selectedGroup),
			'engine' => in_array('ars_engine', $selectedGroup),
			'drive' => in_array('ars_drive', $selectedGroup),
			'transmission' => in_array('ars_transmission', $selectedGroup),
			'province' => in_array('ars_province', $selectedGroup),
			'city' => in_array('ars_city', $selectedGroup),
			'percent' => true,
		];
		// 设置分页
		$Page = LibPage::Show($total, $perPage, true);
		LibTpl::Set('Page', $Page);

		$B2cBase = new B2cBase();
		$templateRes = $B2cBase->get('sh_shop_report_tpl', ['ssr_id', 'ssr_name'], sprintf(' AND ssr_shop_id=%d order by ssr_atime desc',$_SESSION['_userid']));
		LibTpl::Set('reportTemplates', $templateRes['data']);

		LibTpl::Set('group', $selectedGroup);
		LibTpl::Set('selectIdArr', $selectIdArr);
		LibTpl::Set('showCols', $showCols);
		LibTpl::Set('months', $months);
		LibTpl::Set('tjArr', $result ?: []);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '车型报表');
		LibTpl::Put();
	}

	/**
	 * @method 保存报表模板
	 * @author zhengweihua 
	 * @copyright 2025-10-21
	 */
	public function saveReportTpl()
	{
		if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['param']){

			// 处理表单数据，过滤掉betime字段
			$templateData = [];
			$formData = $_POST['param']; // 接收表单数据数组
			if (is_array($formData)) {
				// 处理serializeArray格式的数据
				foreach ($formData as $item) {
					if (is_array($item) && isset($item['name']) && isset($item['value'])) {
						// 排除betime字段
						if ($item['name'] !== 'betime') {
							// 处理复选框等多值情况
							if (isset($templateData[$item['name']])) {
								if (!is_array($templateData[$item['name']])) {
									$templateData[$item['name']] = [$templateData[$item['name']]];
								}
								$templateData[$item['name']][] = $item['value'];
							} else {
								$templateData[$item['name']] = $item['value'];
							}
						}
					}
				}
			}
					
			// 获取统计类型复选框的选中值
			if (isset($templateData['group[]'])) {
				$templateData['group'] = $templateData['group[]'];
				unset($templateData['group[]']);
			}

			$dateArr = [
				'ssr_shop_id'=>$_SESSION['_shopid'],
				'ssr_u_id'=>$_SESSION['_userid'],
				'ssr_name'=>$_POST['name']?:'未命名_'.date('YmdHi'),
				'ssr_param'=>json_encode($templateData),
				'ssr_atime'=>time()
			];


			$B2cBase = new B2cBase();
			if($_POST['ssr_id']){
				$res = $B2cBase->set('sh_shop_report_tpl', $dateArr, ['ssr_id'=>$_POST['ssr_id']]);
			}else{
				$res = $B2cBase->add('sh_shop_report_tpl', $dateArr);
			}
			LibFc::ajaxJsonEncode($res);
		}
	}

	/**
	 * 获取报表模板
	 */
	public function getReportTpl() {
		$id = (int)$_GET['id'];
		if ($id <= 0) {
			LibFc::ajaxJsonEncode(['status' => false, 'data' => '参数错误']);
		}
		
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('sh_shop_report_tpl', ['*'], sprintf(" and ssr_id=%d and ssr_shop_id=%d", $id,$_SESSION['_shopid']), true);
		if($res['data']){
			$ssr_param = json_decode($res['data']['ssr_param'], true);

			$res['data']['ssr_param'] = json_encode($ssr_param);
		}
		LibFc::ajaxJsonEncode($res);
	}

	/**
	 * 删除报表模板
	 */
	public function deleteReportTpl() {
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$id = (int)$_POST['id'];
			if ($id <= 0) {
				LibFc::ajaxJsonEncode(['status' => false, 'data' => '参数错误']);
			}
			
			$B2cBase = new B2cBase();
			$res = $B2cBase->del('sh_shop_report_tpl', sprintf(" and ssr_id=%d and ssr_shop_id=%d", $id,$_SESSION['_shopid']));
			
			LibFc::ajaxJsonEncode($res);
		}
	}


	/**
	 * @method 搜素相关字段
	 * @author zhengweihua 
	 * @copyright 2025-09-16
	 */
	public function getSearchFields()
	{
		$Params = mvc::$URL_PARAMS;
		if (empty($Params['type'])) LibFc::ReturnJson(false, '参数错误');

		$BaseDb = new BaseDb(mvc::$cfg['DB']['API_TJ']);

		$keyword = LibFc::Escape($Params['keyword']);

		$selectedIds = isset($Params['selected_ids']) && !empty($Params['selected_ids']) ? explode(',', $Params['selected_ids']) : [];


		switch ($Params['type']) {
			case 'brand':
				$where = " order by brand_initial ASC";
				if ($Params['keyword']) {
					$where = sprintf(" and brand_name like '%%%s%%' order by brand_initial ASC", $keyword);
				}
				$res = $BaseDb->get('bc_brand', ['brand_id as value', 'brand_name as name'], $where);

				// 如果有 selected_ids，则补充缺失的品牌
				if (!empty($selectedIds)) {
					$existingIds = array_column($res['data'], 'value');
					$missingIds = array_diff($selectedIds, $existingIds);

					if (!empty($missingIds)) {
						$missingRes = $BaseDb->get(
							'bc_brand',
							['brand_id as value', 'brand_name as name'],
							sprintf(" and brand_id in (%s)", implode(',', $missingIds))
						);
						$res['data'] = array_merge($missingRes['data'], $res['data']);
					}
				}
				break;
			case 'model1':
				$where = "";
				$order = " order by mod1_name ASC limit 20";
				if ($Params['keyword']) {
					$where .= sprintf(" and mod1_name like '%%%s%%' ", $keyword);
				}
				if ($Params['brand_id']) {
					$where .= sprintf(" and mod1_brand_id in (%s) ", implode(',', explode(',', $Params['brand_id'])));
				}

				$res = $BaseDb->get('bc_model1', ['mod1_id as value', 'mod1_name as name'], sprintf(" %s %s", $where, $order));
				// 如果有 selected_ids，则补充缺失的品牌
				if (!empty($selectedIds)) {
					$existingIds = array_column($res['data'], 'value');
					$missingIds = array_diff($selectedIds, $existingIds);

					if (!empty($missingIds)) {
						$missingRes = $BaseDb->get(
							'bc_model1',
							['mod1_id as value', 'mod1_name as name'],
							sprintf(" and mod1_id in (%s)", implode(',', $missingIds))
						);
						$res['data'] = array_merge($missingRes['data'], $res['data']);
					}
				}
				break;
			case 'model2':
				$where = "";
				$order = " order by mod2_name ASC limit 20";
				if ($Params['keyword']) {
					$where .= sprintf(" and mod2_name like '%%%s%%'", $keyword);
				}
				if ($Params['mod1_id']) {
					$where .= sprintf(" and mod2_mod1_id in (%s) ", implode(',', explode(',', $Params['mod1_id'])));
				}
				$res = $BaseDb->get('bc_model2', ['mod2_id as value', 'mod2_name as name'], sprintf(" %s %s", $where, $order));
				// 如果有 selected_ids，则补充缺失的品牌
				if (!empty($selectedIds)) {
					$existingIds = array_column($res['data'], 'value');
					$missingIds = array_diff($selectedIds, $existingIds);

					if (!empty($missingIds)) {
						$missingRes = $BaseDb->get(
							'bc_model2',
							['mod2_id as value', 'mod2_name as name'],
							sprintf(" and mod2_id in (%s)", implode(',', $missingIds))
						);
						$res['data'] = array_merge($missingRes['data'], $res['data']);
					}
				}
				break;
			case 'province':
				$Ypw = new YpwBase();
				$where = '';
				$order = ' and pc_pid=0 order by pc_id,pc_seq ASC';
				if ($Params['keyword']) {
					$where = sprintf(" and pc_name like '%%%s%%' ", $keyword);
				}
				$res = $Ypw->Get('yp_province_city', ['pc_id as value', 'pc_name as name'], sprintf(" %s %s", $where, $order));
				// 补充选中的省份
				if (!empty($selectedIds)) {
					$existingIds = array_column($res['data'], 'value');
					$missingIds = array_diff($selectedIds, $existingIds);

					if (!empty($missingIds)) {
						$missingRes = $Ypw->get(
							'yp_province_city',
							['pc_id as value', 'pc_name as name'],
							sprintf(" and pc_id in (%s)", implode(',', $missingIds))
						);
						$res['data'] = array_merge($missingRes['data'], $res['data']);
					}
				}
				array_push($res['data'], ['value' => 0, 'name' => '其他']);
				break;
			case 'city':
				$Ypw = new YpwBase();
				$where = '';
				$order = ' and a.pc_pid=0 order by a.pc_seq,a.pc_name limit 20';
				if ($Params['keyword']) {
					$where = sprintf(" and b.pc_name like '%%%s%%'", $keyword);
				}

				$table  = 'yp_province_city as a 
				join yp_province_city as b on a.pc_id=b.pc_pid';
				$res = $Ypw->Get($table, ['b.pc_id as value', 'b.pc_name as name'], sprintf(" %s %s", $where, $order));
				// 补充选中的城市
				if (!empty($selectedIds)) {
					$existingIds = array_column($res['data'], 'value');
					$missingIds = array_diff($selectedIds, $existingIds);

					if (!empty($missingIds)) {
						$missingRes = $Ypw->get(
							'yp_province_city',
							['pc_id as value', 'pc_name as name'],
							sprintf(" and pc_id in (%s)", implode(',', $missingIds))
						);
						$res['data'] = array_merge($missingRes['data'], $res['data']);
					}
				}
				array_push($res['data'], ['value' => 0, 'name' => '其他']);
				break;
			case 'from':
				$res = ['status' => true, 'data' => [['value' => 'PJL', 'name' => '跑街令'], ['value' => 'SUPER', 'name' => '目录'], ['value' => 'WXROBOT', 'name' => '机器人'], ['value' => 'API', 'name' => '接口']]];
				break;
		}

		LibFc::ajaxJsonEncode($res);
	}
	

	/**
	 * @method 汽配报表-品牌
	 * @author hongzhang 
	 * @copyright 2025-10-11
	 */
	public function ypBrandCharts()
	{
		if ($this->supData['shop_report_industry'] < time()) {
			return LibTpl::Error('您的服务已到期，请联系管理员续费！');
		}
		$Params = mvc::$URL_PARAMS;
		$tjDb = mvc::$cfg['DB']['API_TJ']['db_name'];
		$BaseDb = new BaseDb(mvc::$cfg['DB']['API_TJ']);
		$isExport = !empty($Params['export']);

		// 处理月份参数
		$current = strtotime(date('Y-m-1'));
		$endDate = date('Y-m', strtotime('-1 month', $current));
		$startDate = date('Y-m', strtotime('-1 year', $current));

		// 最早时间不能早于数据库中存在数据的最早时间
		$dbEarliestDate = '';
		$statisticTable = $tjDb . '.at_report_industry_month';
		$statisticWhere = '';
		if ($Params['level'] === 'brand') {
			$statisticTable = $tjDb . '.at_report_industry_item';
			$statisticWhere = "AND ari_type = 'brand'";
		}
		$res = $BaseDb->get($statisticTable, ['MIN(ari_date) as earliest_date'], $statisticWhere, true);
		if ($res['data']) {
			$earliestDate = $res['data']['earliest_date'];
			$dbEarliestDate = date('Y-m', strtotime($earliestDate . '01'));
			$startDate =  $startDate < $dbEarliestDate ? $dbEarliestDate : $startDate;
		}

		LibTpl::Set('limitYear', [
			'minYear' => $startDate . '-1',
			'maxYear' => $endDate . '-1'
		]);


		// 处理预设参数 3个月或6个月
		if (isset($Params['preset'])) {
			switch ($Params['preset']) {
				case 'recent3':
					$startDate = date('Y-m', strtotime("-3 month")) < $dbEarliestDate ? $dbEarliestDate : date('Y-m', strtotime("-3 month"));
					$endDate = date('Y-m', strtotime("-1 month"));
					break;
				case 'recent6':
					$startDate = date('Y-m', strtotime("-6 month")) < $dbEarliestDate ? $dbEarliestDate : date('Y-m', strtotime("-6 month"));
					$endDate = date('Y-m', strtotime("-1 month"));
					break;
			}
		}

		if (!$Params['betime']) {
			$Params['betime'] = $startDate . ' ~ ' . $endDate;
		}
		$dateArr = explode(' ~ ', $Params['betime']);
		$startMonth = date('Ym', strtotime(trim($dateArr[0])));
		$endMonth = date('Ym', strtotime(trim($dateArr[1])));

		// 分页参数
		$page = isset($Params['page']) ? intval($Params['page']) : 1;
		$perPage = isset($_COOKIE['perPage']) ? (int)$_COOKIE['perPage'] : 20; // 每页显示20条记录
		
		// 如果是导出，则不进行分页
		if ($isExport) {
			$offset = 0;
			$perPage = 999999; // 设置一个很大的数值来获取所有数据
		} else {
			$offset = ($page - 1) * $perPage;
		}

		// 如果导出参数存在且ID参数不为空，使用导出参数中的ID列
		$filterIds ="";
		if($isExport && !empty($Params['ids'])){
			switch ($Params['level']) {
				case 'brand':
					$filterIds = "AND i1.ari_keyid IN ({$Params['ids']})";
					break;
				case 'series':
					$filterIds = "AND i1.ari_keyid2 IN ({$Params['ids']})";
					break;
				case 'year':
					$filterIds = "AND i1.ari_keyid2 IN ({$Params['ids']})";
					break;
			}
		}
		// 第一步：获取总热度（用于占比计算）和总数
		if ($Params['level'] === 'brand') {
			//所有品牌总热度
			$totalHeatQuery = sprintf(
				"SELECT 
				SUM(total_heat) as total_all_heat,
				COUNT(*) as total_rows
			FROM (	
				SELECT 
					ari_keyid,
					SUM(art_hotpv) as total_heat
				FROM {$tjDb}.at_report_industry_item i1
				WHERE i1.ari_date BETWEEN '%s' AND '%s'
					  {$statisticWhere}
				GROUP BY ari_keyid
			) as brand_totals",
				$startMonth,
				$endMonth
			);
		} else if ($Params['level'] === 'series') {
			// 单一品牌下所有车系热度
			$totalHeatQuery = sprintf(
				"SELECT
				SUM(total_heat) as total_all_heat,
				COUNT(*) as total_rows
			FROM(
				SELECT
					i1.ari_keyid2,
					SUM(art_hotpv) as total_heat
					FROM {$tjDb}.at_report_industry_item i1
					WHERE
						i1.ari_keyid = %d
						AND i1.ari_type = 'brand_model1'
						AND i1.ari_date BETWEEN '%s' AND '%s'
					GROUP BY i1.ari_keyid2
			) as series_totals",
				$Params['brand_id'],
				$startMonth,
				$endMonth
			);
		} else if ($Params['level'] === 'year') {
			//单一品牌下所有车代热度
			$totalHeatQuery = sprintf(
				"SELECT
				SUM(total_heat) as total_all_heat,
				COUNT(*) as total_rows
			FROM(
				SELECT
					ari_keyid2,
					SUM(art_hotpv) as total_heat
					FROM {$tjDb}.at_report_industry_item i1
					WHERE
						i1.ari_keyid = %d
						AND i1.ari_type = 'brand_model2'
						AND i1.ari_date BETWEEN '%s' AND '%s'
					GROUP BY ari_keyid2
			) as series_totals",
				$Params['brand_id'],
				$startMonth,
				$endMonth
			);
		}


		$totalRes = $BaseDb->BaseDb->Query($totalHeatQuery);
		if ($totalRes) {
			$totalData = $BaseDb->BaseDb->Fetch();
			$totalAllHeat = intval($totalData['total_all_heat']);
			$totalRows = intval($totalData['total_rows']);
		} else {
			$totalAllHeat = 0;
			$totalRows = 0;
		}

		// 第二步：获取分页后的品牌(车系/车代)列表
		if ($Params['level'] === 'brand') {
			$brandSummaryTable = sprintf(
				"
			(SELECT 
				ari_keyid,
				brand_name,
				SUM(art_hotpv) as total_heat
			FROM {$tjDb}.at_report_industry_item i1
			LEFT JOIN {$tjDb}.bc_brand ON i1.ari_keyid = brand_id
			WHERE i1.ari_date BETWEEN '%s' AND '%s'
				  {$statisticWhere}
				  {$filterIds}
			GROUP BY i1.ari_keyid
			ORDER BY total_heat DESC
			LIMIT %d, %d
			) as brand_summary",
				$startMonth,
				$endMonth,
				$offset,
				$perPage
			);
			$summaryFields = ['ari_keyid as brand_id', 'brand_name', 'total_heat'];
		} else if ($Params['level'] === 'series') {
			$brandSummaryTable = sprintf(
				"
			(SELECT 
				ari_keyid2,
				bb.brand_name as brand_name,
				mod1_name as series_name,
				SUM(art_hotpv) as total_heat
			FROM {$tjDb}.at_report_industry_item i1
			LEFT JOIN {$tjDb}.bc_model1 bm1 ON i1.ari_keyid2 = bm1.mod1_id
			LEFT JOIN {$tjDb}.bc_brand bb ON bm1.mod1_brand_id = bb.brand_id
			WHERE
				i1.ari_keyid = %d
				AND i1.ari_type = 'brand_model1'
				AND i1.ari_date BETWEEN '%s' AND '%s'
				  {$filterIds}
			GROUP BY i1.ari_keyid2
			ORDER BY total_heat DESC
			LIMIT %d, %d
			) as series_summary",
				$Params['brand_id'],
				$startMonth,
				$endMonth,
				$offset,
				$perPage
			);
			$summaryFields = ['ari_keyid2 as series_id', 'brand_name', 'series_name', 'total_heat'];
		} else if ($Params['level'] === 'year') {
			$brandSummaryTable = sprintf(
				"
			(SELECT 
				ari_keyid2,
				bb.brand_name as brand_name,
				mod2_name as year_name,
				mod2_start_year as start_year,
				mod2_end_year as end_year,
				SUM(art_hotpv) as total_heat
			FROM {$tjDb}.at_report_industry_item i1
			LEFT JOIN {$tjDb}.bc_model2 bm ON i1.ari_keyid2 = bm.mod2_id
			LEFT JOIN {$tjDb}.bc_model1 bm1 ON bm.mod2_mod1_id = bm1.mod1_id
			LEFT JOIN {$tjDb}.bc_brand bb ON bm.mod2_brand_id = bb.brand_id
			WHERE
				i1.ari_keyid = %d
				AND i1.ari_type = 'brand_model2'
				AND i1.ari_date BETWEEN '%s' AND '%s'
				  {$filterIds}
			GROUP BY ari_keyid2
			ORDER BY total_heat DESC
			LIMIT %d, %d
			) as series_summary",
				$Params['brand_id'],
				$startMonth,
				$endMonth,
				$offset,
				$perPage
			);
			$summaryFields = ['ari_keyid2 as year_id', 'brand_name', 'year_name','start_year', 'end_year', 'total_heat'];
		}
		$summaryRes = $BaseDb->Get($brandSummaryTable, $summaryFields, "");
		// 获取当前页的品牌ID列表
		$searchIds = [];
		$pagedRows = $summaryRes['data'];
		foreach ($pagedRows as $row) {
			if (isset($row['series_id'])) {
				$searchIds[] = $row['series_id'];
			} else if (isset($row['year_id'])) {
				$searchIds[] = $row['year_id'];
			} else {
				$searchIds[] = $row['brand_id'];
			}
		}
		// 如果没有品牌(车系/车代)数据，直接返回空结果
		if (empty($searchIds)) {
			$tableData = [];
			$monthList = [];
		} else {
			// 第二步：只查询当前页品牌的月度明细数据
			$searchIdsStr = implode(',', $searchIds);
			if ($Params['level'] === 'brand') {
				$detailTable = sprintf(
					"
				(SELECT 
					ari_keyid,
					brand_name,
					ari_date,
					SUM(art_hotpv) as month_heat
				FROM {$tjDb}.at_report_industry_item i1
				LEFT JOIN {$tjDb}.bc_brand ON i1.ari_keyid = brand_id
				WHERE i1.ari_date BETWEEN '%s' AND '%s'
				      {$statisticWhere}
				AND i1.ari_keyid IN (%s)
				GROUP BY i1.ari_keyid, i1.ari_date
				ORDER BY i1.ari_date DESC
				) as brand_detail",
					$startMonth,
					$endMonth,
					$searchIdsStr
				);

				$detailFields = ['ari_keyid as brand_id', 'brand_name', 'ari_date', 'month_heat'];
			} else if ($Params['level'] === 'series') {
				$detailTable = sprintf(
					"
				(SELECT 
					ari_keyid2,
					bb.brand_name as brand_name,
					mod1_name as series_name,
					ari_date,
					art_hotpv as month_heat
				FROM {$tjDb}.at_report_industry_item i1
				LEFT JOIN {$tjDb}.bc_model1 bm1 ON i1.ari_keyid2 = bm1.mod1_id
				LEFT JOIN {$tjDb}.bc_brand bb ON bm1.mod1_brand_id = bb.brand_id
				WHERE i1.ari_date BETWEEN '%s' AND '%s'
				AND i1.ari_keyid2 IN (%s)
				AND i1.ari_type = 'brand_model1'
				GROUP BY i1.ari_keyid2, i1.ari_date
				ORDER BY i1.ari_date DESC
				) as series_detail",
					$startMonth,
					$endMonth,
					$searchIdsStr
				);

				$detailFields = ['ari_keyid2 as series_id', 'brand_name', 'series_name', 'ari_date', 'month_heat'];
			} else if ($Params['level'] === 'year') {
				$detailTable = sprintf(
					"
				(SELECT 
					ari_keyid2,
					bb.brand_name as brand_name,
					bm.mod2_name as year_name,
					bm.mod2_start_year as start_year,
					bm.mod2_end_year as end_year,
					ari_date,
					SUM(art_hotpv) as month_heat
				FROM {$tjDb}.at_report_industry_item i1
				LEFT JOIN {$tjDb}.bc_model2 bm ON i1.ari_keyid2 = bm.mod2_id
				LEFT JOIN {$tjDb}.bc_model1 bm1 ON bm.mod2_mod1_id = bm1.mod1_id
				LEFT JOIN {$tjDb}.bc_brand bb ON bm.mod2_brand_id = bb.brand_id
				WHERE i1.ari_date BETWEEN '%s' AND '%s'
				AND i1.ari_keyid2 IN (%s)
				AND i1.ari_type = 'brand_model2'
				GROUP BY i1.ari_keyid2, i1.ari_date
				ORDER BY i1.ari_date DESC
				) as year_detail",
					$startMonth,
					$endMonth,
					$searchIdsStr
				);

				$detailFields = ['ari_keyid2 as year_id', 'brand_name', 'year_name', 'start_year', 'end_year', 'ari_date', 'month_heat'];
			}
			$detailRes = $BaseDb->Get($detailTable, $detailFields, "");
			// 组织月度数据
			$brandMonthData = [];
			foreach ($detailRes['data'] as $row) {
				if (isset($row['series_id'])) {
					$searchId = $row['series_id'];
				} else if (isset($row['year_id'])) {
					$searchId = $row['year_id'];
				} else {
					$searchId = $row['brand_id'];
				}
				if (!isset($brandMonthData[$searchId])) {
					$brandMonthData[$searchId] = [];
				}
				$brandMonthData[$searchId][$row['ari_date']] = intval($row['month_heat']);
			}
			// 组织最终数据（已按总热度排序）
			$tableData = [];

			// 计算月份范围
			$startTime = strtotime($startMonth . '01');
			$endTime = strtotime($endMonth . '01');
			$monthCount = 0;
			$currentTime = $endTime;
			while ($currentTime >= $startTime) {
				$monthCount++;
				$currentTime = strtotime('-1 month', $currentTime);
			}

			// 按照分页后的品牌顺序组织数据
			$index = $offset + 1; // 排名从当前页的起始位置开始
			foreach ($pagedRows as $row) {
				if (isset($row['series_id'])) {
					$searchId = $row['series_id'];
				} else if (isset($row['year_id'])) {
					$searchId = $row['year_id'];
				} else {
					$searchId = $row['brand_id'];
				}
				$totalHeat = intval($row['total_heat']);
				$percentage = $totalAllHeat > 0 ? round(($totalHeat / $totalAllHeat) * 100, 2) : 0;
				if ($Params['level'] === 'brand') {
					$rowData = [
						'brand_id' => $searchId,
						'brand_name' => $row['brand_name'],
						'percentage' => $percentage . '%',
						'total_hot' => $totalHeat,
						'rank' => $index++,
					];
				} else if ($Params['level'] === 'series') {
					$rowData = [
						'series_id' => $searchId,
						'brand_name' => $row['brand_name'],
						'series_name' => $row['series_name'],
						'percentage' => $percentage . '%',
						'total_hot' => $totalHeat,
						'rank' => $index++,
					];
				} else if ($Params['level'] === 'year') {
					$rowData = [
						'year_id' => $searchId,
						'brand_name' => $row['brand_name'],
						'year_name' => $row['year_name'],
						'year' => $row['start_year'] . '-' . ($row['end_year'] ? $row['end_year'] : '至今'),
						'percentage' => $percentage . '%',
						'total_hot' => $totalHeat,
						'rank' => $index++,
					];
				}


				// 添加各月份数据（按月份倒序）
				$currentTime = $endTime;
				$yearlyData = []; // 按年份分组的数据

				for ($i = 0; $i < $monthCount; $i++) {
					$month = date('Ym', $currentTime);
					$year = date('Y', $currentTime);

					$monthValue = isset($brandMonthData[$searchId][$month]) ? $brandMonthData[$searchId][$month] : 0;
					$rowData[$month] = $monthValue;

					if (!isset($yearlyData[$year])) {
						$yearlyData[$year] = [
							'total' => 0,
							'total' => 0,
						];
					}

					// 累计月度数据用于计算月均
					$yearlyData[$year]['total'] += $monthValue;
					// 仅当有数据时才计数
					if ($monthValue > 0) {
						$yearlyData[$year]['count']++;
					}
					$currentTime = strtotime('-1 month', $currentTime);
				}

				// 计算并添加年均数据
				foreach ($yearlyData as $year => $data) {
					$yearlyData[$year]['avg'] = $data['count'] > 0 ? round($data['total'] / $data['count'], 0) : 0;
					$rowData[$year . '_avg'] = $yearlyData[$year]['avg'];
				}

				$tableData[] = $rowData;
			}

			// 动态生成月份列表
			$monthList = [];
			$yearSet = []; // 记录涉及的年份
			$currentTime = $endTime;
			for ($i = 0; $i < $monthCount; $i++) {
				$value = date('Ym', $currentTime);
				$year = date('Y', $currentTime);
				$monthList[] = ['name' => $value, 'value' => $value, 'width' => '70'];
				$yearSet[$year] = true;
				$currentTime = strtotime('-1 month', $currentTime);
			}

			// 添加各年份的月均列（按年份倒序）
			$years = array_keys($yearSet);
			rsort($years); // 年份倒序
			foreach ($years as $year) {
				$monthList[] = ['name' => $year . '年月均', 'value' => $year . '_avg', 'width' => '80'];
			}
		}
		$levelColumns = [
			['name' => '品牌名称', 'value' => 'brand_name', 'width' => '70',],
		];
		if ($Params['level'] == 'series') {
			$levelColumns[] = ['name' => '车系', 'value' => 'series_name', 'width' => '70',];
		}
		if ($Params['level'] == 'year') {
			$levelColumns[] = ['name' => '车代', 'value' => 'year_name', 'width' => '70',];
			$levelColumns[] = ['name' => '年份', 'value' => 'year', 'width' => '120',];
		}
		$fixedColumns = [
			['name' => '排名', 'value' => 'rank', 'width' => '45'],
			['name' => '占比', 'value' => 'percentage', 'width' => '50',],
			['name' => '操作', 'type' => 'btn', 'width' => $Params['level'] === 'brand' ? '240px' : '120px'],
			['name' => '总热度', 'value' => 'total_hot', 'width' => '70',],
		];
		//分布统计按钮
		$buttonList = [
			['name' => '按车系', 'params' => 'level=series'],
			['name' => '按车代', 'params' => 'level=year'],
		];
		$tableColumns = array_merge($levelColumns, $fixedColumns, $monthList);

		if (!empty($Params['export'])) {
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet();
			
			// 设置列宽
			$columnIndex = 'A';
			foreach($tableColumns as $col){
				if($col['name'] != '操作'){
					$sheet->getColumnDimension($columnIndex)->setWidth(15);
					$columnIndex++;
				}
			}
			// 设置表头
			$columnIndex = 'A';
			$row = 1;
			foreach($tableColumns as $col){
				if($col['name'] != '操作'){
					$sheet->setCellValue($columnIndex . $row, $col['name']);
					$columnIndex++;
				}
			}
			
			// 填充数据
			$row = 2;
			foreach ($tableData as $data) {
				$columnIndex = 'A';
				foreach($tableColumns as $col){
					if($col['name'] != '操作'){
						$value = isset($data[$col['value']]) ? $data[$col['value']] : '';
						$sheet->setCellValue($columnIndex . $row, $value);
						$columnIndex++;
					}
				}
				$row++;
			}
			
			// 生成文件名
			$levelName = '';
			switch($Params['level']) {
				case 'brand':
					$levelName = '品牌';
					break;
				case 'series':
					$levelName = '车系';
					break;
				case 'year':
					$levelName = '车代';
					break;
				default:
					$levelName = '品牌';
			}
			
			$fileName = '汽车行业热度统计-' . $levelName;
			$this->downloadExcel($spreadsheet, $fileName, 'Xlsx');
		}

		LibTpl::Set('monthList', $monthList);
		LibTpl::Set('tableColumns', $tableColumns);
		LibTpl::Set('tableData', $tableData);
		LibTpl::Set('buttonList', $buttonList);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('pageMsg', LibPage::Show($totalRows, $perPage, true));
		LibTpl::Set('title', '汽配报表-品牌');
		LibTpl::Put();
	}


	// public function YPModelCharts() {}

	public function ypRegionCharts()
	{
		if ($this->supData['shop_report_industry'] < time()) {
			return LibTpl::Error('您的服务已到期，请联系管理员续费！');
		}
		$Params = mvc::$URL_PARAMS;
		$BaseDb = new BaseDb(mvc::$cfg['DB']['API_TJ']);
		$current = strtotime(date('Y-m-1'));
		$endDate = date('Y-m', strtotime('-1 month', $current)); // 当前月的上个月
		//已有数据的最小时间
		$minRes = $BaseDb->get('at_report_industry_month', ['min(ari_date) as min_date'], '', true);
		$startDate = date('Ym', strtotime('-12 months', $current)) < $minRes['data']['min_date'] ? substr($minRes['data']['min_date'], 0, 4) . '-' . substr($minRes['data']['min_date'], 4, 2) : date('Y-m', strtotime('-12 months', $current));
		LibTpl::Set('limitYear', [
			'minYear' => $startDate . '-1',
			'maxYear' => $endDate . '-1'
		]);
		if (!$Params['betime']) {
			$Params['betime'] = $startDate . ' ~ ' . $endDate;
		}
		//所有品牌
		$brandArr = $Params['brand'] ? explode(',', $Params['brand']) : [];
		$where = " order by brand_initial ASC";

		$res = $BaseDb->get('bc_brand', ['brand_id as value', 'brand_name as name'], $where);
		// 如果有选中的品牌，则添加 selected 属性
		if (!empty($brandArr)) {
			foreach ($res['data'] as &$brand) {
				$brand['selected'] = in_array($brand['value'], $brandArr);
			}
		}
		LibTpl::Set('brandList', $res['data']);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '汽配报表-地区');
		LibTpl::Put();
	}

	/**
	 * @method 获取汽配报表-地区数据
	 * @author zhengweihua 
	 * @copyright 2025-10-11
	 */
	public function getRegionTjData()
	{
		$Params = mvc::$URL_PARAMS;
		//品牌:brand 品牌_车系:brand_model1 品牌_车代:brand_model2 省份:province 品牌_省份:brand_province  省_市:province_city
		$where = '';
		$hasCondition = false;
		$ari_type = '';

		if($Params['betime']){
			$dateArr = explode('~', $Params['betime']);

			if (count($dateArr) == 2) {
				$where .= sprintf(" and ari_date >= '%s' ", date('Ym', strtotime(trim($dateArr[0]))));
				$where .= sprintf(" and ari_date <= '%s' ", date('Ym', strtotime(trim($dateArr[1]))));
			}
		}
		//没有车代_省份的ari_type
		if($Params['mod2_id']){
			$hasCondition = true;
			$tmp = explode(',', $Params['mod2_id']);
			if (count($tmp) == 1) {
				$isSingleMod1 = $tmp[0];
			}
			$where .= sprintf(" and mod2_id in (%s) ", implode(',', $tmp));
			
		}elseif($Params['mod1_id']){
			$hasCondition = true;

			$tmp = explode(',', $Params['mod1_id']);
			if (count($tmp) == 1) {
				$isSingleMod2 = $tmp[0];
			}
			$where .= sprintf(" and mod2_mod1_id in (%s) ", implode(',', $tmp));
			
			
		}elseif ($Params['brand']) {
			$ari_type = 'brand_province';

			$tmp = explode(',', $Params['brand']);
			if (count($tmp) == 1) {
				$isSingleBrand = $tmp[0];
			}
			$where .= sprintf(" and ari_keyid in (%s) ", implode(',', $tmp));
		}else{
			$ari_type = 'province';
		}

		$BaseDb = new BaseDb(mvc::$cfg['DB']['API_TJ']);

		if ($hasCondition) {
			$groupby = 'group by ari_province';
			$table = 'at_report_industry_month 
			join bc_model2 on mod2_id = ari_mod2_id';
			$field  = ['ari_province as id', 'sum(art_hotpv) as value'];
		} else {
			$groupby = 'group by ari_keyid,ari_keyid2';
			$field = ['ari_keyid','ari_keyid2', 'sum(art_hotpv) as value'];
			$table = 'at_report_industry_item';

			$where .= sprintf(" AND ari_type='%s' ",$ari_type);
		}

		$res = $BaseDb->get($table, $field, sprintf(" %s  %s ORDER BY value DESC", $where, $groupby));
		if($res['data'])
		{	
			$rows = [];
			if($ari_type=='brand_province'){
				
				foreach ($res['data'] as $val) {
					$rows[] = [
						'id' => $val['ari_keyid2'],
						'value' => $val['value'],
					];
				}
			}else if($ari_type=='province'){
				foreach ($res['data'] as $val) {
					$rows[] = [
						'id' => $val['ari_keyid'],
						'value' => $val['value'],
					];
				}
			}else{
				$rows = $res['data'];
			}
	
			$totalCounts = array_sum(array_column($rows, 'value'));
			foreach ($rows as &$val) {
				$val['percent'] = $val['value'] > 0 ? round($val['value'] / $totalCounts * 100, 2) . '%' : '';
			}
			unset($val);
		}
		
		
		// 获取所有省份数据
		$allProvincesRes = $BaseDb->get('yp_province_city', ['pc_id', 'pc_name'], ' and pc_pid=0 order by pc_seq');
		$allProvinces = array_column($allProvincesRes['data'], 'pc_name', 'pc_id');

		// 填充缺失的省份数据
		$existingProvinceIds = array_column($rows, 'id');
		foreach ($allProvinces as $provinceId => $provinceName) {
			if (!in_array($provinceId, $existingProvinceIds)) {
				$rows[] = [
					'name' => $provinceName,
					'value' => 0,
					'id' => $provinceId,
					'percent' => ''
				];
			} else {
				$rows[array_search($provinceId, $existingProvinceIds)]['name'] = $provinceName;
			}
		}
		//暂时只取一个名字
		$title = '汽配报表';
		if ($isSingleMod2) {
			$res = $BaseDb->get('bc_model2 join bc_brand on mod2_brand_id = brand_id', ['brand_name', 'mod2_name', 'mod2_start_year', 'mod2_end_year'], sprintf(' and mod2_id=%d', $isSingleMod2), true);
			$years = (!empty($res['data']['mod2_start_year']) || !empty($res['data']['mod2_end_year'])) ?
				((!empty($res['data']['mod2_start_year']) && $res['data']['mod2_start_year'] > 0 ? $res['data']['mod2_start_year'] : '') .
					'-' .
					(!empty($res['data']['mod2_end_year']) && $res['data']['mod2_end_year'] > 0 ? $res['data']['mod2_end_year'] : '')) :
				'';
			$title = $res['data']['brand_name'] . ' ' . $res['data']['mod2_name'] . '(' . $years . ')';
		} elseif ($isSingleMod1) {
			$res = $BaseDb->get('bc_model1 join bc_brand on mod1_brand_id = brand_id', ['brand_name', 'mod1_name'], sprintf(' and mod1_id=%d', $isSingleMod1), true);
			$title =  $res['data']['brand_name'] . ' ' . $res['data']['mod1_name'];
		} elseif ($isSingleBrand) {
			$res = $BaseDb->get('bc_brand', ['brand_name'], sprintf(' and brand_id=%d', $isSingleBrand), true);
			$title = $res['data']['brand_name'];
		}
		$data['series'] = [
			[
				'title' => $title  . '地区分布 ',
				'type' => 'map',
				'mapType' => 'china',
				'roam' => true,
				'data' => $rows
			]
		];
		LibFc::ajaxJsonEncode($data);
	}

	/**
	 * @method 地区详情统计
	 * @author zhengweihua 
	 * @copyright 2025-10-13
	 */
	public function regionCharts()
	{
		$Params = \mvc::$URL_PARAMS;
		$this->industryTj2($Params);
	}

	/**
	 * @method 
	 * @author zhengweihua 
	 * @copyright 2025-10-13
	 */
	public function ypModelCharts()
	{
		$Params = \mvc::$URL_PARAMS;
		$Params['group'] = $_GET['group'] ?: ['mod2_mod1_id'];
		$Params['singleDimen'] = 1;
		$this->industryTj2($Params);
	}


	public function industryTj2($Params)
	{
		if($this->supData['shop_report_industry']<time()){
			return LibTpl::Error('您的服务已到期，请联系管理员续费！');
		}
		$group = $Params['group'] ?: [];

		$BaseDb = new BaseDb(mvc::$cfg['DB']['API_TJ']);
		//type：地区传过来的标识
		if (!$Params['type']) 
		{
			$current = strtotime(date('Y-m-1'));
			$endDate = date('Y-m', strtotime('-1 month', $current)); // 当前月的上个月
			//已有数据的最小时间
			$minRes = $BaseDb->get('at_report_industry_month', ['min(ari_date) as min_date'], '',true);
			$startDate = date('Ym',strtotime('-12 months', $current))<$minRes['data']['min_date']? substr($minRes['data']['min_date'], 0, 4).'-'.substr($minRes['data']['min_date'], 4, 2):date('Y-m',strtotime('-12 months', $current));

			LibTpl::Set('limitYear', [
				'minYear' => $startDate . '-1',
				'maxYear' => $endDate . '-1'
			]);
			if (!$Params['betime']) {
				$Params['betime'] = $startDate . ' ~ ' . $endDate;
			}

			//所有品牌
			if ($Params['brand']) {
				$brandArr = explode(',', $Params['brand']);
			}
			$where = " order by brand_initial ASC";
			
			$res = $BaseDb->get('bc_brand', ['brand_id as value', 'brand_name as name'], $where);
			// 如果有选中的品牌，则添加 selected 属性
			if (!empty($brandArr)) {
				foreach ($res['data'] as &$brand) {
					$brand['selected'] = in_array($brand['value'], $brandArr);
				}
			}
			LibTpl::Set('brandList', $res['data']);
			

			//车系  车代
			$groupTypeArr = ['mod2_mod1_id' => '车系', 'mod2_id' => '车代'];
			LibTpl::Set('groupTypeArr', $groupTypeArr);
			
		}
		LibTpl::Set('Params', $Params);

		//获取分页参数
		$page = isset($Params['page']) ? max(1, (int)$Params['page']) : 1;
		$perPage = isset($_COOKIE['perPage']) ? (int)$_COOKIE['perPage'] : 20;
		$offset = ($page - 1) * $perPage;


		$showCols = [
			'brand' =>false,
			'mod1' => false,
			'mod2' => false,
			'province' => false,
			'city' =>false,
		];

		//品牌:brand 品牌_车系:brand_model1 品牌_车代:brand_model2 省份:province 品牌_省份:brand_province  省_市:province_city
		$where = '';
		if($Params['betime']){
			$dateArr = explode('~', $Params['betime']);
			if (count($dateArr) == 2) {
				$where .= sprintf(" and ari_date >= '%s' ", date('Ym', strtotime(trim($dateArr[0]))));
				$where .= sprintf(" and ari_date <= '%s' ", date('Ym', strtotime(trim($dateArr[1]))));
			}
		}
		if($Params['type']=='province'){
			$perPage = 100;
			$showCols['province'] = true;
			$groupFields = 'ari_province';
			$level = 'province';
			if ($Params['mod2_id']) {
				$hasCondition = true;
				$where .= sprintf(" and mod2_id = %d ", $Params['mod2_id']);
			}elseif ($Params['mod1_id']) {
				$hasCondition = true;
				$where .= sprintf(" and mod2_mod1_id = %d ", $Params['mod1_id']);
			}
			elseif($Params['brand']){
				$ari_type = 'brand_province';
				$where .= sprintf(" and ari_keyid = %d ", $Params['brand']);
			}else{
				$ari_type = 'province';
			}
		}elseif ($Params['type'] == 'city') {
			$showCols['city'] = true;
			$groupFields = 'ari_city';
			$level = 'city';
			if($Params['mod2_id']){
				$hasCondition = true;
				$where .= sprintf(" and mod2_id = %d ", $Params['mod2_id']);
				if ($Params['province_id']) {
					$where .= sprintf(" and ari_province = %d ", $Params['province_id']);
				}	
			}elseif ($Params['mod1_id']) {
				$hasCondition = true;
				$where .= sprintf(" and mod2_mod1_id = %d ", $Params['mod1_id']);
				if ($Params['province_id']) {
					$where .= sprintf(" and ari_province = %d ", $Params['province_id']);
				}	
			}
			elseif($Params['brand']){
				$hasCondition = true;
				$where .= sprintf(" and mod2_brand_id = %d ", $Params['brand']);
				if ($Params['province_id']) {
					$where .= sprintf(" and ari_province = %d ", $Params['province_id']);
				}	
			}else{
				$ari_type = 'province_city';
				if ($Params['province_id']) {
					$where .= sprintf(" and ari_keyid = %d ", $Params['province_id']);
				}
			}
		} elseif ($Params['type'] == 'brand') {
			$showCols['brand'] = true;
			$ari_type = 'brand_province';
			if ($Params['province_id']) {
				$where .= sprintf(" and ari_keyid2 = %d ", $Params['province_id']);
			}
		} elseif ($Params['brand']) {
			$showCols['brand'] = true;
			$ari_type = 'brand';
			$where .= sprintf(" and ari_keyid in (%s) ", implode(',', explode(',', $Params['brand'])));
			if ($Params['mod2_id']) {
				$showCols['mod2'] = true;
				$ari_type = 'brand_model2';
				$where .= sprintf(" and ari_keyid2 in (%s) ", implode(',', explode(',', $Params['mod2_id'])));
			} elseif ($Params['mod1_id']) {
				$showCols['mod1'] = true;
				$ari_type = 'brand_model1';
				$where .= sprintf(" and ari_keyid2 in (%s) ", implode(',', explode(',', $Params['mod1_id'])));
			}
			if ($Params['province_id']) {
				$showCols['province'] = true;
				$ari_type = 'brand_province';
				$where .= sprintf(" and ari_keyid2 in (%s) ", implode(',', explode(',', $Params['province_id'])));
			}
		} elseif ($Params['province_id']) {
			$showCols['province'] = true;
			$ari_type = 'province';
			$where .= sprintf(" and ari_keyid in (%s) ", implode(',', explode(',', $Params['province_id'])));
			// if ($Params['type'] == 'city') {
			// 	$showCols['city'] = true;
			// 	$ari_type = 'province_city';
			// 	$where .= sprintf(" and ari_keyid2 in (%s) ", implode(',', explode(',', $Params['city_id'])));
			// }
		} elseif ($Params['mod2_id']) {
			$showCols['mod2'] = true;
			$ari_type = 'brand_model2';
			$where .= sprintf(" and ari_keyid2 in (%s) ", implode(',', explode(',', $Params['mod2_id'])));
		} elseif ($Params['mod1_id']) {
			$showCols['mod1'] = true;
			$ari_type = 'brand_model1';
			$where .= sprintf(" and ari_keyid2 in (%s) ", implode(',', explode(',', $Params['mod1_id'])));
		}

		if(in_array('mod2_id',$group)){
			$showCols['mod2'] = true;
			$showCols['brand'] = true;
			$ari_type = 'brand_model2';
		}elseif (in_array('mod2_mod1_id',$group)) {
			$showCols['mod1'] = true;
			$showCols['brand'] = true;
			$ari_type = 'brand_model1';
		}

		// 获取所有时间范围内的月份
		$startDate = date('Ym', strtotime(trim($dateArr[0])));
		$endDate = date('Ym', strtotime(trim($dateArr[1])));
		$months = [];
		$current = $startDate;
		while ($current <= $endDate) {
			$months[] = $current;
			$current = date('Ym', strtotime('+1 month', strtotime($current . '01')));
		}
		// 倒序排列月份
		$months = array_reverse($months);
		// 添加年份分组计算月均值
		$yearMonths = [];
		foreach ($months as $month) {
			$year = substr($month, 0, 4);
			if (!isset($yearMonths[$year])) {
				$yearMonths[$year] = [];
			}
			$yearMonths[$year][] = $month;
		}
		if($hasCondition){
			$Params['level'] = $level;
			//指定品牌、车系、车代下的某一个省份的城市数据等多维度查询，
			$table = 'at_report_industry_month 
			join bc_model2 on ari_mod2_id=mod2_id';
			// 获取总条数
			$table1 = "(
				SELECT $groupFields
				FROM $table
				WHERE 1=1 $where
				group by $groupFields
			) as tmp";
			$countRes = $BaseDb->get($table1, ['count(*) as count'], '', true);
			$total = $countRes['data']['count'];
			//获取总热度
			$totalRes = $BaseDb->get($table, ['SUM(art_hotpv) as totalCounts'], $where, true);
			$totalCounts = $totalRes['data']['totalCounts'] ?: 0;

			// 查询数据
			$field = ["$groupFields as ari_keyid",'SUM(art_hotpv) as heat'];
			if($Params['isExport']){
				
				$res = $BaseDb->get($table, $field, sprintf(" %s GROUP BY ari_keyid ORDER BY heat DESC", $where));
			}else{
				$res = $BaseDb->get($table, $field, sprintf(" %s GROUP BY ari_keyid ORDER BY heat DESC LIMIT %d,%d", $where, $offset, $perPage));
			}
			
		}else{
			$table = 'at_report_industry_item';
				
			if($ari_type == 'brand_model2'){
				$Params['level'] = 'year';
			}
			elseif($ari_type == 'brand_model1'){
				
				$Params['level'] = 'series';
			}elseif ($ari_type=='province_city') {
				$Params['level'] = 'city';
			}elseif ($ari_type == 'brand') {
				$Params['level'] = 'brand';
			}elseif ($ari_type=='province') {
				$Params['level'] = 'province';
			}elseif ($ari_type == 'brand_province') {
				if($Params['brand']){
					$Params['level'] = 'province';
					$searchProvince = 1;
				}elseif ($Params['province_id']) {
					$Params['level'] = 'brand';
					$searchBrand = 1;
				}
			}

			$where .= sprintf(" AND ari_type='%s'",$ari_type);
			// 获取总数
			$table1 = "(
				SELECT ari_keyid
				FROM $table
				WHERE 1=1 $where
				group by ari_keyid,ari_keyid2
			) as tmp";

			$countRes = $BaseDb->get($table1, ['count(*) as count'], '', true);
			$total = $countRes['data']['count'];

			if(in_array($ari_type,['brand_model2','brand_model1'])){
				$total>300 && $total = 300;
			}

			// 获取总热度
			$totalRes = $BaseDb->get($table, ['SUM(art_hotpv) as totalCounts'], $where, true);
			$totalCounts = $totalRes['data']['totalCounts'] ?: 0;
			// 查询数据
			if(!$Params['isExport']){
				$field = ['ari_keyid','ari_keyid2','SUM(art_hotpv) as heat'];
				$res = $BaseDb->get($table, $field, sprintf(" %s GROUP BY ari_keyid,ari_keyid2 ORDER BY heat DESC LIMIT %d,%d", $where, $offset, $perPage));
			}else{
				$field = ['ari_keyid','ari_keyid2','SUM(art_hotpv) as heat'];
				$limit = '';
				if(in_array($ari_type,['brand_model2','brand_model1'])){
					$limit = ' limit 300';
				}
				$res = $BaseDb->get($table, $field, sprintf(" %s GROUP BY ari_keyid,ari_keyid2 ORDER BY heat DESC %s", $where,$limit));
			}
		}
		$result = [];
		if ($res['data']) {
			if($hasCondition){
				$ids = array_column($res['data'], 'ari_keyid');
				$where .= sprintf(" AND $groupFields in (%s) ", implode(',', $ids));
				$keykey = 'ari_keyid';
			}elseif(in_array($ari_type,['brand','province']) || $searchBrand){
				$ids = array_column($res['data'], 'ari_keyid');
				$where .= sprintf(" AND ari_keyid in (%s) ", implode(',', $ids));
				$keykey = 'ari_keyid';
			}
			else{
				$ids = array_column($res['data'], 'ari_keyid2');
				$where .= sprintf(" AND ari_keyid2 in (%s) ", implode(',', $ids));
				$keykey = 'ari_keyid2';
			}
			
			// 填充各月数据（从数据库查询月度详情）
			if($hasCondition)
			{
				$monthDetailRes = $BaseDb->get($table, ['ari_date', 'SUM(art_hotpv) AS heat',"$groupFields as ari_keyid"], 
				sprintf(" %s group by ari_date,$groupFields ORDER BY ari_date", $where));
			}else{
				$monthDetailRes = $BaseDb->get($table, ['ari_date', 'art_hotpv as heat','ari_keyid','ari_keyid2'], 
				sprintf(" %s ORDER BY ari_date", $where));
			}
			
			$monthData = [];
			foreach ($monthDetailRes['data'] as $key => $val) {
				$monthData[$val[$keykey]][$val['ari_date']] = intval($val['heat']);
			}

			
			// 根据不同维度获取名称
			if ($ari_type == 'brand_model2') {
				// 车型维度
				$nameRes = $BaseDb->get('bc_model2 
				join bc_model1 on mod2_mod1_id =mod1_id
				join bc_brand on mod2_brand_id =brand_id', ['brand_id','brand_name','mod1_name','mod2_id', 'mod2_name','mod2_start_year','mod2_end_year'], 
					sprintf(' and mod2_id in (%s)', implode(',', $ids)));
				foreach ($nameRes['data'] as $key => $val) {
					$val['years'] =(!empty($val['mod2_start_year']) || !empty($val['mod2_end_year'])) ? 
					((!empty($val['mod2_start_year']) && $val['mod2_start_year'] > 0 ? $val['mod2_start_year'] : '') . 
					'-' . 
					(!empty($val['mod2_end_year']) && $val['mod2_end_year'] > 0 ? $val['mod2_end_year'] : '')) : 
					'';
					$nameMap[$val['mod2_id']] = $val;
				}
			} else if ($ari_type == 'brand_model1') {
				// 车系维度
				$nameRes = $BaseDb->get(
					'bc_model1 join bc_brand on mod1_brand_id =brand_id',
					['brand_id', 'brand_name', 'mod1_id', 'mod1_name'],
					sprintf(' and mod1_id in (%s)', implode(',', $ids))
				);
				$nameMap = array_column($nameRes['data'], null, 'mod1_id');
			} else if ($ari_type == 'province_city' || $ari_type == 'province' || $hasCondition|| $searchProvince) {
				$nameRes = $BaseDb->get(
					'yp_province_city',
					['pc_id', 'pc_name'],
					sprintf(' and pc_id in (%s)', implode(',', $ids))
				);
				$nameMap = array_column($nameRes['data'], null, 'pc_id');
			} elseif ($ari_type == 'brand'||$searchBrand) {
				$nameRes = $BaseDb->get(
					'bc_brand',
					['brand_id', 'brand_name'],
					sprintf(' and brand_id in (%s)', implode(',', $ids))
				);
				$nameMap = array_column($nameRes['data'], null, 'brand_id');
			}

			// 组装结果，使其与多维度查询结构一致
			foreach ($res['data'] as $index => $row) {
				$nameMapItem = $nameMap[$row[$keykey]];

				$item = [
					'brand_id' => $nameMapItem['brand_id'] ?? '',
					'brand_name' => $nameMapItem['brand_name'] ?? '',
					'mod1_id' => $nameMapItem['mod1_id'] ?: '',
					'mod1_name' => $nameMapItem['mod1_name'] ?: '',
					'mod2_id' => $nameMapItem['mod2_id'] ?: '',
					'mod2_name' => $nameMapItem['mod2_name'] ?: '',
					'province'=>$nameMapItem['pc_name'] ?: '',
					'province_id'=>$nameMapItem['pc_id']?:'',
					'city'=>$nameMapItem['pc_name'] ?: '',
					'city_id'=>$nameMapItem['pc_id']?:'',
					'years' => $nameMapItem['years'] ?: '',
					'heat' => $row['heat'],
					'percent' => $totalCounts > 0 ? round(($row['heat'] / $totalCounts) * 100, 2) : 0,
					'rank' => $offset + $index + 1,
					'total' => $row['heat']
				];
				
				// 填充各月数据（单维度查询没有月度详情，所以都为0）
				foreach ($months as $key => $val) {
					$item[$val] = isset($monthData[$row[$keykey]][$val]) ? $monthData[$row[$keykey]][$val] : '';
				}
				
				// 计算各年份月均值
				foreach ($yearMonths as $year => $yearMonthList) {
					$yearTotal = 0;
					$monthCount = 0;
					foreach ($yearMonthList as $month) {
						if (isset($monthData[$row[$keykey]][$month]) && $monthData[$row[$keykey]][$month] > 0) {
							$yearTotal += $monthData[$row[$keykey]][$month];
							$monthCount++;
						}
					}
					$monthlyAverage = $monthCount > 0 ? ceil($yearTotal / $monthCount) : 0;
					$item[$year . '月均'] = $monthlyAverage;
				}
				
				$result[] = $item;
			}
		}

		LibTpl::Set('tjArr', $result);
		LibTpl::Set('Page', LibPage::Show($total, $perPage, true));

		
		// 也需要更新月份数组，包含年份月均值键
		foreach (array_keys($yearMonths) as $year) {
			$months[] = $year . '月均';
		}
		if($Params['isExport']){
			// 导出数据
			$showCols['rank'] =$showCols['percent'] = $showCols['total'] =1;
			$allArr = $result;
			foreach ($showCols as $field => $val) {
				if(!$val) continue;
				switch ($field) {
					case 'brand':
						$allArr['fields']['brand_name'] = '品牌';
						break;
					case 'mod1':
						$allArr['fields']['mod1_name'] = '车系';
						break;
					case 'mod2':
						$allArr['fields']['mod2_name'] = '车型';	
						$allArr['fields']['years'] = '年份';	
						break;
					case 'province':
						$allArr['fields']['province'] = '省份';	
						break;
					case 'city':
						$allArr['fields']['city'] = '城市';	
						break;
					case 'rank':
						$allArr['fields']['rank'] = '排名';	
						break;
					case 'percent':
						$allArr['fields']['percent'] = '占比(%)';	
						break;
					case 'total':
						$allArr['fields']['total'] = '总热度';	
						break;
				}
			}
			foreach ($months as $month) {
				$allArr['fields'][$month] = $month;
			}
			
		
			foreach ($months as $month) {
				$exportCols[$month] = $month;
			}
			$OthSExcel = new OthSExcel();
			$OthSExcel->writer($allArr);
			exit;
		}
		LibTpl::Set('Params', $Params);
		LibTpl::Set('showCols', $showCols);
		LibTpl::Set('group', $group);
		LibTpl::Set('months', $months);
		LibTpl::Set('title', '汽配报表-车型');
		LibTpl::Put('tj/chartsBase.php');
		
	}

	/**
	 * 下载Excel文件
	 * @param $newExcel obj \PhpOffice\PhpSpreadsheet\Spreadsheet;
	 * @param $filename string 文件名称
	 * @param $format string Xlsx|Xls
	 * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
	 */
	public function downloadExcel($newExcel, $filename, $format)
	{
		// $format只能为 xlsx 或 xls
		if ($format == 'Xlsx') {
			header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		} elseif ($format == 'Xls') {
			header('Content-Type: application/vnd.ms-excel');
		}

		header("Content-Disposition: attachment;filename="
			. $filename . date('Y-m-d') . '.' . strtolower($format));
		header('Cache-Control: max-age=0');
		$objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($newExcel, $format);

		$objWriter->save('php://output');
		exit;
	}
}
