<template>
	<el-card class="box-card">
		<template #header>
			<div class="card-header">
				<span>我的待办
					<el-badge class="mark" v-if="backlogCount !== 0" :value="backlogCount" :max="999999"
						style="line-height: 0;margin-top: 8px" />
				</span>

				<div style="float:right;">
					<el-button type="text" @click="refreshList()">刷新</el-button>
					<el-button type="text" @click="toPendingList()">更多>></el-button>
				</div>
			</div>
		</template>
		<el-table :data="dataList" style="width: 100%" height="480" border="inner" :menu-config="{}"
			@sort-change="sortChangeHandle" :sort-config="{ remote: true }" resizable>
			<el-table-column min-width="400px" label="实例标题" prop="vars.title" show-overflow-tooltip>
				<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>
			</el-table-column>
			<el-table-column width="90px" label="流程名称" show-overflow-tooltip prop="processDefinitionName">
			</el-table-column>
			<el-table-column width="100px" label="发起人" show-overflow-tooltip prop="vars.userName"></el-table-column>
			<el-table-column fixed="right" width="100px" label="当前环节" show-overflow-tooltip prop="task.name">
				<template #default="scope">
					<el-tag>{{ scope.row.task.name }}</el-tag>
				</template>
			</el-table-column>
			<el-table-column fixed="right" width="100px" prop="task.createTime" show-overflow-tooltip label="发起时间">
			</el-table-column>
			<el-table-column label="操作" width="100px" fixed="right" align="center">
				<template #default="scope">
					<div v-if="scope.row.belongProject === 'ccpm'">
						<el-button type="text" size="small" @click="todoCcpm(scope.row)">ccpm审核</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>
			</el-table-column>
		</el-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 style="height: calc(100% - 55px);margin-top: 5px">
			<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"
				header-align="center"
				:checkbox-config="{}">
				<vxe-column title="实例标题" field="vars.title">
				</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="100px" fixed="right" align="center">
					<template #default="scope">
						<div>
							<el-button text type="primary" @click="todo(scope.row)">办理</el-button>
							<el-button  text type="primary" @click="trace(scope.row)">进度</el-button>
						</div>
					</template>
				</vxe-column>
			</vxe-table>
			<vxe-pager
				background
				style="margin-top: 5px"
				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>-->
	</el-card>
	<v-dialog title="查看进度" :close-on-click-modal="true" append-to-body v-model="visible" width="70%" height="600px">
		<flow-chart ref="preview" :processInstanceId="processInstanceId"></flow-chart>
	</v-dialog>

	<UpdatePassword ref="updatePassword" :innerVisible="innerVisible" v-on:innerDialog="getInnerStatus($event)">
	</UpdatePassword>
