<template>
	<div class="page" style="height: calc(100% - 80px);">
		<el-form :inline="true" v-if="searchVisible" class="query-form m-b-10" ref="searchForm" :model="searchForm"
			@keyup.enter="refreshList()" @submit.prevent>
			<el-form-item label="完成时间：" prop="searchDates">
				<el-date-picker v-model="searchDates" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
					range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
			</el-form-item>
			<el-form-item label="实例标题" prop="title">
				<el-input v-model="searchForm.title" placeholder="实例标题" clearable></el-input>
			</el-form-item>
			<el-form-item label="流程发起人" prop="assigneeId">
				<el-input v-model="searchForm.assigneeId" placeholder="请选择流程发起人">
					<template #suffix>
						<el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary"
							slot="append" icon="el-icon-search" @click="openUserDia">
							<!--						<UserSelect2  :modelValue="searchForm.assigneeId" :limit='1' @update:modelValue='(value, label) => {searchForm.assigneeId = value}'></UserSelect2>-->
						</el-button>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="refreshList()" icon="search">查询</el-button>
				<el-button type="default" @click="resetSearch()" icon="refresh-right">重置</el-button>
			</el-form-item>
		</el-form>
		<div class="jp-table">
			<vxe-toolbar ref="todoToolbar" :refresh="{ query: refreshList }" export print custom>
				<template #tools>
					<vxe-button type="text" :title="searchVisible ? '收起检索' : '展开检索'" icon="vxe-icon-search"
						class="tool-btn" @click="searchVisible = !searchVisible"></vxe-button>
				</template>
			</vxe-toolbar>
			<div class="jp-table-body">
				<vxe-table border="inner" auto-resize resizable height="auto" :loading="loading" size="small"
					ref="todoTable" show-header-overflow show-overflow highlight-hover-row :menu-config="{}"
					:print-config="{}" :import-config="{}" :export-config="{}" :data="dataList" :checkbox-config="{}">
					<vxe-column type="seq" width="40"></vxe-column>
					<vxe-column type="checkbox" width="40px"></vxe-column>
					<vxe-column title="任务" field="name">
						<template #default="scope">
							{{ scope.row.name }}
							<el-button v-if="scope.row.back" type="warning" size="small"
								@click="callback(scope.row)">撤销</el-button>
						</template>
					</vxe-column>
					<vxe-column title="实例标题" field="vars.title">
					</vxe-column>
					<vxe-column title="流程名称" field="processDefinitionName">
					</vxe-column>
					<vxe-column title="办理状态" field="status">
						<template #default="scope">
							<el-tag :type="scope.row.level">{{ scope.row.status }}
							</el-tag>
						</template>
					</vxe-column>
					<vxe-column title="流程发起人" field="vars.userName"></vxe-column>
					<vxe-column field="endTime" title="完成时间"> </vxe-column>
					<vxe-column title="操作" width="100px" fixed="right" align="center">
						<template #default="scope">
							<el-button type="primary" text @click="detail(scope.row)">历史</el-button>
						</template>
					</vxe-column>
				</vxe-table>
				<vxe-pager background size="small" :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">
				</vxe-pager>
			</div>
		</div>
		<user-select2 ref="userSelect2" @doSubmit="selectUser">
		</user-select2>
	</div>
</template>

