<template>
	<div class="assets-warehouse-page">
		<div class="assets-warehouse-container">
			<el-card shadow="hover">
				<div class="assets-warehouse-search mb15">
					<el-form :inline="true" :model="tableData.param.keyword">
						<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.status" placeholder="请选择状态" clearable style="width: 120px">
								<el-option label="启用" value="enable" />
								<el-option label="禁用" value="disable" />
							</el-select>
						</el-form-item>
						<el-form-item>
							<el-button size="default" type="primary" @click="getWarehouseList">
								<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="warehouseName" label="仓库名称" min-width="150" show-overflow-tooltip />
					<el-table-column prop="warehouseCode" label="仓库编码" width="120" show-overflow-tooltip />
					<el-table-column prop="address" label="仓库地址" min-width="200" show-overflow-tooltip />
					<el-table-column prop="contactPerson" label="联系人" width="100" show-overflow-tooltip />
					<el-table-column prop="contactPhone" label="联系电话" width="130" show-overflow-tooltip />
					<el-table-column prop="status" label="状态" width="80" align="center">
						<template #default="scope">
							<el-switch
								v-model="scope.row.statusEnabled"
								inline-prompt
								active-text="启"
								inactive-text="停"
								@change="onStatusChange(scope.row)"
							/>
						</template>
					</el-table-column>
					<el-table-column prop="createdAt" label="创建时间" width="170" show-overflow-tooltip />
					<el-table-column prop="updatedAt" label="修改时间" width="170" show-overflow-tooltip />
					<el-table-column label="操作" width="180" fixed="right" align="center">
						<template #default="scope">
							<el-button size="small" text type="primary" @click="onEdit(scope.row)">修改</el-button>
							<el-button size="small" text type="info" @click="onViewLog(scope.row)">日志</el-button>
							<el-button size="small" text type="danger" @click="onRowDel(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>
		<EditWarehouse ref="editWarehouseRef" @getWarehouseList="getWarehouseList" />
		<OperationLogDialog ref="operationLogRef" />
	</div>
</template>

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

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listWarehouses, deleteWarehouse, updateWarehouseStatus } from '/@/api/assets/warehouse';
import EditWarehouse from './component/editWarehouse.vue';
import OperationLogDialog from '/@/views/assets/component/operationLogDialog.vue';

// 表格数据
const tableData = reactive({
	data: [] as any[],
	total: 0,
	loading: false,
	param: {
		keyword: '',
		status: undefined as string | undefined,
		pageNum: 1,
		pageSize: 10,
	},
});

// 编辑弹窗ref
const editWarehouseRef = ref();
// 日志弹窗ref
const operationLogRef = ref();

// 获取仓库列表
const getWarehouseList = async () => {
	tableData.loading = true;
	try {
		const res: any = await listWarehouses(tableData.param);
		const list = res.data?.list || [];
		// 添加 statusEnabled 字段用于开关组件
		tableData.data = list.map((item: any) => ({
			...item,
			statusEnabled: item.status === 'enable' || item.status === '1' || item.status === 1,
		}));
		tableData.total = res.data?.total || 0;
	} catch (error) {
		console.error('获取仓库列表失败:', error);
	} finally {
		tableData.loading = false;
	}
};

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

// 打开新增弹窗
const onOpenAdd = () => {
	editWarehouseRef.value.openDialog();
};

// 打开编辑弹窗
const onEdit = (row: any) => {
	editWarehouseRef.value.openDialog(row);
};

// 状态切换
const onStatusChange = async (row: any) => {
	const newStatus = row.statusEnabled ? 'enable' : 'disable';
	const statusText = row.statusEnabled ? '启用' : '禁用';
	try {
		await updateWarehouseStatus({ id: row.id, status: newStatus });
		ElMessage.success(`${statusText}成功`);
	} catch (error) {
		console.error('状态更新失败:', error);
		// 失败时恢复原状态
		row.statusEnabled = !row.statusEnabled;
	}
};

// 查看日志
const onViewLog = (row: any) => {
	operationLogRef.value?.openDialog(row.id);
};

// 删除仓库
const onRowDel = (row: any) => {
	ElMessageBox.confirm(`确定要删除仓库【${row.warehouseName}】吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		try {
			await deleteWarehouse(row.id);
			ElMessage.success('删除成功');
			getWarehouseList();
		} catch (error) {
			console.error('删除失败:', error);
		}
	}).catch(() => {});
};

// 分页大小改变
const onSizeChange = (size: number) => {
	tableData.param.pageSize = size;
	getWarehouseList();
};

// 当前页改变
const onCurrentChange = (page: number) => {
	tableData.param.pageNum = page;
	getWarehouseList();
};

// 页面加载时获取数据
onMounted(() => {
	getWarehouseList();
});
</script>

<style scoped lang="scss">
.assets-warehouse-page {
	padding: 15px;
	.assets-warehouse-container {
		.assets-warehouse-search {
			.el-form-item {
				margin-bottom: 0;
			}
		}
	}
}
</style>
