<template>
	<div class="page">
		<el-form :inline="true" class="query-form" ref="searchForm" :model="searchForm"
				 @keyup.enter.native="refreshList()" @submit.native.prevent>
			<!-- 搜索框-->
			<el-form-item label="归档名称" prop="name">
				<el-input v-model="searchForm.name" placeholder="请输入归档名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="状态" prop="status">
				<el-select v-model="searchForm.status" placeholder="请选择" style="width:100%;">
					<el-option
						v-for="item in $dictUtils.getDictList('filed_type')"
						:key="item.value"
						:label="item.label"
						:value="item.value">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item v-if="showHideItem" prop="createDates" label="创建时间：">
				<el-date-picker
					placement="bottom-start"
					v-model="searchForm.createDates"
					type="datetimerange"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期">
				</el-date-picker>
			</el-form-item>
			<el-form-item v-if="showHideItem" label="创建人" prop="createById">
				<UserSelect2 :limit='1' :modelValue="searchForm.createById"
							 @update:modelValue='(value, label) => {searchForm.createById = value}'></UserSelect2>
			</el-form-item>
			<el-form-item>
				<el-button type="default" @click="showHide" :icon="showHideIcon">{{showHideName}}</el-button>
				<el-button type="primary" @click="refreshList()" icon="el-icon-search">查询</el-button>
				<el-button @click="resetSearch()" icon="el-icon-refresh-right">重置</el-button>
			</el-form-item>
		</el-form>

		<div class="jp-table top" style="">
			<vxe-toolbar :refresh="{query: refreshList}" custom>
				<template #buttons>
					<el-button v-if="hasPermission('fillingbatch:add')" type="primary" icon="el-icon-plus"
							   @click="add()">新建
					</el-button>
					<!--          <el-button v-if="hasPermission('program:configuration:type:del')" type="danger"  icon="el-icon-delete" @click="del()" :disabled="$refs.typeTable && $refs.typeTable.getCheckboxRecords().length === 0" plain>删除</el-button>-->
				</template>
			</vxe-toolbar>
			<div style="height: calc(100% - 50px)">
				<vxe-table
					border="inner"
					auto-resize
					resizable
					height="auto"
					:loading="loading"
					ref="batchTable"
					show-header-overflow
					show-overflow
					highlight-hover-row
					:menu-config="{}"
					:sort-config="{remote:true}"
					:data="dataList"
					:tree-config="{transform: true, rowField: 'id', parentField: 'parentId', accordion: true}"
					:checkbox-config="{}">
					<vxe-column  type="seq" width="60" title="序号"></vxe-column>
					<vxe-column title="归档批次号/报告号" field="no" align="center" tree-node>
						<template #default="scope">
							<el-link  type="primary" :underline="false" v-if="hasPermission('cwProjectRecords:view')" @click="view(scope.row)">{{scope.row.no}}</el-link>
						</template>
					</vxe-column>
					<vxe-column title="批次名称/项目名称" field="name" align="center"></vxe-column>
					<vxe-column title="创建人" field="createName" align="center"></vxe-column>
					<vxe-column title="创建时间" field="createTime" align="center"></vxe-column>
					<vxe-column title="状态" field="status" align="center">
						<template #default="scope">
							<el-button :disabled="scope.row.level !=='1'" @click="detail(scope.row)"
									   :type="$dictUtils.getDictLabel('filed_type_status', scope.row.status, '-')"
									   effect="dark" size="small">{{$dictUtils.getDictLabel("filed_type",
								scope.row.status, '未归档')}}
							</el-button>
						</template>
					</vxe-column>

					<vxe-column title="操作" width="230px" fixed="right" align="center">
						<template #default="scope">
							<el-button
								v-if="hasPermission('fillingbatch:edit') && (scope.row.createById === $store.state.user.id)&&(scope.row.status==='0'||scope.row.status==='1'||scope.row.status==='3') && (scope.row.level === '1')"
								text type="primary" @click="edit(scope.row)">修改
							</el-button>
							<el-button
								v-if="hasPermission('fillingbatch:del') && (scope.row.status === '1' || scope.row.status === '3')  && scope.row.createById === $store.state.user.id && (scope.row.level === '1')"
								type="text" size="primary" @click="del(scope.row.id)">删除
							</el-button>
							<el-button
								v-if="hasPermission('fillingbatch:edit') && scope.row.status === '2' && scope.row.createById === $store.state.user.id && (scope.row.level === '1')"
								text type="primary" size="primary" @click="reback(scope.row)">撤回
							</el-button>
							<!--              审核-->
							<el-button
								v-if="scope.row.status === '2' && checkIsAudit(scope.row) && (scope.row.level === '1')"
								text type="primary" size="primary" @click="examine(scope.row)">审核
							</el-button>
							<!--              被驳回后当前申请人重新调整-->
							<el-button
								v-if="hasPermission('fillingbatch:edit')&&scope.row.createById === $store.state.user.id&&scope.row.status === '4' && (scope.row.level === '1')"
								text type="primary" size="primary" @click="adjust(scope.row)">驳回调整
							</el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
		</div>
		<FillingbatchDia ref="fillingbatchDia" @refreshList="refreshList"></FillingbatchDia>
		<ProjectRecordsForm2 ref="projectRecordsForm2" @refreshList="refreshList"></ProjectRecordsForm2>

	</div>