<script>
// import FlowChart from '../modeler/FlowChart'
import pick from "lodash.pick";
import taskService from "@/api/flowable/taskService";
import UserSelect2 from '@/views/utils/UserTreeSelect';
export default {
	data() {
		return {
			searchForm: {
				beginDate: "",
				endDate: "",
				title: "",
				assigneeId: "",
			},
			searchVisible: true,
			searchDates: "",
			dataList: [],
			tablePage: {
				total: 0,
				currentPage: 1,
				pageSize: 10,
				orders: [],
			},
			loading: false,
			visible: false,
		};
	},
	created() {
		this.refreshList()
	},
	components: {
		UserSelect2
	},
	mounted() {
		this.$nextTick(() => {
			// 将表格和工具栏进行关联
			const $table = this.$refs.todoTable;
			const $toolbar = this.$refs.todoToolbar;
			$table.connect($toolbar);
		});
	},
	activated() {
		this.refreshList();
	},
	watch: {
		searchDates() {
			if (this.searchDates) {
				this.searchForm.beginDate = this.searchDates[0];
				this.searchForm.endDate = this.searchDates[1];
			} else {
				this.searchForm.beginDate = "";
				this.searchForm.endDate = "";
			}
		},
	},
	methods: {
		// 获取数据列表
		refreshList() {
			this.loading = true;
			taskService
				.historicList({
					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.loading = false;
				});
		},
		// 当前页
		currentChangeHandle({ currentPage, pageSize }) {
			this.tablePage.currentPage = currentPage;
			this.tablePage.pageSize = pageSize;
			this.refreshList();
		},
		detail(row) {
			taskService
				.getTaskDef({
					taskDefKey: row.taskDefinitionKey,
					procInsId: row.processInstanceId,
					procDefId: row.processDefinitionId,
				})
				.then(async (data) => {
					// 如果为报销
					if (this.isReimbursementProcess(data.procDefKey)) {
						// 根据流程名称获取对应的报销表单地址
						let url = this.isReimbursementUrl(row.processDefinitionName)
						if (url) {
							let approvalTime = await taskService.getApprovalTimeByProcInsId(row.processInstanceId)
							if (approvalTime) {
								// 根据发起审批的时间判断是否为新版本报销页面
								let newStartDate = this.$dictUtils.getDictLabel("new_version_reimbursement_date", '1', '-')
								const compareResult = this.validateXG.compareDate(approvalTime, newStartDate);
								const newVersionFlag = compareResult == 'same' || compareResult == 'after';

								if (newVersionFlag) {
									data.formUrl = url
								}
							}
						}
					}

					this.$router.push({
						path: "/flowable/task/TaskFormDetail",
						query: {
							readOnly: true,
							taskId: row.executionId,
							title: `${row.processDefinitionName}【${row.name}】`,
							formTitle: `${row.processDefinitionName}`,
							...pick(
								data,
								"formType",
								"formUrl",
								"procDefKey",
								"taskDefKey",
								"procInsId",
								"procDefId",
								"taskId",
								"status",
								"title",
								"businessId"
							),
						},
					});
				});
		},
		isReimbursementUrl(name) {
			// 会计
			let cw = ["会计-所长报销", "会计-所长报销-电子发票", "会计-总经办报销", "盛所会计-报销申请", "会计-报销审批", "会计-报销审批-电子发票"]
			// 中审
			let zs = ["中审-所长报销", "中审-所长报销-电子发票", "中审-总经办报销", "中审-报销审批", "中审-报销审批-电子发票"]
			// 评估
			let pg = ["评估-总经办报销", "评估-所长报销", "评估-所长报销-电子发票", "评估-报销申请", "评估-报销审批-电子发票"]
			// 项目
			let ccpm = ["物资-项目报销", "项目-总经办报销", "项目-报销审批", "项目-报销审批-电子发票", "盛所项目-报销申请",]
			// 咨询
			let zx = ["咨询-总经办报销", "咨询-所长报销", "咨询-所长报销-电子发票", "咨询-报销审批", "咨询-报销审批-电子发票"]
			if (cw.includes(name)) {
				return '/cw/reimbursementApproval/info/NewReimbursementForm'
			}
			if (zs.includes(name)) {
				return '/zs/reimbursement/info/NewReimbursementForm'
			}
			if (pg.includes(name)) {
				return '/reimbursement/info/NewReimbursementForm'
			}
			if (ccpm.includes(name)) {
				return '/ccpm/reimbursement/info/NewReimbursementForm'
			}
			if (zx.includes(name)) {
				return '/consultancy/reimbursement/info/NewReimbursementForm'
			}
			return null;
		},
		isReimbursementProcess(procDefKey) {
			const reimbursementProcesses = [
				"Process_1669271524486",
				"Process_1669271524487",
				"Process_1704851888818",
				"Process_1705370333755",
				"Process_1705389994103",
				"Process_1705390592348",
				"Process_1673924346231",
				"Process_1673924346232",
				"Process_1705391439287",
				"Process_1705391725816",
				"Process_1665383385070",
				"Process_1665383385071",
				"Process_1705454007925",
				"Process_1705454863808",
				"Process_1706170102059",
				"Process_1706175399469",
				"Process_1706176397312",
				"Process_1706176937876",
				"Process_1706671221048",
				"Process_1706679472488",
				"Process_1706680073642",
				"Process_1706680331785",
				"Process_1706680660857",
				"Process_1709102298565",
				"Process_1709104787957",
				"Process_1711418224962",
			];
			return reimbursementProcesses.includes(procDefKey);
		},
		// 取回
		callback(row) {
			console.log(row);
			this.$confirm(`确定撤销该已办任务吗?`, "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				this.loading = true;
				taskService
					.callback({
						processInstanceId: row.processInstanceId,
						preTaskDefKey: row.taskDefinitionKey,
						preTaskId: row.id,
						currentTaskId: row.currentTask.id,
						currentTaskDefKey: row.currentTask.taskDefinitionKey,
					})
					.then((data) => {
						this.loading = false;
						this.$message.success(data);
						this.refreshList();
					});
			});
		},
		resetSearch() {
			this.searchDates = "";
			this.$refs.searchForm.resetFields();
			this.$nextTick(() => {
				this.refreshList();
			});
		},
		openUserDia() {
			this.$refs.userSelect2.init()
		},
		selectUser(user) {
			console.log(user[0].name)
			this.searchForm.assigneeId = user[0].name
		}
	},
};
</script>
