<template>
	<div class="page" style="height: calc(100% - 80px);">
		<el-form :inline="true" size="default" v-if="searchVisible" class="query-form m-b-10" ref="searchForm"
			:model="searchForm" @keyup.enter.native="refreshList()" @submit.native.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 #buttons>
					<el-button v-if="hasPermission('approval:info:edit')" type="primary" icon="el-icon-plus"
						@click="approval()"
						:disabled="$refs.todoTable && $refs.todoTable.getCheckboxRecords().length === 0">批量审核</el-button>
				</template>
				<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="vars.title">
						<template #default="scope">
							<el-link type="primary" :underline="false" v-if="scope.row.belongProject === 'ccpm'"
								@click="todoCcpm(scope.row)">{{ scope.row.vars.title }}</el-link>
							<el-link type="primary" :underline="false" v-if="scope.row.status === 'todo'"
								@click="todo(scope.row)">{{ scope.row.vars.title }}</el-link>
							<span v-else>{{ scope.row.vars.title }}</span>
						</template>
					</vxe-column>
					<vxe-column title="流程名称" field="processDefinitionName">
					</vxe-column>
					<vxe-column title="当前环节" field="task.name">
						<template #default="scope">
							<el-tag>{{ scope.row.task.name }}</el-tag>
						</template>
					</vxe-column>
					<vxe-column title="流程发起人" field="vars.userName"></vxe-column>
					<vxe-column field="task.createTime" title="创建时间">
					</vxe-column>
					<vxe-column title="操作" width="200px" fixed="right" align="center">
						<template #default="scope">
							<div v-if="scope.row.belongProject === 'ccpm'">
								<el-button type="text" size="small" @click="todoCcpm(scope.row)">项目系统审核</el-button>
							</div>
							<div v-else>
								<el-button type="primary" text @click="todo(scope.row)">办理</el-button>

								<el-button type="primary" text @click="trace(scope.row)">进度</el-button>
							</div>
						</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>
		<v-dialog title="查看进度" :close-on-click-modal="true" v-model="visible" width="70%" height="600px">
			<flow-chart ref="preview" :processInstanceId="processInstanceId"></flow-chart>
		</v-dialog>
		<user-select ref="userSelect" :limit="1" @doSubmit="selectUsersToTransferTask"></user-select>
		<user-select2 ref="userSelect2" @doSubmit="selectUser">
		</user-select2>
		<TodoDia ref="todoDia" @refreshDataList="refreshList"></TodoDia>
	</div>
</template>