</template>

<script>
	import fillingbatchService from '@/api/cw/fillingbatch/FillingbatchService'
	import UserSelect2 from '@/components/userSelect'
	import taskService from "@/api/flowable/taskService";
	import processService from "@/api/flowable/processService";
	import pick from 'lodash.pick'
	import FillingbatchDia from "./FillingbatchDia";
	import ProjectRecordsForm2 from '../projectRecords/ProjectRecordsForm2'

	export default {
		data() {
			return {
				showHideItem: false,
				showHideIcon: 'el-icon-arrow-down',
				showHideName: '展示',
				searchForm: {
					name: '',
					status: '',
					createDates: [],
					createById: ''
				},
				dataList: [],
				tablePage: {
					total: 0,
					currentPage: 1,
					pageSize: 10,
					orders: []
				},
				loading: false,
				processDefinitionId: '',
				procDefKey: '',
			}
		},

		created() {

		},
		components: {
			UserSelect2,
			FillingbatchDia,
			ProjectRecordsForm2
		},
		mounted() {
			this.refreshList()
		},
		activated() {
			this.refreshList()
		},
		methods: {
			showHide() {
				if (this.showHideItem === false) {
					this.showHideItem = true
					this.showHideIcon = 'el-icon-arrow-up'
					this.showHideName = '隐藏'
				} else {
					this.showHideItem = false
					this.showHideIcon = 'el-icon-arrow-down'
					this.showHideName = '展示'
				}
			},
			// 新增
			add() {
				// 读取流程表单
				let tabTitle = `发起流程【批量归档】`
				let processTitle = `${this.$store.state.user.name} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [批量归档]`
				taskService.getTaskDef({
					procDefId: this.processDefinitionId,
					status: 'startAndHold'
				}).then((data) => {
					this.$router.push({
						path: '/flowable/task/TaskForm',
						query: {
							...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
							procDefId: this.processDefinitionId,
							procDefKey: this.procDefKey,
							status: 'startAndHold',
							title: tabTitle,
							formType: data.formType,
							formUrl: data.formUrl,
							formTitle: processTitle,
							businessId: 'false',
							isShow: false,
							routePath: '/cw/fillingbatch/FillingbatchList'
						}
					})
				})
			},
			// 修改
			edit(row) {
				// 暂存修改
				let status = ''
				if (row.status === '1') {
					status = 'startAndHold'
				}
				// 撤回或者驳回修改
				if (row.status === '3') {
					status = 'startAndClose'
				} else if (row.status === '4') {
					status = 'reapplyFlag'
				}
				// 读取流程表单
				let tabTitle = `发起流程【批量归档】`
				let processTitle = `${this.$store.state.user.name} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [批量归档]`
				taskService.getTaskDef({
					procDefId: this.processDefinitionId,
					businessId: row.id,
					businessTable: 'cw_fillingbatch_info',
					status: status
				}).then((data) => {
					this.$router.push({
						path: '/flowable/task/TaskForm',
						query: {
							...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
							procDefId: this.processDefinitionId,
							procDefKey: this.procDefKey,
							status: status,
							title: tabTitle,
							formType: data.formType,
							formUrl: data.formUrl,
							formTitle: processTitle,
							businessTable: 'cw_fillingbatch_info',
							businessId: row.id,
							isShow: false,
							routePath: '/cw/fillingbatch/FillingbatchList'
						}
					})
				})
			},
			// 查看
			view(row) {
				if (row.level === '1'){
					this.$refs.fillingbatchDia.init('view', row.id)
				}else {
					this.$refs.projectRecordsForm2.init('view', row.id)
				}

			},
			// 获取数据列表
			refreshList() {
				this.loading = true
				fillingbatchService.list({
					'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
					console.log('data1',this.dataList)
					this.tablePage.total = data.total
					this.loading = false
				})
				processService.getByName('批量归档').then((data) => {
					if (!this.commonJS.isEmpty(data.id)) {
						this.processDefinitionId = data.id
						this.procDefKey = data.key
					}
				})
			},
			// 撤回
			reback(row) {
				this.$confirm(`确定撤回流程吗?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					processService.revokeProcIns(row.procInsId).then((data) => {
						let param = {status: '3', id: row.id}
						fillingbatchService.updateStatusById(param)
						this.$message.success('回退成功')
						this.refreshList()
					})
				})
			},
			// 流程详情
			detail(row) {
				taskService.getTaskDef({
					procInsId: row.procInsId,
					procDefId: this.processDefinitionId
				}).then((data) => {
					this.$router.push({
						path: '/flowable/task/TaskFormDetail',
						query: {
							...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
							isShow: 'false',
							readOnly: true,
							title: '流程详情',
							formTitle: '流程详情',
							businessId: row.id,
							status: 'reback'
						}
					})
				})
			},
			// 驳回后调整
			adjust(row) {
				console.log('row', row)
				fillingbatchService.queryById(row.id).then((data) => {
					console.log('data', data)
					if (data.status !== '4') { // status的值不等于“驳回”，就弹出提示
						this.$message.error('数据已发生改变或不存在，请刷新数据')
						this.refreshList()
					} else {
						this.todo(row)
					}
				})
			},
			// 审核
			examine(row) {
				fillingbatchService.queryById(row.id).then((data) => {
					if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
						this.$message.error('数据已发生改变或不存在，请刷新数据')
						this.refreshList()
					} else {
						this.todo(row)
					}
				})
			},
			// 审核或重新调整跳转
			todo(row) {
				console.log('row.taskId', row.taskId)
				let cUser = false
				taskService.getTaskDefInfo({
					taskId: row.taskId
				}).then((data) => {
					this.$router.push({
						path: '/flowable/task/TaskForm',
						query: {
							...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title', 'businessId'),
							isShow: false,
							formReadOnly: true,
							formTitle: `${data.taskName}`,
							cUser: cUser,
							title: `审批【${data.taskName || ''}】`,
							routePath: '/cw/fillingbatch/FillingbatchList'   // 数据处理后需要跳转的页面路径
						}
					})
				})
			},
			// 删除
			del(id) {
				let ids = id || this.$refs.batchTable.getCheckboxRecords().map(item => {
					return item.id
				}).join(',')
				this.$confirm(`确定删除所选项吗?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.loading = true
					fillingbatchService.remove(ids).then((data) => {
						this.$message.success(data)
						this.refreshList()
						this.loading = false
					})
				})
			},
			resetSearch() {
				this.$refs.searchForm.resetFields()
				this.refreshList()
			},
			// 查询当前登录人是否是数据的审核人
			checkIsAudit(row) {
				let loginUserId = this.$store.state.user.id  // 获取当前登录用户id
				if (this.commonJS.isNotEmpty(row.auditUserIds)) {
					for (const userId of row.auditUserIds) {
						if (userId === loginUserId) {  // 当数据的审核人中包含当前登录人id时，返回true
							return true
						}
					}
				}
				return false
			},
		}
	}
</script>
