<template>
	<div class="layout-padding">
		<div class="!overflow-auto px-1">
			<div class="el-card  p-9">
				<div class="flex justify-between">
					<Title :title="t('versionDistribution.analytics')" />

				</div>
				<div class="mt-2">
					<el-row shadow="hover" class="">
						<el-form :inline="true" :model="formData" ref="queryRef">
							<el-form-item>
								<el-date-picker v-model="formData.time" type="daterange" value-format="YYYY-MM-DD"
									:disabled-date="disableFuture" @change="handleRangeChange" class="!w-[250px]"
									start-placeholder="开始时间" end-placeholder="结束时间" />
							</el-form-item>
							<el-form-item>
								<FilterSelect v-model="formData.version" showAllVersions type="version"
									class="!w-[180px] ml-2" />
							</el-form-item>
						</el-form>
					</el-row>
				</div>
			</div>
			<version-trend-card v-model:selectedVersion="formData.version" :form-data="formData" :channel-options="formData.version" />
			<version-source-card v-if="formData.version !== ''" :form-data="formData" :selected-version="formData.version" />
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, defineAsyncComponent } from 'vue';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';

const VersionTrendCard = defineAsyncComponent(() => import('./components/version-trend-card.vue'));
const VersionSourceCard = defineAsyncComponent(() => import('./components/version-source-card.vue'));
const FilterSelect = defineAsyncComponent(() => import('/@/components/common/filter-select.vue'));

const { t } = useI18n();

const getDefaultDateRange = () => {
	const endDate = dayjs();
	const startDate = endDate.subtract(15, 'day');
	return [startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')];
};
const formData = ref<Record<string, any>>({
	time: getDefaultDateRange(), // 时间范围
});


function disableFuture(date: Date) {
	const today = new Date();
	today.setHours(0, 0, 0, 0);
	return date.getTime() > today.getTime();
}

function handleRangeChange(val: [string, string] | null) {
	if (!val) {
		return;
	}
	const [startStr, endStr] = val;
	const start = dayjs(startStr);
	let end = dayjs(endStr);
	// 限制最大跨度为两年（按天计算，不含边界再减一天）
	if (end.diff(start, 'day') >= 365 * 2) {
		end = start.add(2, 'year').subtract(1, 'day');
		formData.value.time = [start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD')];
	}
}
const Title = defineAsyncComponent(() => import('/@/components/Title/index.vue'));
</script>
 
<style lang="scss" scoped>
.highlight {
	color: #2196f3;
}
.el-form-item--default {
	margin-bottom: 0;
}
.el-form.el-form--inline .el-form-item--default.el-form-item:last-of-type,
.el-form.el-form--inline .el-form-item--small.el-form-item:last-of-type {
	margin-bottom: 0 !important;
}
</style>
