<template>
	<div class="page">
		<el-form v-if="searchVisible" ref="searchForm" :model="searchForm" :inline="true" class="query-form m-b-10"
			@keyup.enter.native="refreshList" @submit.native.prevent>
			<el-form-item label="采购编号" prop="purchaseNo">
				<el-input v-model="searchForm.purchaseNo" clearable placeholder="请输入采购编号" />
			</el-form-item>
			<el-form-item label="采购人" prop="handledBy">
				<UserSelect :limit="1" :modelValue="searchForm.handledBy"
					@update:modelValue="(value) => (searchForm.handledBy = value)" />
			</el-form-item>
			<el-form-item label="采购时间" prop="purchaseTimes">
				<el-date-picker v-model="searchForm.purchaseTimes" type="datetimerange" format="YYYY-MM-DD HH:mm:ss"
					value-format="YYYY-MM-DD HH:mm:ss" range-separator="至" start-placeholder="开始时间"
					end-placeholder="结束时间" placement="bottom-start" />
			</el-form-item>
			<!-- <el-form-item v-if="showHideItem" label="采购部门" prop="handledByOffice">
				<SelectTree ref="officeTree" :props="{
					value: 'id',
					label: 'name',
					children: 'children',
				}" :url="`/system-server/sys/office/treeData?type=2`" :value="searchForm.handledByOffice" size="default"
					:accordion="true" @getValue="(value) => (searchForm.handledByOffice = value)" />
			</el-form-item> -->
			<el-form-item v-if="showHideItem" label="修改状态" prop="status">
				<el-select v-model="searchForm.status" clearable placeholder="请选择状态" style="width: 100%">
					<el-option v-for="item in $dictUtils.getDictList('cw_status')" :key="item.value" :label="item.label"
						:value="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="default" :icon="showHideIcon" @click="showHide">
					{{ showHideName }}
				</el-button>
				<el-button type="primary" icon="el-icon-search" @click="refreshList">
					查询
				</el-button>
				<el-button icon="el-icon-refresh-right" @click="resetSearch">
					重置
				</el-button>
			</el-form-item>
		</el-form>

		<div class="statistics-panel">
			<div class="statistics-card">
				<div class="statistics-label">当前筛选范围采购金额</div>
				<div class="statistics-value">{{ statisticTotalPrice }}</div>
			</div>
			<el-button type="primary" plain @click="refreshStatistics">
				刷新统计
			</el-button>
		</div>

		<div class="jp-table top">
			<vxe-toolbar :refresh="{ query: refreshList }" custom>
				<template #buttons>
					<el-button v-if="hasPermission('psi:foodPurchase:add')" type="primary" icon="el-icon-plus"
						@click="start">
						新增
					</el-button>
					<el-button v-if="hasPermission('psi:foodPurchase:export')" type="warning" icon="el-icon-download"
						plain @click="exportFile">
						导出
					</el-button>
				</template>
				<template #tools>
					<vxe-button text type="primary" icon="vxe-icon-search" class="tool-btn"
						:title="searchVisible ? '收起搜索' : '展开搜索'" @click="searchVisible = !searchVisible" />
				</template>
			</vxe-toolbar>

			<div style="height: calc(100% - 90px)">
				<vxe-table ref="clientTable" :key="tableKey" border="inner" auto-resize resizable height="auto"
					:loading="loading" show-header-overflow show-overflow highlight-hover-row :menu-config="{}"
					:sort-config="{ remote: true }" :data="dataList" :checkbox-config="{}"
					@sort-change="sortChangeHandle">
					<vxe-column type="seq" width="60" title="序号" />
					<vxe-column min-width="180" align="center" title="采购编号" field="purchaseNo">
						<template #default="scope">
							<el-link v-if="hasPermission('psi:foodPurchase:list')" type="primary" :underline="false"
								@click="view(scope.row.id)">
								{{ scope.row.purchaseNo }}
							</el-link>
							<span v-else>{{ scope.row.purchaseNo }}</span>
						</template>
					</vxe-column>
					<vxe-column min-width="180" align="center" title="采购时间" field="purchaseTime" />
					<vxe-column min-width="160" align="center" title="采购金额" field="totalPrice" />
					<!-- <vxe-column min-width="180" align="center" title="待变更时间" field="changePurchaseTime">
						<template #default="scope">
							<span v-if="scope.row.status != '5' && scope.row.status != '0'">
								{{ scope.row.changePurchaseTime }}
							</span>
							<span v-else class="text-gray">-</span>
						</template>
					</vxe-column>
					<vxe-column min-width="160" align="center" title="待变更金额" field="changeTotalPrice">
						<template #default="scope">
							<span v-if="scope.row.status != '5' && scope.row.status != '0'">
								{{ scope.row.changeTotalPrice }}
							</span>
							<span v-else class="text-gray">-</span>
						</template>
					</vxe-column> -->
					<vxe-column min-width="160" align="center" title="采购人" field="handledByName" />
					<vxe-column min-width="140" align="center" title="修改状态" field="status">
						<template #default="scope">
							<el-button effect="dark"
								:type="$dictUtils.getDictLabel('cw_status_flag', scope.row.status, '')"
								@click="detail(scope.row)">
								{{
									$dictUtils.getDictLabel(
										"cw_status",
										scope.row.status,
										"未发起"
									)
								}}
							</el-button>
						</template>
					</vxe-column>
					<vxe-column title="操作" width="320" fixed="right" align="center">
						<template #default="scope">
							<el-button v-if="
								hasPermission('psi:foodPurchase:edit') &&
								['0', '1', '3', '5'].includes(scope.row.status || '0')
							" text type="primary" size="small" @click="push(scope.row)">
								申请修改
							</el-button>
							<el-button v-if="
								hasPermission('psi:foodPurchase:edit') &&
								scope.row.status === '4'
							" text type="primary" size="small" @click="adjust(scope.row)">
								驳回调整
							</el-button>
							<el-button v-if="
								hasPermission('psi:foodPurchase:edit') &&
								scope.row.status === '2'
							" text type="primary" size="small" @click="reback(scope.row)">
								撤回
							</el-button>
							<el-button v-if="
								hasPermission('psi:foodPurchase:edit') &&
								scope.row.changeId &&
								['1', '3', '4'].includes(scope.row.status || '')
							" text type="primary" size="small" @click="terminateChange(scope.row)">
								终止申请
							</el-button>
							<el-button v-if="
								hasPermission('psi:foodPurchase:del') &&
								!scope.row.changeId &&
								scope.row.status !== '2'
							" text type="primary" size="small" @click="del(scope.row.id)">
								删除
							</el-button>
							<el-button v-if="
								scope.row.status === '2' &&
								checkIsAudit(scope.row)
							" text type="primary" size="small" @click="examine(scope.row)">
								审核
							</el-button>
						</template>
					</vxe-column>
				</vxe-table>

				<vxe-pager background :current-page="tablePage.currentPage" :page-size="tablePage.pageSize"
					:total="tablePage.total" :page-sizes="[
						10,
						20,
						100,
						1000,
						{ label: '全量数据', value: 1000000 },
					]" :layouts="[
						'PrevPage',
						'JumpNumber',
						'NextPage',
						'FullJump',
						'Sizes',
						'Total',
					]" @page-change="currentChangeHandle" />

				<UpdateFoodPurchaseForm ref="updateFoodPurchaseForm" @refreshList="refreshList" />
			</div>
		</div>
	</div>
