<template>
	<div class=" p-14">
		<!-- 新增用户质量 -->
		<div class="">
			<div class="flex items-center justify-between mb-2">
				
			</div>

			<div class="relative">
				<div ref="qualityChartRef" style="width: 100%; height: 320px"></div>
			</div>
		</div>

		<!-- 明细表格 -->
		<div class="mt-3">
			<div class="flex items-center justify-between mb-2">
				<div class="text-base font-medium cursor-pointer select-none ml-3 items-center flex text-[#167AF0]"
					@click="showDetail = !showDetail">
					{{ showDetail ? '收起明细数据' : '展开明细数据' }}
					<el-icon class="ml-2">
						<ArrowDown v-if="showDetail" />
						<ArrowUp v-else />
					</el-icon>
				</div>
				<div>
					<el-button type="primary" text>导出</el-button>

				</div>
			</div>
			<el-table v-if="showDetail" :data="tableData" border :cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle">
				<el-table-column prop="date" label="日期" />
				<el-table-column label="新增用户（占比）" >
					<template #default="scope">
						{{ (scope.row.retention * 100).toFixed(2) }}%
					</template>
				</el-table-column>
			</el-table>
			<div v-if="showDetail" class="flex justify-end mt-3">
				<el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
					@change="getBottomDetail" background layout="total, prev, pager, next, sizes"
					:total="pagination.total" :page-sizes="[5, 10, 20]" />
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, defineAsyncComponent } from 'vue';
import * as echarts from 'echarts';
import { getRetentionDetail, getRetention } from '/@/api/count/addUser';

const tableStyle = {
	cellStyle: { textAlign: 'center' },
	headerCellStyle: {
		textAlign: 'center',
		background: 'var(--el-table-row-hover-bg-color)',
		color: 'var(--el-text-color-primary)',
	},
	rowStyle: { textAlign: 'center' },
};
interface TableRow {
	date: string;
	retention: string;
}

const emit = defineEmits(['query']);
const props = defineProps({
	formData: {
		type: Object,
		default: () => ({}),
	},
});
const colorSchemes = [
	{ color: '#409EFF' }, // 蓝色
	{ color: '#67C23A' }, // 绿色
	{ color: '#E6A23C' }, // 黄色
	{ color: '#F56C6C' }, // 红色
];
const pagination = ref({
	current: 1, //当前页数
	total: 0, // 数据总数
	size: 5, // 每页显示条数
});
// 用户质量（留存率）
const qualityChartRef = ref<HTMLDivElement | null>(null);
let qualityChart: echarts.ECharts | null = null;
const tableData = ref<TableRow[]>([]);

interface FormDataType {
	timeUnit: string;
	version: string[];
	channel: string[];
	fromDate: string;
	toDate: string;
}

const formData = ref<FormDataType>({
	timeUnit: 'day',
	version: [],
	channel: [],
	fromDate: props.formData?.time[0],
	toDate: props.formData?.time[1],
});
const lineCartData = ref<{ dates: any; retentions: any }>({
	dates: [],
	retentions: [],
});

const getData = async () => {
	const res = await getRetention({ ...formData.value });
	const data = res?.data || [];
	lineCartData.value = data;
	lineCartData.value.retentions = lineCartData.value.retentions.map((item: any) => (item * 100).toFixed(2));
	initQualityChart();
	getBottomDetail()
};

const getBottomDetail = async () => {
	// 下方明细表
	const res = await getRetentionDetail({ ...formData.value, ...pagination.value });
	const data = res?.data || [];
	tableData.value = data.records;
	pagination.value.current = data.current; //当前页码
	pagination.value.total = data.total; //总条数
	pagination.value.size = data.size; //每页条数
};

// 展开/收起明细
const showDetail = ref(true);

function initQualityChart(): void {
	const randomColorIndex = Math.floor(Math.random() * colorSchemes.length);
	if (!qualityChartRef.value) return;
	if (qualityChart) qualityChart.dispose();
	qualityChart = echarts.init(qualityChartRef.value);
	const option: echarts.EChartsOption = {
		tooltip: { trigger: 'axis', valueFormatter: (v) => `${v}%` },
		grid: { left: 40, right: 20, top: 30, bottom: 30 },
		xAxis: { type: 'category', data: lineCartData.value.dates },
		yAxis: {
			type: 'value',
			min: 0,
			max: 30,
			axisLabel: { formatter: '{value}%' },
			splitLine: { lineStyle: { color: '#f3f4f6' } },
		},
		series: [
			{
				name: '留存率',
				type: 'line',
				smooth: true,
				data: lineCartData.value.retentions,
				itemStyle: {
					color: colorSchemes[randomColorIndex].color,
				},
				lineStyle: {
					color: colorSchemes[randomColorIndex].color,
				},
			},
		],
	};
	qualityChart.setOption(option);
}

onMounted(() => {
	getData();

});
watch(props.formData, () => {
	formData.value = {
		...formData.value,
		channel: props.formData?.channel ? [props.formData?.channel] : [],
		version: props.formData?.version ? [props.formData?.version] : [],
		fromDate: props.formData?.time[0],
		toDate: props.formData?.time[1],
	};
	getData();
});
</script>

<style lang="scss" scoped>
.highlight {
	color: #2196f3;
}
</style>
