<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="lossNo">
				<el-input v-model="searchForm.lossNo" clearable placeholder="请输入报损编号" />
			</el-form-item>
			<el-form-item label="物品名称" prop="goodsName">
				<el-input v-model="searchForm.goodsName" clearable placeholder="请输入物品名称" />
			</el-form-item>
			<el-form-item v-if="showHideItem" label="经办人" prop="handledBy">
				<UserSelect :limit="1" :modelValue="searchForm.handledBy"
					@update:modelValue="value => (searchForm.handledBy = value)" />
			</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="lossDates">
				<el-date-picker v-model="searchForm.lossDates" 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>
				<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="jp-table top">
			<vxe-toolbar :refresh="{ query: refreshList }" custom>
				<template #buttons>
					<el-button v-if="hasPermission('psi:loss:add')" type="primary" icon="el-icon-plus" @click="start()">
						新建
					</el-button>
					<el-button v-if="hasPermission('psi:loss:edit')" type="warning" icon="el-icon-download"
						@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="lossNo">
						<template #default="scope">
							<el-link v-if="hasPermission('psi:loss:list')" type="primary" :underline="false"
								@click="view(scope.row.id)">
								{{ scope.row.lossNo }}
							</el-link>
							<span v-else>{{ scope.row.lossNo }}</span>
						</template>
					</vxe-column>
					<vxe-column min-width="180" align="center" title="物品名称" field="goodsName" />
					<vxe-column min-width="160" align="center" title="经办人" field="handledByName" />
					<vxe-column min-width="180" align="center" title="经办部门" field="handledByOfficeName" />
					<vxe-column min-width="160" align="center" title="报损时间" field="lossDate" />
					<vxe-column min-width="120" align="center" fixed="right" 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="220" fixed="right" align="center">
						<template #default="scope">
							<el-button
								v-if="hasPermission('psi:loss:edit') && scope.row.createBy === $store.state.user.id && (scope.row.status === '1' || scope.row.status === '3')"
								text type="primary" size="small" @click="push(scope.row)">
								修改
							</el-button>
							<el-button
								v-else-if="hasPermission('psi:loss:edit') && isAdmin && ['1', '3', '4', '5'].includes(scope.row.status)"
								text type="primary" size="small" @click="edit(scope.row.id)">
								修改
							</el-button>
							<el-button
								v-if="hasPermission('psi:loss:edit') && scope.row.createBy === $store.state.user.id && scope.row.status === '2'"
								text type="primary" size="small" @click="reback(scope.row)">
								撤回
							</el-button>
							<el-button
								v-if="hasPermission('psi:loss:del') && scope.row.createBy === $store.state.user.id && (scope.row.status === '1' || scope.row.status === '3')"
								text type="primary" size="small" @click="del(scope.row.id)">
								删除
							</el-button>
							<el-button
								v-else-if="hasPermission('psi:loss:del') && isAdmin && ['1', '3', '4', '5'].includes(scope.row.status)"
								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>
							<el-button
								v-if="hasPermission('psi:loss:edit') && scope.row.status === '4' && scope.row.createBy === $store.state.user.id"
								text type="primary" size="small" @click="adjust(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" />

				<UpdateLossInfoForm ref="updateLossInfoForm" @refreshList="refreshList" />
			</div>
		</div>
	</div>
</template>

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

