<template>
	<div class="modern-page-container">
		<div class="page-wrapper">
			<!-- 搜索表单卡片 -->
			<el-card v-show="showSearch" class="search-card" shadow="never">
				<template #header>
					<div class="card-header">
						<span class="card-title">
							<el-icon class="title-icon"><Search /></el-icon>
							筛选条件
						</span>
					</div>
				</template>
				<el-form :model="state.queryForm" ref="searchFormRef" :inline="true" @keyup.enter="getDataList" class="search-form">
					<el-form-item label="采购编号" prop="purchaseNo">
						<el-input v-model="state.queryForm.purchaseNo" placeholder="请输入采购编号" clearable style="width: 200px" />
					</el-form-item>
					<el-form-item label="项目名称" prop="projectName">
						<el-input v-model="state.queryForm.projectName" placeholder="请输入项目名称" clearable style="width: 200px" />
					</el-form-item>
					<!-- 审核状态筛选 - 仅审核模式显示 -->
					<el-form-item v-if="mode === 'audit'" label="审核状态" prop="docAuditStatus">
						<el-select v-model="state.queryForm.docAuditStatus" placeholder="请选择审核状态" clearable style="width: 200px">
							<el-option label="待上传" value="PENDING_UPLOAD" />
							<el-option label="草稿" value="DRAFT" />
							<el-option label="资产管理处审核中" value="ASSET_REVIEWING" />
							<el-option label="需求部门审核中" value="DEPT_REVIEWING" />
							<el-option label="内审部门审核中" value="AUDIT_REVIEWING" />
							<el-option label="资产管理处确认中" value="ASSET_CONFIRMING" />
							<el-option label="已完成" value="COMPLETED" />
							<el-option label="已退回" value="RETURNED" />
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" icon="Search" @click="getDataList">查询</el-button>
						<el-button icon="Refresh" @click="handleReset">重置</el-button>
					</el-form-item>
				</el-form>
			</el-card>

			<!-- 内容卡片 -->
			<el-card class="content-card" shadow="never">
				<template #header>
					<div class="card-header">
						<span class="card-title">
							<el-icon class="title-icon">
								<component :is="titleIcon" />
							</el-icon>
							{{ pageTitle }}
						</span>
						<div class="header-actions">
							<right-toolbar v-model:showSearch="showSearch" class="ml10" @queryTable="getDataList" />
						</div>
					</div>
				</template>

				<!-- 表格 -->
				<el-table
					ref="tableRef"
					:data="state.dataList"
					v-loading="state.loading"
					stripe
					:cell-style="tableStyle.cellStyle"
					:header-cell-style="tableStyle.headerCellStyle"
					class="modern-table"
				>
					<el-table-column type="index" label="序号" width="70" align="center">
						<template #header>
							<el-icon><List /></el-icon>
						</template>
					</el-table-column>
					<el-table-column prop="purchaseNo" label="采购编号" min-width="140" show-overflow-tooltip />
					<el-table-column prop="projectName" label="项目名称" min-width="200" show-overflow-tooltip />
					<!-- 需求部门 - 仅审核模式显示 -->
					<el-table-column v-if="mode === 'audit'" prop="deptName" label="需求部门" min-width="150" show-overflow-tooltip />
					<!-- 预算金额 - 仅审核模式显示 -->
					<el-table-column v-if="mode === 'audit'" prop="budget" label="预算金额(元)" width="120" align="right">
						<template #default="scope">
							{{ scope.row.budget ? Number(scope.row.budget).toLocaleString() : '-' }}
						</template>
					</el-table-column>
					<!-- 文件状态 -->
					<el-table-column :prop="statusProp" label="文件状态" width="140" align="center">
						<template #default="scope">
							<el-tag :type="getStatusType(getRowStatus(scope.row))">
								{{ getStatusLabel(getRowStatus(scope.row)) }}
							</el-tag>
						</template>
					</el-table-column>
					<!-- 当前版本 - 仅审核模式显示 -->
					<el-table-column v-if="mode === 'audit'" prop="currentDocVersion" label="当前版本" width="100" align="center">
						<template #default="scope">
							{{ scope.row.currentDocVersion || '-' }}
						</template>
					</el-table-column>
					<!-- 操作 -->
					<el-table-column label="操作" align="center" fixed="right" width="120">
						<template #default="scope">
							<el-button type="primary" link icon="View" @click="handleProcess(scope.row)">
								{{ actionLabel }}
							</el-button>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页 -->
				<pagination
					v-if="state.pagination && state.pagination.total && state.pagination.total > 0"
					:total="state.pagination.total"
					:current="state.pagination.current"
					:size="state.pagination.size"
					@sizeChange="sizeChangeHandle"
					@currentChange="currentChangeHandle"
				/>
			</el-card>
		</div>

		<!-- 处理弹窗 -->
		<!--    {{mode}}-->
		<DocProcessDialog ref="docProcessDialogRef" :mode="mode" @refresh="getDataList" />
	</div>