<script>
// import FlowChart from '../modeler/FlowChart'
import pick from "lodash.pick";
import UserSelect from "@/components/userSelect/UserSelectDialog";
import taskService from "@/api/flowable/taskService";
import UserSelect2 from '@/views/utils/UserTreeSelect';
import TodoDia from "./TodoDia";
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,
			currentTask: null,
			processInstanceId: "",
			searchParams: {
				title: "",
				assigneeId: "",
				searchDates: "",
				// pageSize:JSON.parse(sessionStorage.getItem('nowPageData'))?.pageSize || 1
			}
		};
	},
	activated() {
		this.$nextTick(() => {
			// 将表格和工具栏进行关联
			const $table = this.$refs.todoTable;
			const $toolbar = this.$refs.todoToolbar;
			$table.connect($toolbar);
		});
		this.refreshList();
	},
	components: {
		UserSelect,
		UserSelect2,
		TodoDia
		// FlowChart
	},
	watch: {
		searchDates() {
			if (this.searchDates) {
				this.searchForm.beginDate = this.searchDates[0];
				this.searchForm.endDate = this.searchDates[1];
			} else {
				this.searchForm.beginDate = "";
				this.searchForm.endDate = "";
			}
		},
		index(index) {
			if (index === this.i) {
				this.refreshList()
			}
		}
	},
	methods: {
		// 获取数据列表
		refreshList() {
			this.loading = true;
			//let loginUserId = this.$store.state.user.id  // 获取当前登录用户id

			console.log("this.sessionStorage", sessionStorage)
			if (sessionStorage) {
				var beginDate = sessionStorage.getItem("beginDate")
				var endDate = sessionStorage.getItem("endDate")
				var title = this.searchForm.title
				var assigneeId = this.searchForm.assigneeId
				if (beginDate) {
					this.searchForm.beginDate = beginDate;
				}
				if (endDate) {
					this.searchForm.endDate = endDate;
				}
				if (beginDate && endDate) {
					var searchDates = []
					searchDates.push(beginDate)
					searchDates.push(endDate)
					this.searchDates = searchDates
				}
				if (title) {
					this.searchForm.title = title;
				}
				if (assigneeId) {
					this.searchForm.assigneeId = assigneeId;
				}
			}
			if (this.searchForm.beginDate) {
				sessionStorage.setItem("beginDate", this.searchForm.beginDate)
			}
			if (this.searchForm.endDate) {
				sessionStorage.setItem("endDate", this.searchForm.endDate)
			}
			if (this.searchForm.title) {
				sessionStorage.setItem("title", this.searchForm.title)
			}
			if (this.searchForm.assigneeId) {
				sessionStorage.setItem("assigneeId", this.searchForm.assigneeId)
			}

			taskService
				.todoList({
					current: this.tablePage.currentPage,
					size: this.tablePage.pageSize,
					orders: this.tablePage.orders,
					...this.searchForm,
				})
				.then((data) => {
					console.log('zzz', data.records)
					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();
		},
		todo(row) {
			console.log('row', row)
			//页面跳转后返回当前页筛选项仍保留
			let _data = Object.assign(this.searchParams, {});//将筛选项存入到data中
			sessionStorage.setItem('nowPageData', JSON.stringify(_data));//存入到sessionStorage中
			taskService
				.getTaskDef({
					taskId: row.task.id,
					taskName: row.task.name,
					taskDefKey: row.task.taskDefinitionKey,
					procInsId: row.task.processInstanceId,
					procDefId: row.task.processDefinitionId,
					procDefKey: row.task.processDefKey,
					status: row.status,
				})
				.then(async (data) => {
					// 如果为报销
					if (this.isReimbursementProcess(data.procDefKey)) {
						// 根据流程名称获取对应的报销表单地址
						let url = this.isReimbursementUrl(row.processDefinitionName)
						if (url) {
							let approvalTime = await taskService.getApprovalTimeByProcInsId(row.task.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/TaskForm",
						query: {
							formTitle: `${row.vars.title}`,
							title: `审批【${row.task.name || ""}】`,
							...pick(
								data,
								"formType",
								"formReadOnly",
								"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);
		},
		trace(row) {
			this.processInstanceId = row.task.processInstanceId;
			this.visible = true;
			this.$nextTick(() => {
				this.$refs.preview.init();
			});
		},
		transferTask(row) {
			this.currentTask = row.task;
			this.$refs.userSelect.init();
		},
		selectUsersToTransferTask(user) {
			taskService
				.delegate(this.currentTask.id, user[0].id)
				.then((data) => {
					this.$message.success(data);
					this.refreshList();
				});
		},
		resetSearch() {
			this.searchDates = "";
			this.$refs.searchForm.resetFields();
			this.$nextTick(() => {
				this.refreshList();
			});
			sessionStorage.clear()
		},
		openUserDia() {
			this.$refs.userSelect2.init()
		},
		selectUser(user) {
			console.log(user[0].name)
			this.searchForm.assigneeId = user[0].name
		},
		approval() {
			let info = this.$refs.todoTable.getCheckboxRecords()
			this.$refs.todoDia.init(info)
		},
		// // 审核方法
		todoCcpm(row) {
			console.log('row', row)
			if (row.task.processDefKey === '108' || row.task.processDefKey === '109' || row.task.processDefKey === '13' || row.task.processDefKey === '102') {
				console.log('row', row)
				let id = row.vars.notifyId
				let title = '报销申请审批'
				this.toCenterForm(id, title, row.task.processDefKey, 'audit') // 跳转
			} else if (row.task.processDefKey === '21' || row.task.processDefKey === '213') {

				let id = row.vars.notifyId
				let title = '发票申请审批'
				this.toInvoiceUpdateCenterForm(id, title, row.task.processDefKey, 'audit') // 跳转
				// if (row.task.name === '财务部门审批'){
				// }else {
				// 	this.toInvoiceCenterForm(id, title, row.task.processDefKey, 'audit') // 跳转
				// }
			} else {
				this.$message.warning('此流程的跨系统审核暂未开放，请前往所属系统进行审核')
			}
		},
		// // 审核页面跳转
		toCenterForm(id, title, processDefKey, type) {
			this.$router.push({ // 跳转
				path: '/generateForm/Generateform',
				query: {
					id: id,
					backPath: '/flowable/task/TodoList',
					title: title,
					processDefKey: processDefKey,
					type: type
				}
			})
		},
		// // 发票审核页面跳转(财务审批)
		toInvoiceUpdateCenterForm(id, title, processDefKey, type) {
			this.$router.push({ // 跳转
				path: '/generateForm/InvoiceUpdateGenerateForm',
				query: {
					id: id,
					backPath: '/flowable/task/TodoList',
					title: title,
					processDefKey: processDefKey,
					type: type
				}
			})
		},
		// // 发票审核页面跳转
		toInvoiceCenterForm(id, title, processDefKey, type) {
			this.$router.push({ // 跳转
				path: '/generateForm/InvoiceGenerateForm',
				query: {
					id: id,
					backPath: '/flowable/task/TodoList',
					title: title,
					processDefKey: processDefKey,
					type: type
				}
			})
		}

	},
};
</script>