export default {
	components: {
		UserSelect,
		SelectTree,
		UpdateLossInfoForm,
	},
	data() {
		return {
			searchVisible: true,
			showHideItem: false,
			showHideIcon: "el-icon-arrow-down",
			showHideName: "展示",
			searchForm: {
				handledBy: "",
				handledByOffice: "",
				lossNo: "",
				goodsName: "",
				lossDates: [],
			},
			dataList: [],
			tablePage: {
				total: 0,
				currentPage: 1,
				pageSize: 10,
				orders: [],
			},
			tableKey: "",
			loading: false,
			processDefinitionAuditId: "",
			procDefAuditKey: "",
			isAdmin: false,
		};
	},
	created() {
		this.lossService = new LossService();
	},
	computed: {
		userName() {
			return this.$store.state.user.name;
		},
	},
	mounted() {
		this.refreshList();
	},
	activated() {
		this.refreshList();
	},
	methods: {
		showHide() {
			this.showHideItem = !this.showHideItem;
			this.showHideIcon = this.showHideItem ? "el-icon-arrow-up" : "el-icon-arrow-down";
			this.showHideName = this.showHideItem ? "隐藏" : "展示";
		},
		edit(id) {
			this.$refs.updateLossInfoForm.init("edit", id);
		},
		view(id) {
			this.$refs.updateLossInfoForm.init("view", id);
		},
		checkIsAdmin() {
			userService.is().then(data => {
				this.isAdmin = data;
			});
		},
		refreshList() {
			this.loading = true;
			this.lossService
				.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.checkIsAdmin();
			processService.getByName("进销存-报损申请").then(data => {
				if (!this.commonJS.isEmpty(data.id)) {
					this.processDefinitionAuditId = data.id;
					this.procDefAuditKey = data.key;
				}
			});
		},
		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();
		},
		del(id) {
			this.$confirm("确定删除当前数据吗？", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				this.loading = true;
				this.lossService
					.remove(id)
					.then(msg => {
						this.$message.success(msg);
						this.refreshList();
					})
					.finally(() => {
						this.loading = false;
					});
			});
		},
		resetSearch() {
			this.$refs.searchForm.resetFields();
			this.refreshList();
		},
		start() {
			const tabTitle = "发起流程【报损申请】";
			const processTitle = `${this.userName} 在${this.moment(new Date()).format("YYYY-MM-DD HH:mm")}发起了[报损申请]`;
			taskService
				.getTaskDef({
					procDefId: this.processDefinitionAuditId,
					status: "startAndHold",
				})
				.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,
							status: "startAndHold",
							title: tabTitle,
							formType: data.formType,
							formUrl: data.formUrl,
							formTitle: processTitle,
							businessId: "false",
							isShow: false,
							routePath: "/psiManagement/loss/LossList",
						},
					});
				});
		},
		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";
			}
			taskService
				.getTaskDef({
					procDefId: this.processDefinitionAuditId,
					businessId: row.id,
					businessTable: "psi_management_loss_basics",
				})
				.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: "psi_management_loss_basics",
							businessId: row.id,
							isShow: "false",
							status,
							routePath: "/psiManagement/loss/LossList",
						},
					});
				});
		},
		detail(row) {
			if (row.status !== "0" && row.status !== "1") {
				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.id,
								status: "reback",
							},
						});
					});
			}
		},
		reback(row) {
			this.$confirm("确定要撤回该申请吗？", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				this.lossService.findById(row.id).then(data => {
					if (data.status !== "2") {
						this.$message.error("数据已发生变化，请刷新后重试");
						this.refreshList();
						return;
					}
					processService.revokeProcIns(row.procInsId).then(msg => {
						this.lossService.updateStatusById({ status: "3", id: row.id }).then(() => {
							this.$message.success(msg);
							this.refreshList();
						});
					});
				});
			});
		},
		adjust(row) {
			this.lossService.findById(row.id).then(data => {
				if (data.status !== "4") {
					this.$message.error("数据已发生变化，请刷新后重试");
					this.refreshList();
					return;
				}
				this.todo(row, "4");
			});
		},
		examine(row) {
			this.lossService.findById(row.id).then(data => {
				if (data.status !== "2") {
					this.$message.error("数据已发生变化，请刷新后重试");
					this.refreshList();
					return;
				}
				this.todo(row, "2");
			});
		},
		todo(row, status) {
			let formReadOnly = true
			if (status === "4") {
				formReadOnly = false
			}
			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: formReadOnly,
						formTitle: `${data.taskName}`,
						cUser: false,
						title: `审批【${data.taskName || ""}】`,
						routePath: "/psiManagement/loss/LossList",
					},
				});
			});
		},
		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.lossService.exportFile({
				current: this.tablePage.currentPage,
				size: this.tablePage.pageSize,
				orders: this.tablePage.orders,
				...options,
				...this.searchForm
			}).then((res) => {
				this.$utils.downloadExcel(res, options.filename)
				this.loading = false
			}).catch(() => {
				this.loading = false
			})
		}
	},
};
</script>