</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 userService from "@/api/sys/UserService";
import UpdatePassword from "@/views/layout/UpdatePassword2.vue";
export default {
	title: "我的待办",
	icon: "wodedaiban",
	description: "我的待办任务",
	layout: {
		w: 6,
		h: 15,
	},
	data() {
		return {
			dataList: [],
			tablePage: {
				total: 0,
				currentPage: 1,
				pageSize: 10,
				orders: [],
			},
			loading: false,
			visible: false,
			currentTask: null,
			processInstanceId: "",
			timer: null,
		};
	},
	computed: {
		backlogCount() {
			return this.$store.state.global.backlogCount
		},
	},
	mounted() {

		// 页面加载后
		// 1.在执行定时器前先执行一次获取接口数据的操作函数, 否则接口会1秒钟后才调用
		// 2.为了避免退出当前页面后,在其他页面也继续调用接口,退出前需要清除定时器.
		this.refreshList();
		if (this.$store.state.user.timer1 == null) {
			this.$store.state.user.timer1 = setInterval(() => {
				this.refreshList()
			}, 60000)
		}


	},
	created() {
		// 判断当前用户是否为管理员
		userService.is().then((data) => {
			if (!data) {
				// 如果当前用户不是管理员，则判断是否修改过密码
				userService.isUpdatePassword().then((data) => {
					if (!data) {
						// 如果没有修改过密码，则弹出密码修改窗口
						this.innerVisible = true
						this.$refs.updatePassword.init(!data)
					}
				})
			}
		})
	},
	beforeDestroy() {
		if (this.$store.state.user.timer1) {
			clearInterval(this.$store.state.user.timer1); // 如果是 setInterval
			this.$store.state.user.timer1 = null;
		}
	},
	activated() {
		this.refreshList();
	},
	components: {
		UserSelect,
		UpdatePassword,
		// FlowChart
	},
	methods: {
		getInnerStatus(status) {
			this.innerVisible = status
		},
		// 获取数据列表
		refreshList() {
			this.loading = true;
			taskService
				.todoList({
					current: this.tablePage.currentPage,
					size: this.tablePage.pageSize,
					orders: this.tablePage.orders,
					...this.searchForm,
				})
				.then((data) => {
					console.log('data', data.records)
					this.dataList = data.records;
					this.tablePage.total = data.total;
					this.$store.state.global.backlogCount = data.total
					this.loading = false;
				});
		},
		// 当前页
		currentChangeHandle({ currentPage, pageSize }) {
			this.tablePage.currentPage = currentPage;
			this.tablePage.pageSize = pageSize;
			this.refreshList();
		},
		todo(row) {
			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 urlObj = this.isReimbursementUrl(row.processDefinitionName)
						if (urlObj) {
							let approvalTime = null
							// 判断是否为文件补充流程和报销流程
							if (urlObj.type && urlObj.type === 'file') {
								approvalTime = await taskService.getCreateTimeByProcInsId(row.task.processInstanceId)
							} else {
								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 = urlObj.url
								}
							}
						}
					}
					var cs = "cs"
					this.$router.push({
						path: "/flowable/task/TaskForm",
						query: {
							wareHouseId: row.processDefinitionName === '物资管理-入库修改' ? data.businessId : '',
							returnId: row.processDefinitionName === '物资管理-领用退回申请' ? data.businessId : '',
							cwArchiveId: row.processDefinitionName === '会计-项目报告归档' ? data.businessId : '',
							formTitle: `${row.vars.title}`,
							title: `审批【${row.task.name || ""}】`,
							cs: cs,
							...pick(
								data,
								"formType",
								"formReadOnly",
								"formUrl",
								"procDefKey",
								"taskDefKey",
								"procInsId",
								"procDefId",
								"taskId",
								"status",
								"title",
								"businessId"
							),
						},
					});
				});
		},
		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_1706176397323",
				"Process_1706176937876",
				"Process_1706671221048",
				"Process_1706679472488",
				"Process_1706680073642",
				"Process_1706680331785",
				"Process_1706680660857",
				"Process_1709102298565",
				"Process_1709104787957",
				"Process_1711418224962",
				"Process_1722305645394",
				"Process_1722412442950",
				"Process_1722416114655",
				"Process_1722404901733",
				"Process_1722389642543",
				"Process_1713769833657"
			];
			return reimbursementProcesses.includes(procDefKey);
		},
		isReimbursementUrl(name) {
			// 会计-文件补充
			let cwFile = ["会计-报销文件补充"]
			//项目-报销文件补充
			let ccpmFile = ["项目-报销文件补充"]
			//咨询-报销文件补充
			let zxFile = ["咨询-报销文件补充"]
			//中审-文件补充
			let zsFile = ["中审-报销文件补充"]
			//评估-文件补充
			let pgFile = ["评估-报销文件补充"]
			// 会计
			let cw = ["会计-所长报销", "会计-所长报销-电子发票", "会计-总经办报销", "盛所会计-报销申请", "会计-报销审批", "会计-报销审批-电子发票"]
			// 中审
			let zs = ["中审-所长报销", "中审-所长报销-电子发票", "中审-总经办报销", "中审-报销审批", "中审-报销审批-电子发票", "中审-苏州分公司(智永祥)-报销"]
			// 评估
			let pg = ["评估-总经办报销", "评估-所长报销", "评估-所长报销-电子发票", "评估-报销申请", "评估-报销审批-电子发票"]
			// 项目
			let ccpm = ["物资-项目报销", "项目-总经办报销", "项目-报销审批", "项目-报销审批-电子发票", "盛所项目-报销申请",]
			// 咨询
			let zx = ["咨询-总经办报销", "咨询-所长报销", "咨询-所长报销-电子发票", "咨询-报销审批", "咨询-报销审批-电子发票"]
			// 苏州
			let sz = ["苏州-业务操作报销"]
			if (sz.includes(name)) {
				return {
					url: '/cw/szfbReimbursementApproval/info/NewReimbursementForm',
					type: 'reimbursement'
				}
			}
			if (cw.includes(name)) {
				return {
					url: '/cw/reimbursementApproval/info/NewReimbursementForm',
					type: 'reimbursement'
				}
			}
			if (zs.includes(name)) {
				return {
					url: '/zs/reimbursement/info/NewReimbursementForm',
					type: 'reimbursement'
				}
			}
			if (pg.includes(name)) {
				return {
					url: '/reimbursement/info/NewReimbursementForm',
					type: 'reimbursement'
				}
			}
			if (ccpm.includes(name)) {
				return {
					url: '/ccpm/reimbursement/info/NewReimbursementForm',
					type: 'reimbursement'
				}
			}
			if (zx.includes(name)) {
				return {
					url: '/consultancy/reimbursement/info/NewReimbursementForm',
					type: 'reimbursement'
				}
			}
			if (cwFile.includes(name)) {
				return {
					url: "/cw/reimbursementApproval/info/NewReimbursementFileSupplementForm",
					type: 'file'
				}
			}
			if (ccpmFile.includes(name)) {
				return {
					url: "/ccpm/reimbursement/info/NewReimbursementFileSupplementForm",
					type: 'file'
				}
			}
			if (zxFile.includes(name)) {
				return {
					url: "/consultancy/reimbursement/info/NewReimbursementFileSupplementForm",
					type: 'file'
				}
			}
			if (zsFile.includes(name)) {
				return {
					url: "/zs/reimbursement/info/NewReimbursementFileSupplementForm",
					type: 'file'
				}
			}
			if (pgFile.includes(name)) {
				return {
					url: "/reimbursement/info/NewReimbursementFileSupplementForm",
					type: 'file'
				}
			}
			return null;
		},
		toPendingList() {
			// this.$router.push('./PendingList')
			this.$router.push({
				path: '/sys/dashboard/workBench/PendingList',
				query: {
					num: 3
				}
			})
		},
		trace(row) {
			this.processInstanceId = row.task.processInstanceId;
			this.visible = true;
			this.$nextTick(() => {
				this.$refs.preview.init();
			});
		},
		// // 审核方法
		todoCcpm(row) {
			console.log('row', row)
			if (row.task.processDefKey === '108' || row.task.processDefKey === '109' || row.task.processDefKey === '13' || row.task.processDefKey === '102') {
				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: '/dashboard/index',
					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>
<style scoped>
.box-card {
	height: 100%;
}
</style>
