<script lang="ts" setup>
/**
 * @Name: Table.vue
 * @Description: 竞品监控表格
 * @Author: Cheney
 */

import { Download, Plus, Refresh } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { usePagination } from '/@/utils/usePagination';
import { useTableData } from '/@/utils/useTableData';
import { CompetitorMonitorCommentColumns } from '/@/views/product-manage/Columns';
import DataTableSlot from './DataTableSlot.vue';
import PermissionButton from '/src/components/PermissionButton/index.vue';
import VerticalDivider from '/src/components/VerticalDivider/index.vue';
import * as api from '../api';
import CreateDialog from '/@/views/product-manage/comment-detail/component/CreateDialog.vue';
import { DictionaryStore } from '/@/stores/dictionary';
import { useScoreEnum, useTivEnum } from '/@/views/product-manage/comment-detail/enum';
import NegativeLabel from '/@/views/product-manage/comment-detail/component/NegativeLabel.vue';
import { hasPermission } from '/@/utils/hasPermission';

const { data: staticData } = DictionaryStore();

const btnLoading = ref(false);

const formInline = reactive<any>({
	country: '',
	score: '',
	tiv: '',
});

const props = defineProps({
	asin: String,
});
const { asin } = props;
const { tableOptions, handlePageChange } = usePagination(fetchList);

const gridRef = ref();
const gridOptions: any = reactive({
	// id: 'competitor-monitor-comment',
	// keepSource: true,
	size: 'mini',
	border: false,
	round: true,
	stripe: true,
	showHeader: true,
	currentRowHighLight: true,
	height: 650,
	// customConfig: {
	// 	storage: {
	// 		visible: true,
	// 		resizable:false,
	// 	}
	// },
	toolbarConfig: {
		size: 'large',
		// custom: true,
		slots: {
			buttons: 'toolbar_buttons',
			tools: 'toolbar_tools',
		},
	},
	rowConfig: {
		isHover: true,
	},
	columnConfig: {
		// resizable: true
	},
	pagerConfig: {
		total: tableOptions.value.total,
		page: tableOptions.value.page,
		limit: tableOptions.value.limit,
	},
	loading: false,
	loadingConfig: {
		icon: 'vxe-icon-indicator roll',
		text: '正在拼命加载中...',
	},
	columns: '',
	data: '',
});

const createOpen = ref(false);
const rowData = ref<any>({});

const isShowLabel = ref(false);

onMounted(() => {
	fetchList();
});

// TODO: 删除goods
async function fetchList(isQuery = false) {
	if (isQuery) {
		gridOptions.pagerConfig.page = 1;
	}

	gridOptions.data = [];
	gridOptions.columns = [];

	const query = {
		asin: asin,
		country_code: formInline?.country,
		score: formInline?.score,
		tiv: formInline?.tiv,
	};
	await useTableData(api.getTableData, query, gridOptions);
  if (gridOptions && gridOptions.data?.length) await gridRef.value.loadColumn(CompetitorMonitorCommentColumns);
	gridOptions.showHeader = Boolean(gridOptions.data?.length);
}

function handleRefresh() {
	fetchList();
}

async function handleDownload() {
	gridOptions.loading = true;
	try {
		const query = {
			asin: asin,
			country_code: formInline?.country,
			score: formInline?.score,
			tiv: formInline?.tiv,
		};
		const response = await api.exportData(query);
		const url = window.URL.createObjectURL(new Blob([response.data]));
		const link = document.createElement('a');
		link.href = url;
		link.setAttribute('download', '评论详情数据.xlsx');
		document.body.appendChild(link);
		link.click();
		ElMessage.success('数据导出成功！');
	} catch (error) {
		ElMessage.error('数据导出失败，请重试！');
		console.error(error);
	} finally {
		gridOptions.loading = false;
	}
}

function handleCreate() {
	createOpen.value = true;
}

function showLabel(row: any) {
	isShowLabel.value = true;
	rowData.value = row;
}

// async function handleQuery() {
//   btnLoading.value = true;
//   await fetchList();
//   btnLoading.value = false;
// }

// function resetParameter() {
//   for (const key in formInline) {
//     formInline[key] = '';
//   }
// }

defineExpose({ fetchList });
</script>

<template>
	<!--查询条件-->
	<div ref="queryContainer" class="flex justify-between">
		<div class="flex flex-1">
			<div class="w-full whitespace-nowrap">
				<el-row :gutter="20" style="margin-bottom: 5px">
					<el-col :span="6">
						<div class="flex items-center">
							<span class="mr-2">国 家</span>
							<el-select v-model="formInline.country" clearable placeholder="请选择国家" @change="fetchList(true)">
								<el-option v-for="item in staticData.country_code" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="flex items-center">
							<span class="mr-2">用户评分</span>
							<el-select v-model="formInline.score" clearable placeholder="请选择用户评分" @change="fetchList(true)">
								<el-option v-for="item in useScoreEnum" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="flex items-center">
							<span class="mr-2">评论类型</span>
							<el-select v-model="formInline.tiv" clearable placeholder="请选择评论类型" @change="fetchList(true)">
								<el-option v-for="item in useTivEnum" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</div>
					</el-col>
				</el-row>
			</div>
		</div>
		<!--<div class="flex gap-1.5 ml-5">-->
		<!--  <el-button :icon="Search" :loading="btnLoading" type="primary" @click="handleQuery">-->
		<!--    查 询-->
		<!--  </el-button>-->
		<!--  <el-button :icon="RefreshRight" color="#ECECF1C9" style="width: 88px; color: #3c3c3c;" @click="resetParameter">-->
		<!--    重 置-->
		<!--  </el-button>-->
		<!--</div>-->
	</div>
	<el-divider ref="dividerContainer" style="margin: 20px 0 12px 0" />
	<vxe-grid ref="gridRef" class="z-0" v-bind="gridOptions">
		<template #toolbar_buttons>
			<div class="flex gap-2">
				<PermissionButton v-if="hasPermission('ReviewCreate')" :icon="Plus" plain round type="primary" @click="handleCreate"> 新 增 </PermissionButton>
				<VerticalDivider class="px-1" style="margin-left: 7px" />
			</div>
		</template>
		<template #toolbar_tools>
			<el-button circle class="toolbar-btn" @click="handleRefresh">
				<el-icon>
					<Refresh />
				</el-icon>
			</el-button>
			<el-button circle class="toolbar-btn" @click="handleDownload">
				<el-icon>
					<Download />
				</el-icon>
			</el-button>
		</template>
		<template #top>
			<div class="mb-2"></div>
		</template>
		<template #pager>
			<vxe-pager
				v-model:currentPage="gridOptions.pagerConfig.page"
				v-model:pageSize="gridOptions.pagerConfig.limit"
				:total="gridOptions.pagerConfig.total"
				class="mt-1.5"
				@page-change="handlePageChange"
			/>
		</template>
		<template #empty>
			<el-empty description="暂无数据" />
		</template>
		<!-- 自定义列插槽 -->
		<template v-for="col in CompetitorMonitorCommentColumns" #[`${col.field}`]="{ row }">
			<DataTableSlot :key="row.id" :field="col.field" :row="row" @open-negativeLabel="showLabel" />
		</template>
	</vxe-grid>
	<CreateDialog v-if="createOpen" v-model="createOpen" @refresh="fetchList" />
	<NegativeLabel v-if="isShowLabel" v-model="isShowLabel" :rowData="rowData" />
</template>

<style scoped>
.toolbar-btn {
	width: 34px;
	height: 34px;
	font-size: 18px;
}

:deep(.custom-el-input .el-select__wrapper) {
	border-radius: 20px;
}
</style>
