<template>
	<div class="inventory-count-page">
		<div class="inventory-count-container">
			<el-card shadow="hover">
				<div class="inventory-count-search mb15">
					<el-form :inline="true" :model="tableData.param">
						<el-form-item label="关键词">
							<el-input size="default" v-model="tableData.param.keyword" placeholder="请输入关键词" clearable style="width: 200px" />
						</el-form-item>
						<el-form-item label="盘点类型">
							<el-select size="default" v-model="tableData.param.countType" placeholder="请选择盘点类型" clearable style="width: 150px">
								<el-option label="明盘" :value="1" />
								<el-option label="盲盘" :value="2" />
							</el-select>
						</el-form-item>
						<el-form-item label="状态">
							<el-select size="default" v-model="tableData.param.status" placeholder="请选择状态" clearable style="width: 120px">
								<el-option label="草稿" :value="1" />
								<el-option label="已计划" :value="2" />
								<el-option label="进行中" :value="3" />
								<el-option label="已提交" :value="4" />
								<el-option label="已完成" :value="5" />
								<el-option label="已取消" :value="6" />
							</el-select>
						</el-form-item>
						<el-form-item>
							<el-button size="default" type="primary" @click="getList">
								<el-icon><ele-Search /></el-icon>
								查询
							</el-button>
							<el-button size="default" @click="onResetQuery">
								<el-icon><ele-Refresh /></el-icon>
								重置
							</el-button>
							<el-button size="default" type="success" @click="onOpenAdd">
								<el-icon><ele-Plus /></el-icon>
								新增
							</el-button>
						</el-form-item>
					</el-form>
				</div>
				<el-table :data="tableData.data" style="width: 100%" v-loading="tableData.loading" border>
					<el-table-column type="index" label="序号" width="60" align="center" />
					<el-table-column prop="countNo" label="盘点编号" width="120" show-overflow-tooltip />
					<el-table-column prop="title" label="任务名称" min-width="40" show-overflow-tooltip />
					<el-table-column prop="countTypeText" label="盘点类型" width="100" align="center">
						<template #default="scope">
							<el-tag :type="getCountTypeTag(scope.row.countType)">{{ scope.row.countTypeText || getCountTypeLabel(scope.row.countType) }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="scopeText" label="盘点范围" width="100" align="center">
						<template #default="scope">
							{{ scope.row.scopeText || getScopeLabel(scope.row.scope) }}
						</template>
					</el-table-column>
					<el-table-column label="仓库/库区/库位" width="150" show-overflow-tooltip>
						<template #default="scope">
							{{ getScopeDisplayNames(scope.row) }}
						</template>
					</el-table-column>
					<el-table-column prop="statusText" label="状态" width="100" align="center">
						<template #default="scope">
							<el-tag :type="getStatusTag(scope.row.status)">{{ scope.row.statusText || getStatusLabel(scope.row.status) }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="progress" label="进度" width="80" align="center">
						<template #default="scope">
							{{ scope.row.progress || 0 }}%
						</template>
					</el-table-column>
					<el-table-column prop="assigneeName" label="负责人" width="100" align="center" />
					<el-table-column prop="createdAt" label="创建时间" width="170" show-overflow-tooltip />
					<el-table-column label="操作" width="150" fixed="right" align="center">
						<template #default="scope">
							<el-button link type="primary" @click="onOpenImport(scope.row)">导入</el-button>
							<el-button link type="danger" @click="onDelete(scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页 -->
				<div class="mt15" style="text-align: right">
					<el-pagination
						v-model:current-page="tableData.param.pageNum"
						v-model:page-size="tableData.param.pageSize"
						:page-sizes="[10, 20, 50, 100]"
						:total="tableData.total"
						layout="total, sizes, prev, pager, next, jumper"
						@size-change="onSizeChange"
						@current-change="onCurrentChange"
					/>
				</div>
			</el-card>
		</div>
		<EditInventoryCount ref="editRef" @refresh="getList" />
		<ImportDialog ref="importRef" @refresh="getList" />
	</div>
</template>

<script lang="ts">
export default {
	name: 'assetsOperationCount',
};
</script>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listInventoryCounts, deleteInventoryCount, completeInventoryCount, cancelInventoryCount } from '/@/api/assets/operation/count';
import EditInventoryCount from './component/editInventoryCount.vue';
import ImportDialog from './component/importDialog.vue';

const editRef = ref();
const importRef = ref();

const tableData = reactive({
	data: [] as any[],
	total: 0,
	loading: false,
	param: {
		keyword: '',
		countType: undefined as number | undefined,
		status: undefined as number | undefined,
		pageNum: 1,
		pageSize: 10,
	},
});

// 获取盘点类型标签
const getCountTypeTag = (type: number) => {
	const tagMap: Record<number, string> = {
		0: 'primary',
		1: 'success',
		2: 'warning',
	};
	return tagMap[type] || 'info';
};

// 获取盘点类型文本
const getCountTypeLabel = (type: number) => {
	const labelMap: Record<number, string> = {
		1: '明盘',
		2: '盲盘',
	};
	return labelMap[type] || '未知';
};

// 获取盘点范围文本
const getScopeLabel = (scope: number) => {
	const labelMap: Record<number, string> = {
		1: '按仓库盘点',
		2: '按库区盘点',
		3: '按库位盘点',
		4: '按SKU盘点',
		5: '按资产盘点',
	};
	return labelMap[scope] || '未知';
};

// 根据盘点范围获取显示名称
const getScopeDisplayNames = (row: any) => {
	const scope = row.scope;
	if (scope === 1) {
		// 按仓库盘点，显示仓库名称
		return (row.warehouseNames || []).join('、') || '-';
	} else if (scope === 2) {
		// 按库区盘点，显示库区名称
		return (row.zoneNames || []).join('、') || '-';
	} else if (scope === 3) {
		// 按库位盘点，显示库位名称
		return (row.locationNames || []).join('、') || '-';
	}
	return '-';
};

// 获取状态标签
const getStatusTag = (status: number) => {
	const tagMap: Record<number, string> = {
		1: 'info',      // 草稿
		2: 'primary',   // 已计划
		3: 'warning',   // 进行中
		4: '',          // 已提交
		5: 'success',   // 已完成
		6: 'danger',    // 已取消
	};
	return tagMap[status] || 'info';
};

// 获取状态文本
const getStatusLabel = (status: number) => {
	const labelMap: Record<number, string> = {
		1: '草稿',
		2: '已计划',
		3: '进行中',
		4: '已提交',
		5: '已完成',
		6: '已取消',
	};
	return labelMap[status] || '未知';
};

// 获取列表
const getList = async () => {
	tableData.loading = true;
	try {
		const res: any = await listInventoryCounts(tableData.param);
		tableData.data = res.data?.list || [];
		tableData.total = res.data?.total || 0;
	} catch (error) {
		console.error('获取盘点任务列表失败:', error);
	} finally {
		tableData.loading = false;
	}
};

// 重置查询
const onResetQuery = () => {
	tableData.param.keyword = '';
	tableData.param.countType = undefined;
	tableData.param.status = undefined;
	tableData.param.pageNum = 1;
	getList();
};

// 新增
const onOpenAdd = () => {
	editRef.value?.openDialog();
};

// 编辑
const onEdit = (row: any) => {
	editRef.value?.openDialog(row);
};

// 完成盘点
const onComplete = (row: any) => {
	ElMessageBox.confirm(`确定要完成盘点任务【${row.title}】吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		try {
			const res: any = await completeInventoryCount(row.id);
			if (res.code === 0) {
				ElMessage.success('操作成功');
				getList();
			} else {
				ElMessage.error(res.message || '操作失败');
			}
		} catch (error) {
			console.error('完成盘点失败:', error);
		}
	}).catch(() => {});
};

// 取消盘点
const onCancel = (row: any) => {
	ElMessageBox.prompt(`请输入取消原因`, '取消盘点任务', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		inputPlaceholder: '请输入取消原因',
	}).then(async ({ value }) => {
		try {
			const res: any = await cancelInventoryCount([row.id], value);
			if (res.code === 0) {
				ElMessage.success('操作成功');
				getList();
			} else {
				ElMessage.error(res.message || '操作失败');
			}
		} catch (error) {
			console.error('取消盘点失败:', error);
		}
	}).catch(() => {});
};

// 删除
const onDelete = (row: any) => {
	ElMessageBox.confirm(`确定要删除盘点任务【${row.title}】吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		try {
			const res: any = await deleteInventoryCount(row.id);
			if (res.code === 0) {
				ElMessage.success('删除成功');
				getList();
			} else {
				ElMessage.error(res.message || '删除失败');
			}
		} catch (error) {
			console.error('删除盘点任务失败:', error);
		}
	}).catch(() => {});
};

// 打开导入弹窗
const onOpenImport = (row: any) => {
	importRef.value?.openDialog(row.id);
};

// 分页大小变化
const onSizeChange = (size: number) => {
	tableData.param.pageSize = size;
	tableData.param.pageNum = 1;
	getList();
};

// 页码变化
const onCurrentChange = (page: number) => {
	tableData.param.pageNum = page;
	getList();
};

onMounted(() => {
	getList();
});
</script>

<style scoped lang="scss">
.inventory-count-page {
	padding: 15px;
}
</style>