<template>
	<view class="havedone-container">
		<uni-nav-bar fixed="true" statusBar="true" left-icon="back" :title="uniNavBarTitle"
		 background-color="#157A2C" color="#fff"
			@clickLeft="back"></uni-nav-bar>
			<!-- <iframe src="http://aiot.zoomwin.com.cn:51001/test/a.html" style="width: 200px;height: 600px" frameborder="0"></iframe> -->
		<view v-if="processInstance.processDefinition && taskFormComp">
			<component :is="taskFormComp" id='async-biz-form-component' :taskId="listData.taskId" :businessId="listData.businessId" :id="listData.id"
				:taskDefinitionKey="listData.taskDefinitionKey"
				 ref="bziRef"></component>
				 
		</view>
		<!-- <view v-for="(item, index) in runningTasks" :key="index">
			<div v-if="processInstance.processDefinition">
				<taskSubmit id='async-sub-form-component' :taskId="listData.taskId" :businessId="listData.businessId" :id="listData.id"
					:taskDefinitionKey="listData.taskDefinitionKey" @handleAudit="handleAudit"
					@getTableValue="getTableValue" @handleUpdateAssignee="handleUpdateAssignee(item)"
					@handleBackList="handleBackList(item)" ref="subForm">
				</taskSubmit>
			</div>
		</view> -->
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		getProcessInstance,
		getTaskListByProcessInstanceId
	} from '@/api/wt/index.js'
import Vue from 'vue'
// import taskForm from './taskForm.vue'
// import taskSubmit from './taskSubmit.vue'

	export default {
		name: 'processTask',
		// components:{ taskForm,taskSubmit },
		data() {
			return {
				uniNavBarTitle: '',
				processInstanceLoading: false,
				listData: {},
				processInstance: {},
				runningTasks: [],
				auditForms: [],
				activeComp: null,
				taskFormComp: null, // 动态加载的 taskForm 组件
			}
		},

		onLoad(option) {
			this.listData = option
			this.getDetail()
			this.activeComp = 'tab1'
			// 动态加载 miniHandleRouter 对应的 taskForm 组件
			// if (option.miniHandleRouter) {
			// 	this.loadTaskFormComponent(option.miniHandleRouter)
			// }
		},
		mounted() {

			this.$nextTick(() => {
				this.loadComponent()
			})

		},
		methods: {
			async loadComponent() {
				// pages/home/wt/components/purchaseOrder/processTask
            // 动态引入组件
			console.log('this.listData.miniHandleRouter', this.listData.miniHandleRouter)
            const Component = await import('@/pages/home' + this.listData.miniHandleRouter + '.vue');
            
            // 局部注册组件
            this.taskFormComp = Component.default || Component;
        },
			/** 动态加载 miniHandleRouter 对应的 taskForm 组件 */
		loadTaskFormComponent(router) {
			try {
				// router 格式: /wt/components/purchaseOrder/taskForm
				// require.context 在编译期解析所有 taskForm.vue，运行时按 key 取值
				const context = require.context('@/pages/home', true, /taskForm\.vue$/)
				const key = '.' + router + '.vue' // -> ./wt/components/purchaseOrder/taskForm.vue
				const module = context(key)
				if (module) {
					this.taskFormComp = module.default || module
				}
			} catch (e) {
				console.error('动态加载 taskForm 组件失败:', router, e)
				uni.showModal({
					title: '组件加载失败',
					content: `无法加载: ${router}`,
					showCancel: false
				})
			}
		},
			/** 获得流程实例 */
		async	getDetail() {
				// 获得流程实例相关
				this.processInstanceLoading = true;
				getProcessInstance({
					id: this.listData.id
				}).then(async (response) => {
					if (!response) {
						this.$message.error('查询不到流程信息！');
						return;
					}
					// 设置流程信息 
						this.processInstance = response;
					this.uniNavBarTitle =`${ response.name } 【${ response.startUser?.nickname}】`
						
			
					// //将业务表单，注册为动态组件
					// Vue.component('async-biz-form-component', (resolve) => {
					// 	require(['pages/home' + this.listData.miniHandleRouter], resolve);
					// });
					// Vue.component('async-sub-form-component', (resolve) => {
					// 	require(['pages/home' + this.listData.miniViewRouter], resolve);
					// });
					
				
					this.processInstanceLoading = false;
				});

				this.runningTasks = [];
				this.auditForms = [];
				getTaskListByProcessInstanceId({
					processInstanceId: this.listData.id
				}).then((response) => {
					console.log(response, 'response');
					// 审批记录
					this.tasks = [];
					// 移除已取消的审批
					response.forEach((task) => {
						if (task.result !== 4) {
							this.tasks.push(task);
						}
					});
					// 排序，将未完成的排在前面，已完成的排在后面；
					this.tasks.sort((a, b) => {
						// 有已完成的情况，按照完成时间倒序
						if (a.endTime && b.endTime) {
							return b.endTime - a.endTime;
						} else if (a.endTime) {
							return 1;
						} else if (b.endTime) {
							return -1;
							// 都是未完成，按照创建时间倒序
						} else {
							return b.createTime - a.createTime;
						}
					});

					// 需要审核的记录
					let userInfo = wx.getStorageSync("userInfo");
					this.tasks.forEach((task) => {
						if (task.result !== 1 && task.result !== 6) {
							// 只有待处理才需要
							return;
						}
						if (!task.assigneeUser || task.assigneeUser.id !== userInfo.userId) {
							// 自己不是处理人
							return;
						}
						if (task.taskDefinitionKey !== this.listData.taskDefinitionKey) {
							// 不是当前流程的
							return;
						}
						this.runningTasks.push({
							...task
						});
						console.log(this.runningTasks, ' this.runningTasks');
						this.auditForms.push({
							reason: ''
						});
					});
				});
			},


			/** 处理审批通过和不通过的操作 */
			handleAudit(data) {
				let text = data.status === 1 ? '通过' : '不通过';
				this.$refs.uToast.show({
					type: 'success',
					message: `审批${data.title || text}成功！`,
					iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png'
				})
				// 获得最新详情
				setTimeout(() => {
				
					uni.navigateBack()
				}, 1000)


				// const index = this.runningTasks.indexOf(task);
				// this.$refs['form' + index][0].validate((valid) => {
				//   if (!valid) {
				//     return;
				//   }
				//   const data = {
				//     id: task.id,
				//     reason: this.auditForms[index].reason
				//   };
				//   if (pass) {
				//     approveTask(data).then((response) => {
				//       this.$message.success('审批通过成功！');
				//       this.handleClose(); // 获得最新详情
				//     });
				//   } else {
				//     rejectTask(data).then((response) => {
				//       this.$message.success('审批不通过成功！');
				//       this.handleClose(); // 获得最新详情
				//     });
				//   }
				// });
			},
			getTableValue(fn) {
				fn(this.$refs.bziRef.getTableValue());
			}
		}

	}
</script>

<style>
</style>