<template>
	<el-tabs type="card" v-model="activeTab" style="height: 100%" @tab-click="handleClick">
		<el-tab-pane v-for="tab in tabs" :key="tab.key" :label="tab.label" :name="tab.key">
			<div class="sensitive-words flex">
				<TreeSelect class="mr20" ref="treeSelectdRef" @treeCheck="getTreeCheck"></TreeSelect>
				<div class="table-box">
					<pageSearch
						ref="searchTableRef"
						:searchConfig="activeTab === '1' ? searchConfig : searchNonIndustryConfig"
					/>
					<pageContent
						ref="tableListRef"
						:total="total"
						v-loading="loading"
						:contentConfig="activeTab === '1' ? contentConfig : contentNonIndustryConfig"
						:pageList="tableData"
					>
						<!-- 短信接收人 -->
						<template #msgRecipient="scope">
							<template :index="index" v-for="(item, index) in bj_msg_recipient">
								<el-tag
									:index="index"
									v-if="item.value == scope.row.msgRecipient"
									:type="scope.row.msgRecipient == '1' ? 'success' : 'danger'"
									>{{ item.label }}</el-tag
								>
							</template>
						</template>
						<!-- 通讯录状态 -->
						<template #abStatus="scope">
							<template :index="index" v-for="(item, index) in bj_ab_status">
								<el-tag
									:index="index"
									v-if="item.value == scope.row.abStatus"
									:type="scope.row.abStatus == '1' ? 'success' : 'danger'"
									>{{ item.label }}</el-tag
								>
							</template>
						</template>
						<template #button>
							<el-button type="primary" @click="handleImportShow()">导入</el-button>
							<el-button type="primary" @click="onImportTemplate()">下载模版</el-button>
							<el-button type="primary" @click="onAdd()">新增</el-button>
							<el-button type="primary" @click="onExport()">导出</el-button>
						</template>
						<template #operate="scope">
							<el-button type="primary" link @click="handleCheck(scope.row.liaisonId)"> 查看 </el-button>
							<template v-if="scope.row.abStatus == '1'">
								<el-button type="primary" link @click="handleEdit(scope.row.liaisonId)"> 编辑 </el-button>
								<el-button type="danger" link @click="onDelete(scope.row)"> 删除 </el-button>
							</template>
							<template v-esle>
								<el-button type="primary" link @click="handleStatus(scope.row, '启用', '1')">
									启用
								</el-button>
							</template>
						</template>
					</pageContent>
				</div>
			</div>
		</el-tab-pane>
	</el-tabs>
	<pageDetail :modalConfig="activeTab === '1' ? detailConfig : detailNonIndustryConfig" ref="modalRef">
	</pageDetail>
	<pageImport
		v-model:isVisible="importDialog.isvisible"
		:title="importDialog.title"
		@refresh-table="handleQuery()"
	/>
</template>

<script setup lang="ts">
import contentConfig from './config/content.config';
import contentNonIndustryConfig from './config/content.nonIndustry.config';
import pageContent from '@/components/components/pageContent.vue';
import searchConfig from './config/search.config';
import searchNonIndustryConfig from './config/search.nonIndustry.config';
import pageSearch from '@/components/components/pageSearch.vue';
import detailConfig from './config/detail.config';
import detailNonIndustryConfig from './config/detail.nonIndustry.config';
import pageDetail from './components/detail.vue';
import pageImport from './components/import.vue';
import useSystemStore from '@/store/main';
import TreeSelect from './components/treeSelect.vue';
import { type TabsPaneContext } from 'element-plus';
import { outTypeList } from '@/libs/commonMeth';
import { changeInventoryStatus } from '@/api/notificationInfoManage/contactsmanage';

const bj_msg_recipient = outTypeList('bj_msg_recipient'); //短信接收人
const bj_ab_status: any = outTypeList('bj_ab_status'); //通讯录状态
// 使用pinia数据
const systemStore = useSystemStore();
const { pageDetailInfo, searchObj } = storeToRefs(systemStore);

const total = ref(0);
const pageSize = ref([10, 20, 30]);
const tableData = ref([]);
const tableListRef: any = ref<InstanceType<typeof pageContent>>();

const tabs = reactive([
	{
		key: '1',
		label: '行业内联络员',
		total: 0,
		tableData: [],
		loading: false,
		showDetail: true,
	},
	{
		key: '2',
		label: '行业外联络员',
		total: 0,
		tableData: [],
		loading: false,
		showDetail: true,
	},
]);

const activeTab = ref('1');
const searchTableRef: any = ref<InstanceType<typeof pageSearch>>();
// 操作弹框
import usePageModal from '@/components/components/hooks/usePageDetails';
const { modalRef, handleNewDataClick, handleEditDataClick, handleCheckDataClick, handlePageDetail } =
	usePageModal();

const getTreeCheck = async data => {
	if (activeTab.value == '1') {
		searchConfig.pageListParams.belongsDeptIds = data.join();
	} else {
		searchNonIndustryConfig.pageListParams.belongsDeptIds = data.join();
	}
	searchTableRef.value[0].handleQueryClick();
};

