<template>
	<div class="page">
		<el-form :inline="true" class="query-form m-b-10" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
			<!-- 搜索框-->
			<el-form-item label="项目编号" prop="projectNumber">
				<el-input v-model="searchForm.projectNumber" placeholder="请输入项目编号" clearable></el-input>
			</el-form-item>

			<el-form-item>
				<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}" ref="toolbarRef" export custom>
				<template #buttons>
					<el-button v-if="hasPermission('reimburseRegister:add')" type="primary" icon="el-icon-plus" @click="start()">新建</el-button>
				</template>
			</vxe-toolbar>
			<div style="height: calc(100% - 90px)">
				<vxe-table
					border="inner"
					auto-resize
					resizable
					height="auto"
					:loading="loading"
					ref="clientTable"
					show-header-overflow
					show-overflow
					highlight-hover-row
					:print-config="{}"
					:export-config="{
                    remote: true,
                    filename: `实习-报销${moment(new Date()).format('YYYY-MM-DD')}`,
                    sheetName: '实习-报销信息',
                    exportMethod: exportMethod,
                    types: ['xlsx'],
                    modes: ['current', 'selected', 'all']
                  }"
					:menu-config="{}"
					@sort-change="sortChangeHandle"
					:sort-config="{remote:true}"
					:data="dataList"
					:checkbox-config="{}">
					<vxe-column type="seq" width="60" title="序号"></vxe-column>
					<vxe-column min-width="160" align="center" title="报销编号" field="no"></vxe-column>
					<vxe-column min-width="160" align="center" title="经办人" field="operator"></vxe-column>
					<vxe-column min-width="160" align="center" title="报销日期" field="reimDate"></vxe-column>
					<vxe-column min-width="160" align="center" title="报销金额(元)" field="totalNum"></vxe-column>
					<vxe-column min-width="100" title="状态" fixed="right" align="center" field="type">
						<template #default="scope">
							<el-button @click="detail(scope.row)" :type="$dictUtils.getDictLabel('status_info', scope.row.type, '')" effect="dark" >{{$dictUtils.getDictLabel("status", scope.row.type, '未开始')}} </el-button>
						</template>
					</vxe-column>
					<vxe-column title="操作" width="200px" fixed="right" align="center">
						<template  #default="scope">
							<div v-if="isAdmin">
								<el-button v-if="
                      scope.row.type === '5' || scope.row.type === '4' || scope.row.type === '3'" text type="primary" @click="editForm(scope.row.id)">修改</el-button>
								<el-button v-if="
                      scope.row.type === '5' || scope.row.type === '4' || scope.row.type === '3'" text type="primary" @click="del(scope.row.id)">删除</el-button>
							</div>
							<div v-else>
								<el-button v-if="hasPermission('reimburseRegister:edit') && scope.row.createById === $store.state.user.id && (scope.row.type === '1' || scope.row.type === '3' )" text type="primary"   @click="edit(scope.row)">修改</el-button>
								<el-button v-if="hasPermission('reimburseRegister:edit') && scope.row.createById === $store.state.user.id && (scope.row.type === '2')" text type="primary"  @click="reback(scope.row)">撤回</el-button>
								<el-button v-if="hasPermission('reimburseRegister:del') && scope.row.createById === $store.state.user.id && (scope.row.type === '1')" text type="primary"  @click="del(scope.row.id)">删除</el-button>
								<!--              审核-->
								<el-button v-if="scope.row.type==='2'&& checkIsAudit(scope.row)" text type="primary"  @click="examine(scope.row)">审核</el-button>
								<!--              被驳回后当前申请人重新调整-->
								<el-button v-if="scope.row.createById === $store.state.user.id&&scope.row.type === '4'" text type="primary"  @click="adjust(scope.row)">驳回调整</el-button>
							</div>
						</template>
					</vxe-column>
				</vxe-table>
				<vxe-pager
					background
					: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>
		</div>
		<ReimburseSubmitAccountEditForm ref="reimburseSubmitAccountEditForm" @refreshList="refreshList"></ReimburseSubmitAccountEditForm>
	</div>
</template>

