<template>
	<view>
		<u-subsection :list="procInsId ? ['表单信息'] : ['表单信息']" mode="button" :fontSize="16" :current="tabIndex"
			@change="tabSelect"></u-subsection>
		<view v-show="0 === tabIndex">
			<scroll-view scroll-y>
				<view class=" bg-white ">
					<TestActivitiLeaveForm v-if="formUrl.endsWith('TestActivitiLeaveForm')" :formReadOnly="formReadOnly"
						:class="formReadOnly ? 'readonly' : ''" ref="form" :businessId="businessId">
					</TestActivitiLeaveForm>
					<EnrollmentRegistrationAddForm v-if="formUrl.endsWith('EnrollmentRegistrationAddForm')"
						:formReadOnly="formReadOnly" :class="formReadOnly ? 'readonly' : ''" ref="form"
						:businessId="businessId"></EnrollmentRegistrationAddForm>
					<DepartRegistrationAddForm v-else-if="formUrl.endsWith('DepartRegistrationAddForm')"
						:formReadOnly="formReadOnly" :class="formReadOnly ? 'readonly' : ''" ref="form"
						:businessId="businessId"></DepartRegistrationAddForm>
					<HandoverAddForm v-else-if="formUrl.endsWith('HandoverAddForm')" :formReadOnly="formReadOnly"
						:class="formReadOnly ? 'readonly' : ''" ref="form" :businessId="businessId"></HandoverAddForm>
					<!-- 已完成 -->
					<ReimbursementForm v-else-if="formUrl.endsWith('ReimbursementForm')" :formReadOnly="formReadOnly"
						:class="formReadOnly ? 'readonly' : ''" ref="form" :businessId="businessId"></ReimbursementForm>
					<!-- 已完成 -->
					<InvoiceFormTask v-else-if="formUrl.endsWith('InvoiceFormTask')" :formReadOnly="formReadOnly"
						:class="formReadOnly ? 'readonly' : ''" ref="form" :businessId="businessId"></InvoiceFormTask>
					<RegistrationAddForm v-else-if="formUrl.endsWith('RegistrationAddForm')"
						:formReadOnly="formReadOnly" :class="formReadOnly ? 'readonly' : ''" ref="form"
						:businessId="businessId"></RegistrationAddForm>
					<!-- 已完成 -->
					<PsiCollectForm
						v-else-if="formUrl.includes('/psiManagement/collect/') && formUrl.endsWith('CollectForm')"
						:formReadOnly="formReadOnly" :class="formReadOnly ? 'readonly' : ''" ref="form"
						:businessId="businessId" :status="status"></PsiCollectForm>
					<DishOrderApproval
						v-else-if="formUrl.includes('/psiManagement/dishManage/') && formUrl.endsWith('DishOrderApproval')"
						:formReadOnly="formReadOnly" :class="formReadOnly ? 'readonly' : ''" ref="form"
						:businessId="businessId" :status="status"></DishOrderApproval>
					<CollectForm v-else-if="formUrl.endsWith('CollectForm')" :formReadOnly="formReadOnly"
						:class="formReadOnly ? 'readonly' : ''" ref="form" :businessId="businessId"></CollectForm>
					<!-- 已完成 -->
					<PsiPurchaseForm
						v-else-if="formUrl.includes('/psiManagement/purchase/') && formUrl.endsWith('PurchaseForm')"
						:formReadOnly="formReadOnly" :class="formReadOnly ? 'readonly' : ''" ref="form"
						:businessId="businessId"></PsiPurchaseForm>
					<PsiWareHouseUpdateForm
						v-else-if="formUrl.includes('/psiManagement/wareHouse/') && formUrl.endsWith('WareHouseUpdateForm')"
						:formReadOnly="formReadOnly" :class="formReadOnly ? 'readonly' : ''" ref="form"
						:businessId="businessId" :status="status"></PsiWareHouseUpdateForm>
					<PsiLossForm v-else-if="formUrl.includes('/psiManagement/loss/') && formUrl.endsWith('LossForm')"
						:formReadOnly="formReadOnly" :class="formReadOnly ? 'readonly' : ''" ref="form"
						:businessId="businessId" :status="status"></PsiLossForm>
					<PurchaseForm v-else-if="formUrl.endsWith('PurchaseForm')" :formReadOnly="formReadOnly"
						:class="formReadOnly ? 'readonly' : ''" ref="form" :businessId="businessId"></PurchaseForm>
					<HolidayForm v-else-if="formUrl.endsWith('HolidayForm')" :formReadOnly="formReadOnly"
						:class="formReadOnly ? 'readonly' : ''" ref="form" :businessId="businessId"></HolidayForm>
					<MeetingRoomForm v-else-if="formUrl.endsWith('MeetingRoomForm')" :formReadOnly="formReadOnly"
						:class="formReadOnly ? 'readonly' : ''" ref="form" :businessId="businessId"></MeetingRoomForm>
					<!-- <component :formReadOnly="formReadOnly" :class="formReadOnly?'readonly':''"  ref="form" :businessId="businessId" :is="form"></component> -->
					<PreviewForm :formData="formData" v-if="formType !== '2'" :processDefinitionId="procDefId"
						:edit="true" ref="form"></PreviewForm>
				</view>
				<view class=" bg-white margin-top" v-if="!procInsId || taskId">
					<u--form :model="auditForm" labelWidth="130px" class="u-form" labelPosition="left" :rules="rules"
						ref="auditForm">
						<u-form-item v-if="!procInsId" label="流程标题" borderBottom prop="title">
							<u--input v-model="title" placeholder="请输入流程标题" border="none"></u--input>
						</u-form-item>
						<u-form-item v-if="taskId" label="审批意见" borderBottom prop="message">
							<u--textarea v-model="auditForm.message" placeholder="请输入审批意见" border="none"></u--textarea>
						</u-form-item>
						<u-form-item label="是否抄送" borderBottom prop="isCC">
							<u-switch v-model="isCC"></u-switch>
						</u-form-item>
						<u-form-item label="抄送给" v-if="isCC">
							<user-select v-model="auditForm.userIds"></user-select>
						</u-form-item>
						<!--					<u-form-item label="指定下一步处理者" borderBottom prop="isAssign">-->
						<!--						<u-switch v-model="isAssign" ></u-switch>-->
						<!--					</u-form-item>-->
						<u-form-item label="指定" v-if="isAssign">
							<user-select v-model="auditForm.assignee"></user-select>
						</u-form-item>
						<user-select-dialog title="选择转办用户" ref="transferUserSelectDialog" :showRadio="true"
							:showCheckBox="false" @doSubmit="selectUsersToTransferTask"></user-select-dialog>
						<user-select-dialog title="选择委派用户" ref="delegateUserSelectDialog" :showRadio="true"
							:showCheckBox="false" @doSubmit="selectUsersToDelateTask"></user-select-dialog>
						<user-select-dialog title="选择加签用户" ref="addSignTaskUserSelectDialog"
							@doSubmit="selectUsersToAddSignTask"></user-select-dialog>
						<task-back-nodes ref="taskBackNodes" @getBackTaskDefKey="back"></task-back-nodes>
						<view class="bottom-wrap  flex">
							<view class="flex-sub" v-show="button.isHide === '0'" v-for="(button, index) in buttons"
								:key="index">
								<u-button type="primary" class=" buttonBox" :color="colors[index]" :disabled="testFlag"
									@click="submit(button, buttons)" :text="button.name"></u-button>
							</view>
						</view>
					</u--form>
				</view>
				<u-gap height="70"></u-gap>
			</scroll-view>
		</view>
		<!--<view v-show="1 === tabIndex">
			<view class="padding bg-white">

				<view class="cu-timeline" :key="index" v-for="(act, index) in historicTaskList">
					<view class="cu-time">{{act.histIns.startTime |formatDate('MM-DD')}}</view>
					<view class="cu-item text-blue">
						<view class="content">
							<view class="cu-capsule radius">
								<view class="cu-tag bg-cyan">{{act.histIns.activityName}}</view>
								&lt;!&ndash; <view class="cu-tag line-cyan">{{act.histIns.activityName}}</view> &ndash;&gt;
							</view>

							<view class="margin-top">
								审批人 ： {{act.assigneeName}}
							</view>
							<view class="margin-top">
								办理状态 ：<view class="cu-tag bg-blue">{{act.comment.status}}</view>
							</view>
							<view class="margin-top">
								审批意见 ： {{act.comment.message}}
							</view>
							<view class="margin-top">
								开始时间 : {{act.histIns.startTime |formatDate}}
							</view>
							<view class="margin-top">
								结束时间 : {{act.histIns.endTime |formatDate}}
							</view>
							<view class="margin-top">
								用时 : {{act.durationTime || '0秒'}}
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>-->
		<u-divider :text="'流转记录'"></u-divider>
		<view class="padding bg-white">

			<view class="cu-timeline" :key="index" v-for="(act, index) in historicTaskList">
				<view class="cu-time">{{ act.histIns.startTime | formatDate('MM-DD') }}</view>
				<view class="cu-item text-blue">
					<view class="content">
						<view class="cu-capsule radius">
							<view class="cu-tag bg-cyan">{{ act.histIns.activityName }}</view>
							<!-- <view class="cu-tag line-cyan">{{act.histIns.activityName}}</view> -->
						</view>

						<view class="margin-top">
							审批人 ： {{ act.assigneeName }}
						</view>
						<view class="margin-top">
							办理状态 ：<view class="cu-tag bg-blue">{{ act.comment.status }}</view>
						</view>
						<view class="margin-top">
							审批意见 ： {{ act.comment.message }}
						</view>
						<view class="margin-top">
							开始时间 : {{ act.histIns.startTime | formatDate }}
						</view>
						<view class="margin-top">
							结束时间 : {{ act.histIns.endTime | formatDate }}
						</view>
						<view class="margin-top">
							用时 : {{ act.durationTime || '0秒' }}
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex'
import HolidayForm from '@/pages/dailyOfficeWork/holiday/HolidayForm.vue'
import DepartRegistrationAddForm from '@/pages/human/depart/registration/DepartRegistrationAddForm.vue'
import HandoverAddForm from '@/pages/human/depart/handover/HandoverAddForm.vue'
import ReimbursementForm from '@/pages/cw/reimbursementApproval/info/ReimbursementForm.vue'
import InvoiceFormTask from '@/pages/cw/invoice/InvoiceFormTask.vue'
import userSelect from '@/components/user-select/user-select.vue'
import userSelectDialog from '@/components/user-select/user-select-dialog.vue'
import PreviewForm from '../form/GenerateFlowableForm'
import TaskBackNodes from './components/TaskBackNodes.vue'
import TestActivitiLeaveForm from '@/pages/test/activiti/TestActivitiLeaveForm.vue'
import RegistrationAddForm from '@/pages/human/practice/register/RegistrationAddForm.vue'
import CollectForm from '@/pages/materialManagement/collect/CollectForm.vue'
import PurchaseForm from '@/pages/materialManagement/purchase/PurchaseForm.vue'
import PsiPurchaseForm from '@/pages/psiManagement/purchase/PurchaseForm.vue'
import PsiWareHouseUpdateForm from '@/pages/psiManagement/wareHouse/WareHouseUpdateForm.vue'
import PsiLossForm from '@/pages/psiManagement/loss/LossForm.vue'
import PsiCollectForm from '@/pages/psiManagement/collect/CollectForm.vue'
import DishOrderApproval from '@/pages/psiManagement/dishManage/DishOrderApproval.vue'
import EnrollmentRegistrationAddForm from '@/pages/human/enrollment/registration/EnrollmentRegistrationAddForm.vue'
import moment from 'moment'
import taskService from "@/api/flowable/taskService"
import formService from "@/api/flowable/formService"
import processService from "@/api/flowable/processService"
import flowCopyService from "@/api/flowable/flowCopyService"
import taskDefExtensionService from "@/api/flowable/taskDefExtensionService"
import MeetingRoomForm from '@/pages/dailyOfficeWork/daily/MeetingRoomForm.vue'
var graceChecker = require("@/common/graceChecker.js");
export default {
	computed: mapState({
		userInfo: (state) => state.user.userInfo,
	}),
	onLoad: async function (option) {
		this.flow = JSON.parse(decodeURIComponent(option.flow));
		this.procDefId = this.flow.procDefId
		this.procDefKey = this.flow.procDefKey
		this.formType = this.flow.formType
		this.formUrl = this.flow.formUrl
		this.taskId = this.flow.taskId
		this.taskDefKey = this.flow.taskDefKey
		this.status = this.flow.status
		this.title = this.flow.formTitle
		this.businessId = this.flow.businessId
		this.procInsId = this.flow.procInsId
		this.formReadOnly = this.flow.formReadOnly !== undefined && this.flow.formReadOnly !== 'false' && this.flow.formReadOnly !== false
		this.isCC = false
		this.isAssign = false
		this.auditForm.assignee = null
		this.auditForm.userIds = null
		this.auditForm.message = ''
		uni.setNavigationBarTitle({
			title: this.title
		});

		// 获取当前节点审核人  与  当前登录人的ID 进行对比，如果不是审核人，那么不允许操作
		/*let userId = this.userInfo.id

		// 获取 URL 中的 'flow' 参数
		const flowParam = this.$route.query.flow;
		// 将 URL 编码的 'flow' 参数解析为 JSON 对象
		const flowObject = JSON.parse(decodeURIComponent(flowParam));
		await taskService.getTaskAuditUsersForApp(this.procInsId).then((data) => {
			console.log('getTaskAuditUsersForApp.data', data)
			if (!data.includes(userId)) {
				this.testFlag = true
			}
		})*/

	},
	async mounted() {
		if (this.formType === '2') { //外置表单
			if (this.formUrl === '/404') {
				this.form = null
				uni.showToast({ title: '没有关联流程表单!', icon: "none" });
			} else {
				// uniapp 不支持动态组件，所以通过名称匹配决定调用的表单组件
				if (this.formUrl.endsWith('TestActivitiLeaveForm')) {

					this.form = TestActivitiLeaveForm
				} else if (this.formUrl.endsWith('EnrollmentRegistrationAddForm')) {
					this.form = EnrollmentRegistrationAddForm
				} else if (this.formUrl.endsWith('DepartRegistrationAddForm')) {
					this.form = DepartRegistrationAddForm
				} else if (this.formUrl.endsWith('HandoverAddForm')) {
					this.form = HandoverAddForm
				} else if (this.formUrl.endsWith('ReimbursementForm')) {
					this.form = ReimbursementForm
				} else if (this.formUrl.endsWith('InvoiceFormTask')) {
					this.form = InvoiceFormTask
				} else if (this.formUrl.endsWith('RegistrationAddForm')) {
					this.form = RegistrationAddForm
				} else if (this.formUrl.includes('/psiManagement/collect/') && this.formUrl.endsWith('CollectForm')) {
					this.form = PsiCollectForm
				} else if (this.formUrl.includes('/psiManagement/dishManage/') && this.formUrl.endsWith('DishOrderApproval')) {
					this.form = DishOrderApproval
				} else if (this.formUrl.endsWith('CollectForm')) {
					this.form = CollectForm
				} else if (this.formUrl.includes('/psiManagement/purchase/') && this.formUrl.endsWith('PurchaseForm')) {
					this.form = PsiPurchaseForm
				} else if (this.formUrl.includes('/psiManagement/wareHouse/') && this.formUrl.endsWith('WareHouseUpdateForm')) {
					this.form = PsiWareHouseUpdateForm
				} else if (this.formUrl.includes('/psiManagement/loss/') && this.formUrl.endsWith('LossForm')) {
					this.form = PsiLossForm
				} else if (this.formUrl.endsWith('PurchaseForm')) {
					this.form = PurchaseForm
				} else if (this.formUrl.endsWith('HolidayForm')) {
					this.form = HolidayForm
				} else if (this.formUrl.endsWith('MeetingRoomForm')) {
					this.form = MeetingRoomForm
				} else {
					uni.showToast({ title: '没有关联流程表单!', icon: "none" });
				}

			}
		} else { // 动态表单
			// 读取流程表单
			if (this.formUrl === '/404') {
				uni.showToast({ title: '没有关联流程表单!', icon: "none" });
			} else {
				let data = await formService.getMobileForm(this.formUrl);
				// 初始化动态表单
				data.forEach((item) => { //挂载 writable，readable,value 属性，是为了触发对这三个属性的监听
					item.writable = true
					item.readable = true
					if (this.isObjectValue(item)) {
						item.value = null
					} else {
						item.value = ''
					}
					let input = JSON.parse(JSON.stringify(item))
					this.formData.push(input)
				})
				if (this.isStartStatus(this.status)) {
					// 读取启动表单配置
					let data = await formService.getStartFormData({ processDefinitionId: this.procDefId })
					this.setData(data, 'start')
				} else {
					// 读取任务表单配置
					let data = await formService.getTaskFormData({ taskId: this.taskId })
					this.setData(data, 'audit')
				}
			}
		}
		// 读取按钮配置
		if (this.isStartStatus(this.status)) {
			this.buttons = [{ code: '_flow_start', name: this.status === 'startAndClose' ? '提交' : '启动', isHide: '0' }]
		} else if (this.status === 'reapplyFlag') {
			this.buttons = [{ code: '_flow_reapply', name: '重新提交', isHide: '0' }]
		} else if (this.procDefKey && this.taskDefKey) {
			// 读取按钮
			taskDefExtensionService.queryByDefIdAndTaskId({
				processDefId: this.procDefKey,
				taskDefId: this.taskDefKey
			}).then((data) => {
				this.buttons = data.flowButtonList
			})
		}
		// 读取历史任务列表
		if (this.procInsId) {
			taskService.historicTaskList(this.procInsId).then((data) => {
				this.historicTaskList = data.reverse()
			})
		}

	},
	components: {
		userSelect,
		userSelectDialog,
		TestActivitiLeaveForm,
		RegistrationAddForm,
		CollectForm,
		PurchaseForm,
		PsiPurchaseForm,
		PsiWareHouseUpdateForm,
		PsiLossForm,
		PsiCollectForm,
		DishOrderApproval,
		HolidayForm,
		DepartRegistrationAddForm,
		HandoverAddForm,
		ReimbursementForm,
		InvoiceFormTask,
		EnrollmentRegistrationAddForm,
		TaskBackNodes,
		PreviewForm,
		MeetingRoomForm
	},
	data() {
		return {
			testFlag: false,
			days: '',
			flow: null,
			tabIndex: 0,
			form: null,
			formType: '',
			formUrl: '',
			taskSelectedTab: 'frist',
			historicTaskList: [],
			procDefId: '',
			procInsId: '',
			formReadOnly: false,
			procDefKey: '',
			taskId: '',
			formData: [],
			taskDefKey: '',
			status: '',
			title: '',
			businessId: '',
			buttons: [],
			isCC: false,
			isAssign: false,
			colors: ['#3c9cff', '#f56c6c', '#5ac725', '#f9ae3d', '#89c152',
				'#c38cc1', '#448aca', '#73d1f1', '#ffb34b', '#f18080',
				'#88a867', '#bfbf39', '#94d554', '#f19ec2', '#afaae4',
				'#86cefa', '#98d1ee', '#72dcdc', '#9acdcb', '#77b1cc', '#80a7dc'
			],
			auditForm: {
				message: '',
				type: '',
				status: '',
				userIds: null,
				assignee: null
			},
			rules: {
				'title': [
					{
						required: true,
						message: '流程标题',
						trigger: ['blur', 'change']
					}
				],
				'messsage': [
					{
						required: true,
						message: '审批内容',
						trigger: ['blur', 'change']
					}
				]
			}
		}
	},
	methods: {
		isStartStatus(status) {
			return status === 'start' || status === 'startAndClose'
		},
		tabSelect(index) {
			this.tabIndex = index
		},
		// 为任务表单赋值
		setData(taskFormData, status) {
			this.formData.forEach((input) => {
				let item = taskFormData.filter((item) => {
					if (input.model === item.id) {
						return true
					} else {
						return false
					}
				})[0]
				if (item) {
					if (status === 'start') {
						this.isFixParam(input)
						if (this.isObjectValue(input)) {
							if (input.options.defaultValue && typeof input.options.defaultValue === 'string') {
								input.value = JSON.parse(input.options.defaultValue)
							} else {
								input.value = input.options.defaultValue
							}
						} else {

							input.value = input.options.defaultValue || ''
						}
					} else {
						if (this.isObjectValue(input)) {
							if (item.value && typeof item.value === 'string') {
								input.value = JSON.parse(item.value)
							} else {
								input.value = item.value
							}
						} else {
							input.value = item.value
						}
					}

					input.readable = item.readable
					input.writable = item.writable
				} else {
					input.readable = false
				}
			})
		},
		// 默认参数赋值替换 ${user.name}...
		isFixParam(input) {
			if (/^[$][{].*[}]$/.test(input.options.defaultValue)) {
				let params = input.options.defaultValue.substring(2, input.options.defaultValue.length - 1)
				if (params === "new Date()") {
					input.options.defaultValue = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
				} else {
					let value = { user: this.$store.state.user.userInfo }
					params.split('.').forEach((param) => {
						value = value?.[param]
					})
					input.options.defaultValue = value
				}
			}
		},
		// 判断数据类型是否是非String类型
		isObjectValue(input) {
			if (input.type === 'checkbox' ||
				input.type === 'slider' ||
				input.type === 'switch' ||
				input.type === 'rate' ||
				input.type === 'fileupload' ||
				input.type === 'imgupload' ||
				input.type === 'select' && input.options.multiple) {
				return true
			}
			return false
		},
		// 抄送
		cc(procInsId) {
			if (this.isCC && this.auditForm.userIds) {
				flowCopyService.save({
					userIds: this.auditForm.userIds,
					procDefId: this.procDefId,
					procInsId: procInsId,
					procDefName: '',
					procInsName: this.title,
					taskName: ''
				})
			}
		},
		// 暂存草稿
		save() {

		},
		// 启动流程
		start(vars) {
			if (this.formType === '2') { // 外置表单启动
				const submitForm = this.status === 'startAndClose' && this.$refs.form.startForm
					? this.$refs.form.startForm
					: this.$refs.form.saveForm
				submitForm.call(this.$refs.form, (businessTable, businessId, inputForm) => {
					let assignee = this.auditForm.assignee
					if (inputForm) {
						if (inputForm.days) {
							this.days = inputForm.days
						}

						if (inputForm.assignee) {
							assignee = inputForm.assignee
						}
					}

					taskService.start({
						procDefKey: this.procDefKey,
						businessTable: businessTable,
						businessId: businessId,
						...vars,
						title: this.title,
						assignee: assignee,
						days: this.days
					}).then((data) => {
						uni.showToast({ title: "启动成功", icon: "success" });
						uni.navigateTo({
							url: '/pages/index/index'
						})
						this.cc(data)
					})
				})
			} else { //动态表单启动
				this.$refs.form.submitStartFormData({
					processDefinitionId: this.procDefId,
					...vars,
					title: this.title,
					assignee: this.auditForm.assignee
				}, (data) => {
					uni.showToast({ title: "启动成功", icon: "success" });
					uni.navigateTo({
						url: '/pages/index/index'
					})
					this.cc(data)
				})
			}
		},
		// 同意
		// 同意
		agree(vars) {
			vars = { ...vars, agree: true }
			if (this.formType === '2') {
				this.commit(vars)
			}
		},
		// 重新申请
		reapply(vars) {
			console.log('进入了重新申请')
			vars = { ...vars, agree: true }
			if (this.formType === '2') { // 外置表单
				let param = {
					num: this.$route.query.num,
					taskId: this.taskId,
					taskDefKey: this.taskDefKey,
					procInsId: this.procInsId,
					procDefId: this.procDefId,
					vars: vars,
					comment: this.auditForm,
					assignee: this.auditForm.assignee,
					cope: {
						userIds: this.auditForm.userIds,
						procDefId: this.procDefId,
						procInsId: '',
						procDefName: '',
						procInsName: this.title,
						taskName: ''
					}
				}
				this.$refs.form.reapplyForm((businessTable, businessId, inputForm, recordType) => {
					vars = { ...vars, ...inputForm, recordType }

					let assignee = this.auditForm.assignee
					if (inputForm) {
						if (inputForm.procDefId) {
							param.procDefId = inputForm.procDefId
						}
						if (inputForm.days) {
							this.days = inputForm.days
						}

						if (inputForm.assignee) {
							assignee = inputForm.assignee
						}
					}


					console.log('recordType', recordType)
					this.recordType = recordType
					console.log('this.recordType', this.recordType)
					taskService.audit({
						taskId: this.taskId,
						taskDefKey: this.taskDefKey,
						procInsId: this.procInsId,
						procDefId: this.procDefId,
						vars: vars,
						comment: this.auditForm,
						assignee: assignee,
						recordType: this.recordType,
						days: this.days,
					}).then((data) => {
						uni.showToast({ title: "审批成功", icon: "success" });
						uni.navigateTo({
							url: '/pages/workbench/task/TodoList'
						})
						this.cc(data)
					})
				}, param)
			}
		},
		// 驳回
		reject(vars) {
			uni.showModal({
				title: '提示',
				content: '确定驳回流程吗？',
				success: (res) => {
					if (res.confirm) {
						vars = { ...vars, agree: false }
						uni.showLoading()
						this.$refs.form.updateStatusById('reject', (assignee) => {
							// taskService.backNodes(this.taskId).then((data) => {
							// 	let backNodes = data
							// 	if (backNodes.length > 0) {
							// 		let backTaskDefKey = backNodes[backNodes.length - 1].taskDefKey
							// 		this.back(backTaskDefKey)
							// 	}
							// })
							taskService.audit({
								taskId: this.taskId,
								taskDefKey: this.taskDefKey,
								procInsId: this.procInsId,
								procDefId: this.procDefId,
								vars: vars,
								comment: this.auditForm,
								assignee: this.auditForm.assignee
							}).then((data) => {
								uni.showToast({ title: "审批成功", icon: "success" });
								uni.navigateTo({
									url: '/pages/workbench/task/TodoList'
								})
							})
						})
					} else if (res.cancel) {
						uni.hideLoading()
					}
				}
			});
		},
		// 驳回到任意节点
		turnBack() {
			this.$refs.taskBackNodes.init(this.taskId)
		},
		// 回退到任意节点
		back(backTaskDefKey) {
			taskService.back({
				taskId: this.taskId,
				backTaskDefKey: backTaskDefKey,
				...this.auditForm
			}).then((data) => {
				uni.showToast({ title: "驳回成功", icon: "success" });
				uni.navigateTo({
					url: '/pages/workbench/task/TodoList'
				})
				this.cc(data)
			})
		},
		// 加签
		addMultiInstance() {
			// this.$refs.addSignTaskUserSelectDialog.showModal()
		},
		selectUsersToAddSignTask(users) {
			let userIds = users.map((user) => {
				return user.id
			}).join(',')
			taskService.addSignTask({ taskId: this.taskId, userIds: JSON.stringify(userIds), message: '', flag: false }).then((data) => {
				uni.showToast({ title: data, icon: "success" });
			})
		},
		// 减签
		delMultiInstance() {

		},
		// 转办
		transfer() {
			this.$refs.transferUserSelectDialog.showModal()
		},
		selectUsersToTransferTask(userId) {
			alert(userId)
			if (!userId) {
				uni.showToast({ title: '没有选择任何用户!', icon: "none" });
				return
			}
			taskService.transfer(this.taskId, userId).then((data) => {
				uni.showToast({ title: data, icon: "success" });
				uni.navigateTo({
					url: '/pages/workbench/task/TodoList'
				})
			})
		},
		// 委托
		delegate() {
			this.$refs.delegateUserSelectDialog.showModal()
		},
		selectUsersToDelateTask(userId) {
			if (!userId) {
				uni.showToast({ title: '没有选择任何用户!', icon: "none" });
				return
			}
			taskService.delegate(this.taskId, userId).then((data) => {
				uni.showToast({ title: data, icon: "success" });
				uni.navigateTo({
					url: '/pages/workbench/task/TodoList'
				})
			})
		},
		// 终止
		stop() {
			// uni.showLoading()
			uni.showModal({
				title: '提示',
				content: '确定终止流程吗？',
				success: (res) => {

					// 将数据状态更改为暂存状态
					this.$refs.form.updateStatusById('hold', () => {
						if (res.confirm) {
							processService.stop(this.procInsId, this.auditForm.message).then((data) => {
								uni.showToast({ title: data, icon: "success" });
								uni.navigateTo({
									url: '/pages/workbench/task/TodoList'
								})
							})
						} else if (res.cancel) {
							uni.hideLoading()
						}
					})
				}
			});
		},
		// 打印
		print() {

		},
		// 关闭
		close() {
			uni.navigateTo({
				url: '/pages/workbench/task/TodoList'
			})
		},
		// 自定义按钮提交
		commit(vars) {
			//定义表单规则
			var rule = [
				// {name:"message", checkType : "notnull", checkRule:"",  errorMsg:"审批意见不能为空!"}
			];
			//进行表单检查
			var formData = this.auditForm;
			var checkRes = graceChecker.check(formData, rule);
			if (!checkRes) {
				uni.showToast({ title: graceChecker.error, icon: "none" });
				return;
			}
			if (this.formType === '2') { //外置表单审批
				this.$refs.form.agreeForm((businessTable, businessId, inputForm) => {
					if (inputForm) {
						if (inputForm.days) {
							this.days = inputForm.days
						}
					}

					taskService.audit({
						taskId: this.taskId,
						taskDefKey: this.taskDefKey,
						procInsId: this.procInsId,
						procDefId: this.procDefId,
						vars: vars,
						comment: this.auditForm,
						assignee: this.auditForm.assignee,
						days: this.days,
					}).then((data) => {
						uni.showToast({ title: "审批成功", icon: "success" });
						uni.navigateTo({
							url: '/pages/workbench/task/TodoList'
						})
						this.cc(data)
					})
				})
			} else { // 动态表单启动
				this.$refs.form.submitTaskFormData(vars, this.procInsId, this.taskId, this.auditForm.assignee, this.auditForm, (data) => {
					uni.showToast({ title: "启动成功", icon: "success" });
					uni.navigateTo({
						url: '/pages/index/index'
					})
					//抄送
					this.cc(data)
				})
			}
		},
		submit(currentBtn, buttons) {
			let vars = {} // 存储流程变量

			// 把当前操作对应的自定义按钮(以_flow_开头的是系统按钮，排除在外）的编码，存储为对应的流程变量，值设置为true，其余自定义按钮编码对应的流程变量值为false。
			buttons.forEach((btn) => {
				if (btn.code && !btn.code.startsWith('_flow_')) {
					vars[btn.code] = false
				}
			})
			if (currentBtn.code && !currentBtn.code.startsWith('_flow_')) {
				vars[currentBtn.code] = true
			}
			vars.title = this.title // 标题
			vars.assignee = this.auditForm.assignee // 指定的下一步骤处理人
			this.auditForm.type = currentBtn.code // 提交类型
			this.auditForm.status = currentBtn.name // 按钮文字

			switch (currentBtn.code) {
				case '_flow_start': // 自动流程
					this.start(vars)
					break
				case '_flow_save': // 保存草稿
					this.save()
					break
				case '_flow_agree': // 同意
					this.agree()
					break
				case '_flow_reject': // 驳回
					this.reject()
					break
				case '_flow_back': // 驳回到任意步骤
					this.turnBack()
					break
				case '_flow_add_multi_instance': // 加签
					this.addMultiInstance()
					break
				case '_flow_del_multi_instance': // 减签
					this.delMultiInstance()
					break
				case '_flow_transfer': // 转办
					this.transfer()
					break
				case '_flow_delegate':// 外派
					this.delegate()
					break
				case '_flow_stop':// 终止
					this.stop()
					break
				case '_flow_print':// 打印
					this.print()
					break
				case '_flow_reapply':// 重新申请
					this.reapply()
					break
				case '_flow_close':// 关闭
					this.close()
					break
				default:
					this.commit(vars) // 自定义按钮提交
			}
		}
	}
}
</script>
