<template>
	<div>
		<el-dialog :title="title" :close-on-click-modal="false" dialogDrag width="400px" append-to-body
			align-center="true" height="auto" v-loading="loading" @close="close" @keyup.enter.native="getWorkClient"
			v-model="visibleChoose">
			<el-icon style="color: #E6A23C;size:20px">
				<Warning />
			</el-icon>{{ confirmText }}
			<template #footer>
				<div class="dialog-footer">
					<el-button v-loading="loading" size="primary" @click="todo('1')" v-noMoreClick>同意
					</el-button>
					<!-- <el-button v-loading="loading" type="paimary" @click="todo('0')" v-noMoreClick>驳回
					</el-button> -->
				</div>
			</template>
		</el-dialog>
		<TaskForm ref="taskForm"></TaskForm>
	</div>
</template>

<script>
import taskService from "@/api/flowable/taskService";

export default {
	data() {
		return {
			title: '',
			visibleChoose: false,
			loading: false,
			dataList: [],
			allReimbursements: false,
			batchAuditTimer: null
		}
	},
	beforeUnmount() {
		if (this.batchAuditTimer) {
			clearTimeout(this.batchAuditTimer)
		}
	},
	methods: {
		init(info) {
			this.title = '批量审核'
			this.visibleChoose = true
			this.dataList = info || []
			this.allReimbursements = false
			this.loading = false
		},
		initAll() {
			this.title = '一键处理'
			this.visibleChoose = true
			this.dataList = []
			this.allReimbursements = true
			this.loading = false
		},
		async todo(type) {
			if (!this.allReimbursements && !this.dataList.length) {
				this.$message.warning('请选择需要审核的数据')
				return
			}

			this.loading = true
			try {
				const params = {
					agree: type === '1'
				}
				if (this.allReimbursements) {
					params.allReimbursements = true
				} else {
					params.taskIds = this.dataList.map(item => item.task.id)
				}
				const data = await taskService.batchAudit(params)
				this.$message.success('批量审核已提交，正在处理中')
				this.close()
				if (data && data.jobId) {
					this.pollBatchAudit(data.jobId)
				}
			} finally {
				this.loading = false
			}
		},
		pollBatchAudit(jobId) {
			if (this.batchAuditTimer) {
				clearTimeout(this.batchAuditTimer)
			}
			this.batchAuditTimer = setTimeout(async () => {
				try {
					const progress = await taskService.getBatchAuditJob(jobId)
					if (progress.status !== 'COMPLETED') {
						this.pollBatchAudit(jobId)
						return
					}
					// this.$message({
					// 	type: progress.failed > 0 ? 'warning' : 'success',
					// 	message: `批量审核完成：成功${progress.success}条，失败${progress.failed}条`
					// })
					this.$emit('refreshDataList')
				} catch (e) {
					this.pollBatchAudit(jobId)
				}
			}, 2000)
		},
		close() {
			this.visibleChoose = false
		}
	},
	computed: {
		confirmText() {
			return this.allReimbursements ? '是否处理全部报销审核' : '是否处理被选中的报销审核'
		}
	}
}
</script>
<style scoped>
/deep/ .el-dialog__body {
	padding-top: 0;
}

/deep/ .el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
	margin-bottom: 0px;
}
</style>