</template>

<script>
import pick from "lodash.pick";
import UserSelect from "@/components/userSelect";
import SelectTree from "@/components/treeSelect/treeSelect.vue";
import taskService from "@/api/flowable/taskService";
import processService from "@/api/flowable/processService";
import userService from "@/api/sys/userService";
import FoodPurchaseService from "@/api/psi/FoodPurchaseService";
import UpdateFoodPurchaseForm from "./UpdateFoodPurchaseForm";

export default {
	components: {
		UserSelect,
		SelectTree,
		UpdateFoodPurchaseForm,
	},
	data() {
		return {
			searchVisible: true,
			showHideItem: false,
			showHideIcon: "el-icon-arrow-down",
			showHideName: "展开",
			searchForm: {
				purchaseNo: "",
				handledBy: "",
				handledByOffice: "",
				status: "",
				purchaseTimes: [],
			},
			dataList: [],
			tablePage: {
				total: 0,
				currentPage: 1,
				pageSize: 10,
				orders: [],
			},
			tableKey: "",
			loading: false,
			statisticTotalPrice: "0.00",
			processDefinitionAuditId: "",
			procDefAuditKey: "",
			isAdmin: false,
		};
	},
	created() {
		this.foodPurchaseService = new FoodPurchaseService();
	},
	computed: {
		userName() {
			return this.$store.state.user.name;
		},
	},
	mounted() {
		this.refreshList();
	},
	activated() {
		this.refreshList();
	},
	methods: {
		getEditBusinessTable() {
			return "psi_management_food_purchase_change";
		},
		showHide() {
			this.showHideItem = !this.showHideItem;
			this.showHideIcon = this.showHideItem
				? "el-icon-arrow-up"
				: "el-icon-arrow-down";
			this.showHideName = this.showHideItem ? "隐藏" : "展开";
		},
		checkIsAdmin() {
			userService.is().then((data) => {
				this.isAdmin = data;
			});
		},
		start() {
			this.$refs.updateFoodPurchaseForm.init("add", "");
		},
		view(id) {
			this.$refs.updateFoodPurchaseForm.init("view", id);
		},
		refreshList() {
			this.loading = true;
			this.foodPurchaseService
				.list({
					current: this.tablePage.currentPage,
					size: this.tablePage.pageSize,
					orders: this.tablePage.orders,
					...this.searchForm,
				})
				.then((data) => {
					this.dataList = data.records;
					this.tablePage.total = data.total;
					this.tableKey = Math.random();
				})
				.finally(() => {
					this.loading = false;
				});
			this.refreshStatistics();
			this.checkIsAdmin();
			processService.getByName("食材采购统计-修改").then((data) => {
				if (!this.commonJS.isEmpty(data.id)) {
					this.processDefinitionAuditId = data.id;
					this.procDefAuditKey = data.key;
				}
			});
		},
		refreshStatistics() {
			this.foodPurchaseService
				.statistics({ ...this.searchForm })
				.then((data) => {
					this.statisticTotalPrice = data.totalPrice || "0.00";
				});
		},
		currentChangeHandle({ currentPage, pageSize }) {
			this.tablePage.currentPage = currentPage;
			this.tablePage.pageSize = pageSize;
			this.refreshList();
		},
		sortChangeHandle(column) {
			this.tablePage.orders = [];
			if (column.order != null) {
				this.tablePage.orders.push({
					column: this.$utils.toLine(column.property),
					asc: column.order === "asc",
				});
			}
			this.refreshList();
		},
		resetSearch() {
			this.$refs.searchForm.resetFields();
			this.refreshList();
		},
		del(id) {
			this.$confirm("确定删除当前数据吗？", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				this.loading = true;
				this.foodPurchaseService
					.remove(id)
					.then((msg) => {
						this.$message.success(msg);
						this.refreshList();
					})
					.finally(() => {
						this.loading = false;
					});
			});
		},
		push(row) {
			const title = "发起流程【食材采购修改】";
			const processTitle = `${this.userName} 在 ${this.moment(
				new Date()
			).format("YYYY-MM-DD HH:mm")} 发起了[食材采购修改]`;
			let status = "startAndHold";
			if (row.status === "3") {
				status = "startAndClose";
			} else if (row.status === "4") {
				status = "reapplyFlag";
			}
			this.foodPurchaseService.prepareChange(row.id).then((biz) => {
				taskService
					.getTaskDef({
						procDefId: this.processDefinitionAuditId,
						businessId: biz.businessId,
						businessTable: this.getEditBusinessTable(),
					})
					.then((data) => {
						this.$router.push({
							path: "/flowable/task/TaskForm",
							query: {
								...pick(
									data,
									"formType",
									"formUrl",
									"procDefKey",
									"taskDefKey",
									"procInsId",
									"procDefId",
									"taskId",
									"status",
									"title"
								),
								procDefId: this.processDefinitionAuditId,
								procDefKey: this.procDefAuditKey,
								title,
								formType: data.formType,
								formUrl: data.formUrl,
								formTitle: processTitle,
								businessTable: this.getEditBusinessTable(),
								businessId: biz.businessId,
								isShow: "false",
								status,
								routePath:
									"/psiManagement/foodPurchase/FoodPurchaseList",
							},
						});
					});
			});
		},
		detail(row) {
			if (!row.procInsId || ["0", "1"].includes(row.status || "0")) {
				return;
			}
			taskService
				.getTaskDef({
					procInsId: row.procInsId,
					procDefId: this.processDefinitionAuditId,
				})
				.then((data) => {
					this.$router.push({
						path: "/flowable/task/TaskFormDetail",
						query: {
							...pick(
								data,
								"formType",
								"formUrl",
								"procDefKey",
								"taskDefKey",
								"procInsId",
								"procDefId",
								"taskId",
								"status",
								"title"
							),
							isShow: "false",
							readOnly: true,
							title: "食材采购修改流程详情",
							formTitle: "食材采购修改流程详情",
							businessId: row.changeId || row.id,
							businessTable: row.changeId
								? this.getEditBusinessTable()
								: "psi_management_food_purchase_basic",
							status: "reback",
						},
					});
				});
		},
		reback(row) {
			this.$confirm("确定撤回该修改申请吗？", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				this.foodPurchaseService.findChangeById(row.changeId).then((data) => {
					if (data.status !== "2") {
						this.$message.error("数据已发生变化，请刷新后重试");
						this.refreshList();
						return;
					}
					processService.revokeProcIns(row.procInsId).then((msg) => {
						this.foodPurchaseService
							.updateChangeStatusById({
								status: "3",
								id: row.changeId,
							})
							.then(() => {
								this.$message.success(msg);
								this.refreshList();
							});
					});
				});
			});
		},
		terminateChange(row) {
			this.$confirm("确定终止该修改申请吗？终止后会删除修改数据，并恢复展示原始数据。", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(async () => {
				try {
					if (!row.changeId) {
						this.$message.error("修改单不存在，请刷新后重试");
						this.refreshList();
						return;
					}
					const changeData = await this.foodPurchaseService.findChangeById(row.changeId);
					if (this.commonJS.isEmpty(changeData.id)) {
						this.$message.error("修改单不存在，请刷新后重试");
						this.refreshList();
						return;
					}
					if (changeData.status === "2" && row.procInsId) {
						await processService.stop(row.procInsId, "终止食材采购修改申请");
					}
					const msg = await this.foodPurchaseService.removeChange(row.changeId);
					this.$message.success(msg || "操作成功");
					this.refreshList();
				} catch (error) {
					if (error) {
						this.refreshList();
					}
				}
			});
		},
		adjust(row) {
			this.foodPurchaseService.findChangeById(row.changeId).then((data) => {
				if (data.status !== "4") {
					this.$message.error("数据已发生变化，请刷新后重试");
					this.refreshList();
					return;
				}
				this.todo(row, false);
			});
		},
		examine(row) {
			this.foodPurchaseService.findChangeById(row.changeId).then((data) => {
				if (data.status !== "2") {
					this.$message.error("数据已发生变化，请刷新后重试");
					this.refreshList();
					return;
				}
				this.todo(row, true);
			});
		},
		todo(row, formReadOnly = true) {
			taskService.getTaskDefInfo({ taskId: row.taskId }).then((data) => {
				this.$router.push({
					path: "/flowable/task/TaskForm",
					query: {
						...pick(
							data,
							"formType",
							"formUrl",
							"procDefKey",
							"taskDefKey",
							"procInsId",
							"procDefId",
							"taskId",
							"status",
							"title",
							"businessId"
						),
						isShow: false,
						formReadOnly,
						formTitle: `${data.taskName}`,
						cUser: false,
						title: `审批【${data.taskName || ""}】`,
						businessTable: this.getEditBusinessTable(),
						routePath:
							"/psiManagement/foodPurchase/FoodPurchaseList",
					},
				});
			});
		},
		checkIsAudit(row) {
			const loginUserId = this.$store.state.user.id;
			if (this.commonJS.isNotEmpty(row.auditUserIds)) {
				return row.auditUserIds.includes(loginUserId);
			}
			return false;
		},
		exportFile() {
			const options = {
				filename: `${this.moment(new Date()).format("YYYY-MM-DD")}食材采购数据导出`,
				sheetName: "食材采购数据导出",
				mode: "all",
			};
			this.loading = true;
			this.foodPurchaseService
				.exportFile({
					current: this.tablePage.currentPage,
					size: this.tablePage.pageSize,
					orders: this.tablePage.orders,
					...options,
					...this.searchForm,
				})
				.then((res) => {
					this.$utils.downloadExcel(res, options.filename);
				})
				.finally(() => {
					this.loading = false;
				});
		},
	},
};
</script>

<style scoped>
.statistics-panel {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 12px;
	padding: 12px 16px;
	background: linear-gradient(135deg, #f7fbff 0%, #eef7f2 100%);
	border: 1px solid #dbe8dc;
	border-radius: 10px;
}

.statistics-card {
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.statistics-label {
	font-size: 13px;
	color: #6b7280;
}

.statistics-value {
	font-size: 28px;
	font-weight: 700;
	color: #14532d;
}
</style>