</template>

<script setup lang="ts" name="PurchasingDocProcess">
import { ref, reactive, computed, defineAsyncComponent, onMounted } from 'vue';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { getDocProcessList } from '/@/api/purchase/docProcess';
import { Search, DocumentCopy, DocumentChecked, List } from '@element-plus/icons-vue';
import { useUserInfo } from '/@/stores/userInfo';

// 引入组件
const DocProcessDialog = defineAsyncComponent(() => import('./DocProcessDialog.vue'));

const userInfoStore = useUserInfo();
const docProcessDialogRef = ref();
const searchFormRef = ref();
const showSearch = ref(true);

// 从用户角色自动判断模式
const mode = computed(() => {
	const roleCodes = userInfoStore.userInfos.roleCodes || [];
	// 有 PURCHASE_AGENT 角色则显示代理模式
	if (roleCodes.includes('PURCHASE_AGENT')) {
		return 'agent';
	}
	// 其他情况显示审核模式
	return 'audit';
});

// 页面标题
const pageTitle = computed(() => {
	return mode.value === 'agent' ? '招标代理工作台' : '招标文件审核';
});

// 标题图标
const titleIcon = computed(() => {
	return mode.value === 'agent' ? DocumentCopy : DocumentChecked;
});

// 操作按钮标签
const actionLabel = computed(() => {
	return mode.value === 'agent' ? '处理' : '审核';
});

// 状态字段
const statusProp = computed(() => {
	return mode.value === 'agent' ? 'status' : 'docAuditStatus';
});

// 查询表单
const getQueryForm = () => {
	const base: any = {
		purchaseNo: '',
		projectName: '',
	};
	if (mode.value === 'audit') {
		base.docAuditStatus = '';
	}
	return base;
};

const state: BasicTableProps = reactive<BasicTableProps>({
	pageList: (params?: any) => getDocProcessList(mode.value, params),
	queryForm: getQueryForm(),
	createdIsNeed: true,
});

const { getDataList, tableStyle, sizeChangeHandle, currentChangeHandle } = useTable(state);

const handleReset = () => {
	searchFormRef.value?.resetFields();
	getDataList();
};

// 获取行状态（兼容两种字段名）
const getRowStatus = (row: any) => {
	return mode.value === 'agent' ? row.status : row.docAuditStatus;
};

const getStatusType = (status: string) => {
	const typeMap: Record<string, string> = {
		PENDING_UPLOAD: 'info',
		DRAFT: 'info',
		ASSET_REVIEWING: 'warning',
		DEPT_REVIEWING: 'warning',
		AUDIT_REVIEWING: 'warning',
		ASSET_CONFIRMING: 'primary',
		COMPLETED: 'success',
		RETURNED: 'danger',
	};
	return typeMap[status] || 'info';
};

const getStatusLabel = (status: string) => {
	const labelMap: Record<string, string> = {
		PENDING_UPLOAD: '待上传',
		DRAFT: '草稿',
		ASSET_REVIEWING: '资产管理处审核中',
		DEPT_REVIEWING: '需求部门审核中',
		AUDIT_REVIEWING: '内审部门审核中',
		ASSET_CONFIRMING: '资产管理处确认中',
		COMPLETED: '已完成',
		RETURNED: '已退回',
	};
	return labelMap[status] || '-';
};

const handleProcess = (row: any) => {
	docProcessDialogRef.value?.open(row);
};

// 监听路由参数变化，重新加载数据
onMounted(() => {
	// 重置查询表单
	state.queryForm = getQueryForm();
});
</script>

<style scoped lang="scss">
@import '/@/assets/styles/modern-page.scss';
</style>