<script>
	import reimburseSubmitAccountService from '@/api/human/register/ReimburseSubmitAccountService'
	import processService from '@/api/flowable/ProcessService'
	import userService from '@/api/sys/UserService'
	import taskService from '@/api/flowable/TaskService'
	import pick from "lodash.pick";
	import ReimburseSubmitAccountEditForm from "./ReimburseSubmitAccountEditForm";
	export default {
		data () {
			return {
				num: 0,
				searchForm: {
					projectNumber: '',
				},
				dataList: [],
				tablePage: {
					total: 0,
					currentPage: 1,
					pageSize: 10,
					orders: []
				},
				loading: false,
				processDefinitionAuditId: '',
				procDefAuditKey: '',
				isAdmin: false,
				create: '',
				haveProjectIds: ''
			}
		},
		created () {
		},
		components: {
			ReimburseSubmitAccountEditForm
		},
		computed: {
			userName () {
				return this.$store.state.user.name
			},
			user () {
				this.createName = this.$store.state.user.name
				return this.$store.state.user
			}
		},
		mounted () {
			this.$nextTick(() => {
				//将表格和工具栏进行关联
				const $table = this.$refs.clientTable;
				const $toolbar = this.$refs.toolbarRef;
				$table.connect($toolbar);
			})
			this.refreshList()
		},
		activated () {
			this.refreshList()
		},
		methods: {
			// 新增
			add () {
			},
			// 修改
			editForm (id) {
				id = id || this.$refs.clientTable.getCheckboxRecords().map(item => {
					return item.id
				})[0]
				this.$refs.reimburseSubmitAccountEditForm.init('edit', id)
			},
			// 查询当前用户是否是管理员用户
			checkIsAdmin () {
				userService.is().then((data) => {
					this.isAdmin = data
				})
			},
			// 获取数据列表
			refreshList () {
				this.loading = true
				reimburseSubmitAccountService.list({
					'current': this.tablePage.currentPage,
					'size': this.tablePage.pageSize,
					'orders': this.tablePage.orders,
					...this.searchForm
				}).then((data) => {
					this.dataList = data.records
					this.tablePage.total = data.total
					this.loading = false
				})
				this.checkIsAdmin()
				processService.getByName('实习-报销').then((data) => {
					if (!this.commonJS.isEmpty(data.id)) {
						this.processDefinitionAuditId = data.id
						this.procDefAuditKey = data.key
					}
				})
			},
			// 当前页
			currentChangeHandle ({ currentPage, pageSize }) {
				this.tablePage.currentPage = currentPage
				this.tablePage.pageSize = pageSize
				this.refreshList()
			},
			// 排序
			sortChangeHandle (column) {
				this.tablePage.orders = []
				if (column.order != null) {
					this.tablePage.orders.push({column: this.$utils.toLine(column.property), asc: column.order === 'asc'})
				}
				this.refreshList()
			},
			resetSearch () {
				this.$refs.searchForm.resetFields()
				this.refreshList()
			},
			// 修改
			edit (row) {
				// 暂存修改
				let status = ''
				if (row.type === '1') {
					status = 'startAndHold'
				}
				// 撤回或者驳回修改
				if (row.type === '3') {
					status = 'startAndClose'
				} else if (row.status === '4') {
					status = 'reapplyFlag'
				}
				// 读取流程表单
				let tabTitle = `发起流程【实习-报销】`
				let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [实习-报销]`
				taskService.getTaskDef({ procDefId: this.processDefinitionAuditId,
					businessId: row.id,
					businessTable: 'human_resources_practice_reimburse_submit_account',
					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.processDefinitionAuditId,
							procDefKey: this.procDefKey,
							status: status,
							title: tabTitle,
							formType: data.formType,
							formUrl: data.formUrl,
							formTitle: processTitle,
							businessTable: 'human_resources_practice_reimburse_submit_account',
							businessId: row.id,
							isShow: false,
							routePath: '/human/reimburseRegister/ReimburseSubmitAccountList'
						}
					})
				})
			},
			start () {
				// 读取流程表单
				let tabTitle = `发起流程【实习-报销】`
				let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [实习-报销]`
				taskService.getTaskDef({ procDefId: this.processDefinitionAuditId,
					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.processDefinitionAuditId,
							procDefKey: this.procDefKey,
							status: 'startAndHold',
							title: tabTitle,
							formType: data.formType,
							formUrl: data.formUrl,
							formTitle: processTitle,
							businessId: 'false',
							isShow: false,
							routePath: '/human/reimburseRegister/ReimburseSubmitAccountList'
						}
					})
				})
			},
			// 撤回
			reback (row) {
				this.$confirm(`确定撤回流程吗?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					processService.revokeProcIns(row.procInsId).then((data) => {
						let param = {type: '3', id: row.id}
						reimburseSubmitAccountService.updateStatusById(param)
						this.$message.success('回退成功')
						this.refreshList()
					})
				})
			},
			// 审核
			examine (row) {
				reimburseSubmitAccountService.findById(row.id).then((data) => {
					if (data.type !== '2') { // status的值不等于“审核中”，就弹出提示
						this.$message.error('数据已发生改变或不存在，请刷新数据')
						this.refreshList()
					} else {
						this.todo(row)
					}
				})
			},
			// 查看流程结果
			detail (row) {
				if (!this.commonJS.isEmpty(row.type) && row.type !== '1') {
					// eslint-disable-next-line eqeqeq
					taskService.getTaskDef({
						procInsId: row.procInsId,
						procDefId: this.processDefinitionAuditId
					}).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'
							}
						})
					})
				}
			},
			// 审核或重新调整跳转
			todo (row) {
				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: '/human/reimburseRegister/ReimburseSubmitAccountList'   // 数据处理后需要跳转的页面路径
						}
					})
				})
			},
			// 驳回后调整
			adjust (row) {
				console.log('row', row)
				reimburseSubmitAccountService.findById(row.id).then((data) => {
					console.log('data', data)
					if (data.type !== '4') { // status的值不等于“驳回”，就弹出提示
						this.$message.error('数据已发生改变或不存在，请刷新数据')
						this.refreshList()
					} else {
						this.todo(row)
					}
				})
			},
			// 自定义服务端导出
			exportMethod ({ options }) {
				// 传给服务端的参数
				const params = {
					'current': this.tablePage.currentPage,
					'size': this.tablePage.pageSize,
					'orders': this.tablePage.orders,
					...this.searchForm,
					filename: options.filename,
					sheetName: options.sheetName,
					isHeader: options.isHeader,
					original: options.original,
					mode: options.mode,
					selectIds: options.mode === 'selected' ? options.map(item => item.id) : [],
					exportFields: options.columns.map(column => column.property)
				}
				return reimburseSubmitAccountService.exportExcel(params).then((res) => {
					// 将二进制流文件写入excel表，以下为重要步骤
					this.$utils.downloadExcel(res, options.filename)
				}).catch(function (err) {
					if (err.response) {
						// console.log(err.response)
					}
				})
			},
			// 删除
			del (id) {
				let ids = id || this.$refs.clientTable.getCheckboxRecords().map(item => {
					return item.id
				}).join(',')
				this.$confirm(`确定删除所选项吗?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.loading = true
					reimburseSubmitAccountService.remove(ids).then((data) => {
						this.$message.success(data)
						this.refreshList()
						this.loading = false
					})
				})
			},
			// 查询当前登录人是否是数据的审核人
			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>
