<template>
	<div>
		<el-card shadow="hover" class="border-none">
			<span class="title">监控ASIN每月平均评分</span>
			<div class="mb-1" style="display: flex; align-items: baseline; justify-content: space-between">
				<div style="display: flex; gap: 25px; margin-bottom: 10px">
					<div>
						<span style="font-size: 14px; padding-right: 4px; ">ASIN </span>
						<el-input v-model="searchAsin" clearable style="width: 180px" @change="fetchData" placeholder="请输入ASIN"></el-input>
					</div>
					<div>
						<span style="font-size: 14px; padding-right: 4px; ">SKU </span>
						<el-input v-model="searchSku" clearable style="width: 180px" @change="fetchData" placeholder="请输入SKU"></el-input>
					</div>
					<div>
						<span class="mr-1" style="font-size: 14px; ">时间选择 </span>
						<el-date-picker
							v-model="asinMonthDate"
							:clearable="false"
							:disabled-date="disabledDate"
							placeholder="选择月"
							style="width: 170px"
							type="month"
						>
						</el-date-picker>
					</div>
				</div>
				<div>
					<el-button :icon="Download" circle plain @click="handleDownload"></el-button>
				</div>
			</div>
			<el-card body-style="padding: 0" shadow="never">
				<vxe-grid :cell-style="cellStyle" :header-cell-style="headerStyle" show-overflow="tooltip" v-bind="gridOptions" v-on="gridEvents">
					<template #avg_score="{ row }">
						<template v-if="row.avg_score !== null && row.avg_score !== undefined && row.avg_score !== ''">
							<el-tooltip v-if="row.avg_score > 0" :content="row.avg_score" placement="top" :show-after="300">
								<el-rate v-if="row.avg_score > 0" v-model="row.avg_score"  :colors="['#FF0000', '#FF9900', '#67C23A']" disabled text-color="#1e293b" />
							</el-tooltip>
							<span v-else>{{ row.avg_score }}</span>
						</template>
						<template v-else>
							<span>-</span>
						</template>
					</template>
					<template #empty>
						<el-empty description="暂无数据" />
					</template>
				</vxe-grid>
			</el-card>
		</el-card>
	</div>
</template>

<script lang="ts" setup>
import { getTableData, getTableDownloadData } from '/src/views/score-statistics/api';
import { Download } from '@element-plus/icons-vue';
import { scoreStatisticsColumns } from '/src/views/score-statistics/Columns';

const gridOptions = reactive({
	border: 'inner',
	loading: false,
	height: 700,
	pagerConfig: {
		enabled: true,
		total: 20,
		currentPage: 1,
		pageSize: 20,
		pageSizes: [10, 20, 30],
	},
	rowConfig: {
		height: 38,
	},
	columns: scoreStatisticsColumns,
	data: [],
});

const asinMonthDate = ref(dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD'));

const disabledDate = (time: Date) => {
	// 禁用当前月和当前月之后的日期
	const today = new Date(); // 获取当前日期
	const currentYear = today.getFullYear();
	const currentMonth = today.getMonth() + 1; // 获取月份，注意要 +1
	// 通过比较年份和月份来禁用
	return time.getFullYear() > currentYear || (time.getFullYear() === currentYear && time.getMonth() + 2 > currentMonth);
};

const searchAsin = ref('');
const searchSku = ref('');
const averageData = ref([]);

const gridEvents = {
	pageChange({ pageSize, currentPage }) {
		gridOptions.pagerConfig.currentPage = currentPage;
		gridOptions.pagerConfig.pageSize = pageSize;
		fetchData();
	},
};

async function fetchData() {
	gridOptions.loading = true; // 显示加载状态
	try {
		const params = {
			limit: gridOptions.pagerConfig.pageSize,
			page: gridOptions.pagerConfig.currentPage,
			review_date: asinMonthDate.value,
			asin: searchAsin.value,
			sku: searchSku.value,
		};

		const resp = await getTableData(params);
		gridOptions.data = resp.data;
		gridOptions.pagerConfig.total = resp.total;
	} catch (error) {
		console.log(error);
	} finally {
		gridOptions.loading = false;
	}
}

async function handleDownload() {
	gridOptions.loading = true; // 显示加载状态
	try {
		const params = {
			review_date: asinMonthDate.value,
			asin: searchAsin.value,
			sku: searchSku.value,
		};
		const resp = await getTableDownloadData(params);
		const url = window.URL.createObjectURL(resp.data);
		const link = document.createElement('a');
		link.href = url;
		link.setAttribute('download', asinMonthDate.value + '平均评分.xlsx');
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
		window.URL.revokeObjectURL(url);
		gridOptions.loading = false;
		ElMessage.success('下载成功！');
	} catch (error) {
		console.log(error);
	} finally {
		gridOptions.loading = false;
	}
}

function cellStyle() {
	return {
		fontSize: '13px',
		fontWeight: '500',
	};
}

function headerStyle() {
	return {
		fontSize: '13px',
		backgroundColor: '#f0f1f3',
		height: 10,
		//color: '#b4b6ba',
		//fontWeight: '500',
	};
}

watch(asinMonthDate, (newVal) => {
	const date = dayjs(newVal).startOf('month').format('YYYY-MM-DD');
	if (date !== asinMonthDate.value) {
		asinMonthDate.value = date;
		fetchData();
	}
});

onMounted(() => {
	fetchData();
});
</script>

<style scoped>
.tool {
	padding-right: 25px;
}

.title {
	display: flex;
	align-items: center; /* 垂直居中对齐 */
	/* justify-content: space-between; !* 水平居中对齐 *! */
	font-size: 16px;
	font-weight: 500;
	margin-bottom: 20px;
}
</style>