const handleQuery = async () => {
	loading.value = true;
	setTimeout(() => {
		if (treeSelectdRef.value) {
			treeSelectdRef.value[0].handleReset(false);
		}
		if (searchTableRef.value) {
			searchTableRef.value[0].handleResetClick();
		}
		loading.value = false;
	}, 500);
};

const treeSelectdRef = ref<InstanceType<typeof TreeSelect>>();
const loading = ref(false);
const handleClick = async (tab: TabsPaneContext) => {
	loading.value = true;
	setTimeout(() => {
		if (treeSelectdRef.value) {
			treeSelectdRef.value[0].handleReset(false);
		}
		if (searchTableRef.value) {
			searchTableRef.value[0].handleResetClick();
		}
		loading.value = false;
	}, 500);
};

const importDialog = reactive({
	isvisible: false,
	title: '通报联络员数据导入',
});

function handleImportShow() {
	importDialog.isvisible = true;
}

const handleEdit = async (id: string) => {
	await handlePageDetail(id);
	await handleEditDataClick();
};

const handleCheck = async (id: string) => {
	await handlePageDetail(id);
	await handleCheckDataClick();
};

// 新增按钮
const onAdd = () => {
	handleNewDataClick();
};
const onImportTemplate = () => {
	const link = document.createElement('a');
	link.href = `/assets/address-book.xlsx`;
	link.download = '违法信息通报通讯录人员导入模板.xlsx'; // 指定下载后的文件名
	link.style.display = 'none';
	document.body.appendChild(link);
	link.click();
	document.body.removeChild(link);
};
const onExport = () => {
	ElMessage.success('小编在努力开发中。。。');
	return;
};

// 删除按钮
function onDelete(row: any) {
	ElMessageBox.confirm(`确定删除联络人“${row.contactName}”条目信息吗？`, '删除提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			systemStore.deletePageDataAction(contentConfig.pageName, row.liaisonId, {
				industryType: activeTab.value,
			});
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			});
		});
}

// 状态按钮
function handleStatus(row: any, status: string, str: string) {
	ElMessageBox.confirm(`是否${str}联络人“${row.contactName}”条目信息吗？`, '状态提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			const postData: any = await changeInventoryStatus(row.liaisonId, status);
			if (postData.code === 200) {
				tableListRef.value.fetchPageListData({ industryType: activeTab.value });
				ElMessage.success('操作成功！');
			} else {
				ElMessage.error('操作失败！');
			}
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '取消操作',
			});
		});
}

const handleDownload = async () => {
	ElMessageBox.confirm(`确定要导出所选数据信息？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		distinguishCancelAndClose: true,
	})
		.then(async () => {
			const isLoading = ElLoading.service({
				lock: true,
				text: 'Loading',
				background: 'rgba(0, 0, 0, 0.7)',
			});
			let data: any = {};
			// 获取表格数据
			// data = cfgSelection.value;
			try {
				// 创建 Blob 对象
				const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
				// 获取列名
				const headers = [
					{ key: 'uuid', label: '目标设备码' },
					{ key: 'client_ip', label: '目标设备IP' },
					{ key: 'type', label: '适用平台' },
					{ key: 'remark', label: '目标设备名称' },
				];
				const headerRow = headers.map(header => header.label).join(',');
				// 构造 CSV 内容
				const csvContent = [
					headerRow,
					...data.map((row: any) => headers.map(header => row[header.key]).join(',')),
				].join('\n');

				// 构造文件名
				const filename = `${timestamp}.csv`; // 指定下载文件的名称;
				// 创建 Blob 对象
				const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8' });
				// 创建下载链接
				const url = URL.createObjectURL(blob);
				const a = document.createElement('a');
				a.href = url;
				a.download = filename;
				a.click();
				URL.revokeObjectURL(url); // 释放 URL 对象
			} finally {
				isLoading.close();
			}
		})
		.catch(() => {});
};

// 筛选-状态赋值 bj_notification_status
async function searchItem() {
	searchConfig.formItems.forEach(item => {
		if (item.prop === 'msgRecipient') {
			item.options = bj_msg_recipient;
		}
		if (item.prop === 'abStatus') {
			item.options = bj_ab_status;
		}
	});
	searchNonIndustryConfig.formItems.forEach(item => {
		if (item.prop === 'abStatus') {
			item.options = bj_ab_status;
		}
	});
}
searchItem();
</script>

<style scoped lang="scss">
.sensitive-words {
	margin: 20px;
	height: calc(100vh - 20vh);
	margin-top: 0;
}

.status {
	cursor: pointer;
	position: relative;

	.status-tip {
		position: absolute;
		top: 2px;
		left: 60px;
	}
}

.dialog-tip {
	text-align: center;
}

.table-box {
	width: 75%;
	display: flex;
	flex-direction: column;
}

:deep .el-tabs__item.is-active {
	color: #fff;
	background-color: #409eff;
}
:deep .el-tabs__header {
	padding-left: 20px;
	background-color: #fff;
}
</style>
