<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<!-- 标题 -->
			<el-row class="mb10 header-summary">
				<div class="title">参控股管理库</div>
			</el-row>

			<!-- 工具栏 + 搜索 -->
			<el-row class="toolbar-row mb10">
				<div class="left-actions">
					<el-button type="primary" @click="add">发起新增</el-button>
					<el-button type="primary" @click="handleBatchDelete(selectIds)">发起更新</el-button>
				</div>
				<div class="right-search">
					<el-form class="search-form" :inline="true" :model="queryForm" @keyup.enter="getDataList" ref="queryRef">
						<el-form-item label="企业名称:" prop="expertName">
							<el-input :placeholder="t('expertLibrary.placeholder.input')" style="max-width: 180px" v-model="queryForm.expertName" />
						</el-form-item>
						<el-form-item label="统一社会信用代码:" prop="technologyField">
							<el-input :placeholder="t('expertLibrary.placeholder.input')" style="max-width: 180px" v-model="queryForm.technologyField" />
						</el-form-item>
					</el-form>
				</div>
			</el-row>

			<!-- 表格 -->
			<el-table :data="tableData" border style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="48" />
				<el-table-column type="index" :label="t('expertLibrary.table.index')" width="60" />
				<el-table-column prop="expertName" label="企业名称" min-width="140" />
				<el-table-column prop="contactInformation" label="统一社会信用代码" min-width="140" />
				<el-table-column prop="technologyField" label="成立日期" min-width="140" />
				<el-table-column prop="professionalTitle" label="注册资本" min-width="120" />
				<el-table-column prop="workUnit" label="注册地址" min-width="160" />
				<el-table-column prop="level" label="单位类型" min-width="100"> </el-table-column>
				<el-table-column prop="status" label="经营规模" min-width="120"> </el-table-column>
				<el-table-column label="经营状态" width="100" fixed="right"> </el-table-column>
				<el-table-column label="操作" width="120" fixed="right">
					<template #default="scope">
						<el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
						<el-button type="text" size="small" @click="handleView(scope.row)">重新报送国资</el-button>
						<el-button type="text" size="small" @click="handleView(scope.row)">报送国资</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页 -->
			<div class="mt15 flex justify-end">
				<el-pagination
					background
					layout="sizes, prev, pager, next, jumper, total"
					:total="pagination.total"
					:page-sizes="[10, 20, 50, 100]"
					v-model:page-size="pagination.size"
					v-model:current-page="pagination.page"
					@size-change="handleSizeChange"
					@current-change="handlePageChange"
				/>
			</div>

			<ExpertDetailDialog v-model:visible="detailVisible" :detail="currentDetail" :meta="detailMeta" />
		</div>
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage, useMessageBox } from '/@/hooks/message';
import ExpertDetailDialog from '/@/components/investment/ExpertDetailDialog.vue';
import { getExpertInformationPageAPI, deleteExpertInformationsAPI } from '/@/api/investment/cooperationUnit';
import { useRouter } from 'vue-router';

const router = useRouter();

const { t } = useI18n();

// 查询与分页
const queryRef = ref();
const queryForm = reactive({
	expertName: '',
	technologyField: '',
	externalStatus: '',
});

const pagination = reactive({
	page: 1,
	size: 10,
	total: 0,
});

const loading = ref(false);
const tableData = ref<any[]>([]);

// 选择
const multiple = ref(true);
const selectIds = ref<(string | number)[]>([]);

const add = () => {
	// 跳转新增页面
	router.push({ path: '/workbench/shares/add' });
};

const extractPageData = (response: any) => {
	const records = response?.records ?? response?.data?.records ?? [];
	const total = response?.total ?? response?.data?.total ?? 0;
	const page = response?.current ?? response?.page ?? response?.data?.current ?? pagination.page;
	const size = response?.size ?? response?.data?.size ?? pagination.size;
	return { records, total, page, size };
};

const getDataList = async () => {
	loading.value = true;
	try {
		const params = {
			page: pagination.page,
			size: pagination.size,
			...queryForm,
		};
		const res = await getExpertInformationPageAPI(params);
		const { records, total, page, size } = extractPageData(res);
		tableData.value = records;
		pagination.total = total;
		pagination.page = page;
		pagination.size = size;
	} finally {
		loading.value = false;
	}
};

const resetQuery = () => {
	queryForm.expertName = '';
	queryForm.technologyField = '';
	queryForm.externalStatus = '';
	pagination.page = 1;
	getDataList();
};

const handleSelectionChange = (rows: any[]) => {
	selectIds.value = rows.map((r) => r.id);
	multiple.value = selectIds.value.length === 0;
};

const handleBatchDelete = async (ids: (string | number)[]) => {
	if (!ids?.length) return;
	await useMessageBox().confirm(t('common.delConfirmText'));
	await deleteExpertInformationsAPI(ids);
	useMessage().success(t('common.delSuccessText'));
	getDataList();
};

const exportExcel = () => {
	useMessage().info(t('common.exportOkText') || '导出任务已提交');
};

// 详情查看
const detailVisible = ref(false);
const currentDetail = ref<any>({});
const detailMeta = reactive({
	reporter: 'xxx',
	unit: 'xxx',
	date: new Date().toISOString().slice(0, 10),
});
const handleView = (row: any) => {
	// 转换为详情组件需要的格式
	const attachmentUrl = row.attachmentUrl ? JSON.parse(row.attachmentUrl) : [];
	const attachments = attachmentUrl.map((url: string) => {
		return { url, name: url.split('fileName=')[1] };
	});
	// 转换为详情组件需要的格式
	const testimonyMaterials = row.testimonyMaterials ? JSON.parse(row.testimonyMaterials) : [];
	const evidences = testimonyMaterials.map((url: string) => {
		return { url, name: url.split('fileName=')[1] };
	});
	currentDetail.value = { ...row, attachments, evidences };
	detailVisible.value = true;
};

const levelLabel = (val: string) => {
	if (val === 'national') return t('expertApply.level.national');
	if (val === 'provincial') return t('expertApply.level.provincial');
	if (val === 'city') return t('expertApply.level.city');
	return val || '-';
};
const externalStatusLabel = (val: string) => {
	return (
		{
			'0': t('expertLibrary.status.pending'),
			'1': t('expertLibrary.status.reviewing'),
			'2': t('expertLibrary.status.approved'),
			'3': t('expertLibrary.status.rejected'),
		}[val] || 1
	);
};

// 初始加载
const handleSizeChange = (val: number) => {
	pagination.size = val;
	pagination.page = 1;
	getDataList();
};

const handlePageChange = (val: number) => {
	pagination.page = val;
	getDataList();
};

getDataList();
</script>

<style scoped>
.toolbar-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.toolbar-row .left-actions {
	display: flex;
	align-items: center;
}

.toolbar-row .right-search {
	display: flex;
	align-items: center;
	align-self: center;
}

.header-summary .title {
	margin: 0 auto;
	font-size: 18px;
	font-weight: 600;
}

.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>
