<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="project">
        <el-input size="small" v-model="searchForm.project" placeholder="请输入报销项目" clearable>
          <el-button icon="el-icon-search" slot="append" @click="openProgramPageForm"></el-button>
        </el-input>
      </el-form-item>-->
			<el-form-item label="报销编号" prop="no">
				<el-input v-model="searchForm.no" placeholder="请输入报销编号" clearable>
				</el-input>
			</el-form-item>
			<el-form-item label="报销时间" prop="dates">
				<el-date-picker style="" placement="bottom-start" format="YYYY-MM-DD HH:mm:ss"
					value-format="YYYY-MM-DD HH:mm:ss" v-model="searchForm.dates" type="datetimerange"
					range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="经办人" prop="handled">
				<!--			<UserSelect :limit='1' :modelValue="searchForm.handled" @update:modelValue='(value, label) => {searchForm.handled = value}'></UserSelect>-->
				<el-input v-model="searchForm.handled" placeholder="请选择经办人">
					<template #suffix>
						<el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary"
							slot="append" icon="el-icon-search" @click="openUserDia1">
						</el-button>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="报销人" prop="reimBy">
				<!--			<UserSelect :limit='1' :modelValue="searchForm.reimBy" @update:modelValue='(value, label) => {searchForm.reimBy = value}'></UserSelect>-->
				<el-input v-model="searchForm.reimBy" placeholder="请选择报销人">
					<template #suffix>
						<el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary"
							slot="append" icon="el-icon-search" @click="openUserDia2">
						</el-button>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item v-if="showHideItem" label="报销项" prop="reimbursementType">
				<el-select v-model="searchForm.reimbursementType" placeholder="请选择" style="width:100%;" clearable>
					<el-option v-for="item in $dictUtils.getDictList('reimbursement_type')" :key="item.value"
						:label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item v-if="showHideItem" label="报销状态" prop="type">
				<el-select v-model="searchForm.type" placeholder="请选择" style="width:100%;" clearable>
					<el-option v-for="item in $dictUtils.getDictList('status')" :key="item.value" :label="item.label"
						:value="item.value">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item v-if="showHideItem" label="报销部门" prop="department">
				<SelectTree ref="officeTree" :props="{
					value: 'id',             // ID字段名
					label: 'name',         // 显示名称
					children: 'children'    // 子级字段名
				}" :url="`/system-server/sys/office/treeData?type=2`" :value="searchForm.department" :clearable="true"
					size="default" :accordion="true" @getValue="(value, label) => { searchForm.department = label }" />
			</el-form-item>
			<!--<el-form-item v-if="showHideItem" label="报销类型" prop="sourceType">
        <el-select size="small" v-model="searchForm.sourceType" placeholder="请选择报销类型">
          <el-option
            v-for="item in $dictUtils.getDictList('cw_reimbursement_source_type')"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>-->
			<el-form-item v-if="showHideItem" label="报销类别" prop="remiType">
				<SelectTree ref="areaTree" :props="{
					value: 'id',             // ID字段名
					label: 'name',         // 显示名称
					children: 'children'    // 子级字段名
				}" url="/public-modules-server/reimbursementApproval/type/treeData1?type=last" :value="searchForm.remiType"
					:clearable="true" size="default" :accordion="true"
					@getValue="(value, label) => { searchForm.remiType = label }" />
			</el-form-item>
			<el-form-item v-if="showHideItem" label="报销金额" prop="amounts">
				<InputNumber :disabled="false" :precision="num" :value="searchForm.amounts"
					@changefrom="(val) => { searchForm.amounts[0] = val }"
					@changeto="(val) => { searchForm.amounts[1] = val }">
				</InputNumber>
			</el-form-item>
			<el-form-item v-if="showHideItem" label="付款状态" prop="paymentStatus">
				<el-select v-model="searchForm.paymentStatus" placeholder="请选择付款状态" clearable>
					<el-option v-for="item in $dictUtils.getDictList('payment_status')" :key="item.value"
						:label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-form-item>
			<!--<el-form-item v-if="showHideItem" label="报告号" prop="reportNumber">
        <el-input size="small" v-model="searchForm.reportNumber" placeholder="请输入报告号" clearable></el-input>
      </el-form-item>-->
			<el-form-item v-if="showHideItem" label="发票号" prop="financeNumber">
				<el-input style="width: 150px" v-model="searchForm.financeNumber" placeholder="请输入发票号" clearable>
				</el-input>
			</el-form-item>
			<el-form-item>
				<el-button @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" style="">
			<vxe-toolbar ref="toolbarRef" :refresh="{ query: refreshList }" export custom>
				<template #buttons>
					<el-button v-if="hasPermission('zsReimbursement:info:add')" type="primary" icon="el-icon-plus"
						@click="add()">新建</el-button>
					<el-button v-if="hasPermission('zsReimbursement:info:del')" type="danger" icon="el-icon-delete"
						@click="del()" :disabled="$refs.infoTable && $refs.infoTable.getCheckboxRecords().length === 0"
						plain>删除</el-button>
					<el-button type="warning" icon="el-icon-download" @click="exportInvoiceReimbursementFile()"
						plain>数电发票报销</el-button>
				</template>
			</vxe-toolbar>
			<div class="jp-table-body">
				<vxe-table border="inner" auto-resize resizable height="auto" :loading="loading" size="small"
					ref="infoTable" show-header-overflow show-overflow highlight-hover-row
					:tooltip-config="tooltipConfig" :menu-config="{}" :sort-config="{ remote: true }" :export-config="{
						remote: true,
						filename: `中审报销数据${moment(new Date()).format('YYYY-MM-DD')}`,
						sheetName: `中审报销数据${moment(new Date()).format('YYYY-MM-DD')}`,
						exportMethod: exportMethod,
						types: ['xlsx'],
						modes: ['current', 'selected', 'all']
					}" :data="dataList" :checkbox-config="{}">
					<vxe-column type="seq" width="60" title="序号"></vxe-column>
					<vxe-column type="checkbox" width="40"></vxe-column>
					<vxe-column width="130" title="报销编号" field="no" align="center">
						<template #default="scope">
							<el-link type="primary" :underline="false" v-if="hasPermission('zsReimbursement:info:view')"
								@click="view(scope.row)">{{ scope.row.no }}</el-link>
							<el-link type="primary" :underline="false"
								v-else-if="hasPermission('zsReimbursement:info:view')" @click="view(scope.row)">{{
									scope.row.no }}</el-link>
							<span v-else>{{ scope.row.no }}</span>
						</template>
					</vxe-column>
					<vxe-column v-if="hasPermission('zs:user:payment')" width="130" title="报销项"
						field="reimbursementType" align="center">
						<template #default="scope">
							{{ $dictUtils.getDictLabel('reimbursement_type', scope.row.reimbursementType, '') }}
						</template>
					</vxe-column>
					<vxe-column width="130" title="报销类型" field="sourceType" align="center">
						<template #default="scope">
							{{ $dictUtils.getDictLabel('zs_cw_reimbursement_source_type', scope.row.sourceType, '') }}
						</template>
					</vxe-column>
					<vxe-column width="130" title="报销类别" field="typeName" align="center"></vxe-column>
					<vxe-column min-width="180" title="报销项目" field="projectName" align="center">
						<template #default="scope">
							<el-link type="primary" :underline="false"
								v-if="hasPermission('cw:reimbursement:info:view') && scope.row.projectId != undefined"
								@click="viewProject(scope.row.projectId)">{{ scope.row.sourceType === '2' ? '' :
									scope.row.projectName }}</el-link>
							<el-link type="primary" :underline="false"
								v-else-if="hasPermission('cw:reimbursement:info:view') && scope.row.projectId != undefined"
								@click="viewProject(scope.row.projectId)">{{ scope.row.sourceType === '2' ? '' :
									scope.row.projectName }}</el-link>
							<span v-else>{{ scope.row.sourceType === '2' ? '' : scope.row.projectName }}</span>
						</template>
					</vxe-column>
					<vxe-column min-width="180" title="报销合同" field="projectName" align="center">
						<template #default="scope">
							<el-link type="primary" :underline="false"
								v-if="hasPermission('cw:reimbursement:info:view') && scope.row.projectId != undefined"
								@click="viewContract(scope.row.projectId)">{{ scope.row.sourceType === '2' ?
									scope.row.projectName : '' }}</el-link>
							<span v-else>{{ scope.row.sourceType === '2' ? scope.row.projectName : '' }}</span>
						</template>
					</vxe-column>
					<vxe-column min-width="180" title="报告号" field="reportNumber" align="center"></vxe-column>
					<!--<vxe-column width="180" title="报销合同" field="projectName"align="center">
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false" v-if="hasPermission('zsReimbursement:info:view') && scope.row.projectId != undefined" @click="viewContract(scope.row.projectId)">{{scope.row.sourceType === '2' ? scope.row.projectName : ''}}</el-link>
              <span v-else>{{scope.row.sourceType === '2' ? scope.row.projectName : ''}}</span>
            </template>
          </vxe-column>-->
					<!--<vxe-column width="180" title="报告号" field="reportNumber"align="center"></vxe-column>-->
					<vxe-column width="100" title="经办人" field="userName" align="center"></vxe-column>
					<vxe-column width="100" title="报销人" field="name" align="center"></vxe-column>
					<vxe-column width="100" title="报销部门" field="deptName" align="center"></vxe-column>
					<vxe-column width="100" title="报销日期" field="approvalTime" align="center"></vxe-column>
					<vxe-column width="120" title="报销金额(元)" field="number" fixed="right" align="center"></vxe-column>
					<vxe-column 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 v-if="hasPermission('zs:user:payment')" min-width="100" title="付款状态" fixed="right"
						align="center" field="paymentStatus">
						<template #default="scope">
							<el-button
								:type="$dictUtils.getDictLabel('payment_status_info', scope.row.paymentStatus, '')"
								effect="dark">{{ $dictUtils.getDictLabel("payment_status", scope.row.paymentStatus,
									'未审批') }} </el-button>
						</template>
					</vxe-column>
					<vxe-column width="100" title="文件补充状态" fixed="right" align="center" field="fileStatus">
						<template #default="scope">
							<el-button @click="detailFile(scope.row)"
								:type="$dictUtils.getDictLabel('status_info', scope.row.fileStatus, '')"
								effect="dark">{{ $dictUtils.getDictLabel("status", scope.row.fileStatus, '未开始') }}
							</el-button>
						</template>
					</vxe-column>
					<vxe-column title="操作" min-width="200px" fixed="right" align="center">
						<template #default="scope">
							<!--				管理员修改-->
							<el-button v-if="(isAdmin)" text type="primary" @click="editForm(scope.row)">修改</el-button>

							<el-button
								v-if="hasPermission('zsReimbursement:info:edit') && scope.row.createId === $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('zsReimbursement:info:edit') && scope.row.createId === $store.state.user.id && (scope.row.type === '4')"
								text type="primary" @click="todo(scope.row)">驳回调整</el-button>
							<el-button
								v-if="hasPermission('zsReimbursement:info:edit') && scope.row.createId === $store.state.user.id && (scope.row.type === '2')"
								text type="primary" @click="reback(scope.row)">撤回</el-button>
							<el-button
								v-if="hasPermission('zsReimbursement:info:del') && scope.row.createId === $store.state.user.id && (scope.row.type === '1')"
								text type="primary" @click="del(scope.row.id)">删除</el-button>
							<el-button v-if="checkIsAudit(scope.row)" text type="primary"
								@click="todo(scope.row)">审核</el-button>
							<!--								付款-->
							<el-button v-if="hasPermission('zs:user:payment') && scope.row.paymentStatus !== '1'" text
								type="primary" @click="payment(scope.row)">付款</el-button>
							<el-button v-if="hasPermission('zs:user:payment') && scope.row.paymentStatus === '1'" text
								type="primary" @click="rePayment(scope.row)">撤回付款</el-button>
							<!--								文件补充-->
							<el-button
								v-if="hasPermission('file:supplement') && (scope.row.type === '5' || scope.row.applyFile === true) && (scope.row.fileStatus === '0' || scope.row.fileStatus === '5' || scope.row.fileStatus === '' || scope.row.fileStatus === null || scope.row.fileStatus === undefined)"
								text type="primary" @click="addFile(scope.row)">文件补充</el-button>
							<el-button v-if="hasPermission('file:supplement') && (scope.row.fileStatus === '3')" text
								type="primary" @click="editFile(scope.row)">文件补充</el-button>
							<el-button v-if="hasPermission('file:supplement') && (scope.row.fileStatus === '2')" text
								type="primary" @click="rebackFile(scope.row)">撤回文件补充</el-button>
							<el-button
								v-if="hasPermission('file:supplement') && scope.row.fileStatus === '4' && checkIsAuditFile(scope.row)"
								text type="primary" @click="adjustFile(scope.row)">文件补充驳回调整</el-button>
							<el-button v-if="scope.row.fileStatus === '2' && checkIsAuditFile(scope.row)" text
								type="primary" @click="examineFile(scope.row)">审核</el-button>

						</template>
					</vxe-column>
				</vxe-table>
				<vxe-pager background size="small" :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>

				<!--        <ProgramPageForm ref="programPageForm" @getProgram="getProgram"></ProgramPageForm>-->
				<ProjectChooseForm ref="projectChooseForm" @getProgram="getProgram"></ProjectChooseForm>
				<InfoForm ref="infoForm" @refreshDataList="refreshList"></InfoForm>
				<NewInfoForm ref="newInfoForm" @refreshDataList="refreshList"></NewInfoForm>
				<InfoUpdateForm ref="infoUpdateForm" @refreshDataList="refreshList"></InfoUpdateForm>
				<NewInfoUpdateForm ref="newInfoUpdateForm" @refreshDataList="refreshList"></NewInfoUpdateForm>

				<!--        <ProjectForm ref="projectForm" @refreshDataList="refreshList"></ProjectForm>-->
				<ProjectRecordsForm ref="projectRecordsForm" @refreshDataList="refreshList"></ProjectRecordsForm>
				<ProjectListForm ref="projectListForm"></ProjectListForm>
				<ContractNameForm ref="contractNameForm"></ContractNameForm>
				<user-select1 ref="userSelect1" @doSubmit="selectUser1"></user-select1>
				<user-select2 ref="userSelect2" @doSubmit="selectUser2"></user-select2>
			</div>
		</div>
	</div>
</template>

<script>
import ReimbursementService from '@/api/zs/reimbursement/ReimbursementService'
import InputNumber from '@/views/workContract/InputNumber.vue'
// import SelectUserTree from '@/views/utils/treeUserSelect'
import UserSelect from '@/components/userSelect'
import SelectTree from '@/components/treeSelect/treeSelect.vue'
import ProjectChooseForm from '../projectInfo/ProjectChooseForm'
import ProjectListForm from '@/views/cw/reimbursementApproval/info/ProgramForm'
import InfoForm from './InfoForm'
import NewInfoForm from './NewInfoForm'


import taskService from '@/api/flowable/taskService'
import processService from '@/api/flowable/processService'
import pick from 'lodash.pick'
import ProjectRecordsForm from '@/views/cw/projectRecords/ProjectRecordsForm'
import ContractNameForm from '@/views/cw/workContract/ContractNameForm'
import userService from '@/api/sys/UserService'
import InfoUpdateForm from "./InfoUpdateForm";
import NewInfoUpdateForm from "./NewInfoUpdateForm";

import UserSelect1 from '@/views/utils/UserTreeSelect'
import UserSelect2 from '@/views/utils/UserTreeSelect'
import dayjs from 'dayjs';
export default {
	data() {
		return {
			formUrl: '/zs/reimbursement/info/NewReimbursementForm',
			showHideItem: false,
			showHideIcon: 'el-icon-arrow-down',
			showHideName: '展示',
			num: 0,
			visable: false,
			gridData: [],
			searchForm: {
				project: '',
				dates: [],
				handled: '',
				reimBy: '',
				type: [],
				department: '',
				remiType: '',
				amounts: [],
				reportNumber: '',
				sourceType: '',
				no: '',
				paymentStatus: '',
				financeNumber: ''
			},
			dataList: [],
			tablePage: {
				total: 0,
				currentPage: 1,
				pageSize: 10,
				orders: []
			},
			loading: false,
			isZj: false,
			isDgsbxBmzr: false,
			isZjbry: false,
			isAdmin: false,
			tooltipConfig: {
				showAll: false,
				enterable: true,
				contentMethod: ({ type, column, row, items, _columnIndex }) => {
					const { field } = column
					// 重写默认的提示内容
					if (field === 'paymentStatus') {
						if (row.paymentStatus === '1') {
							return '付款时间:' + row.paymentTime;
						}
					}
					// 其余的单元格使用默认行为
					return null
				}
			}
		}
	},
	// reimbursementService: null,
	reimbursementService: null,
	// taskService: null,
	// processService: null,
	created() {
		// this.reimbursementService = new ReimbursementService()
		this.reimbursementService = new ReimbursementService()
		// this.taskService = new TaskService()
		// this.processService = new ProcessService()
	},
	components: {
		InputNumber,
		// SelectUserTree,
		SelectTree,
		// ProgramPageForm,
		ProjectChooseForm,
		InfoForm,
		NewInfoForm,
		// ProjectForm,
		ProjectRecordsForm,
		ProjectListForm,
		UserSelect,
		ContractNameForm,
		InfoUpdateForm,
		NewInfoUpdateForm,
		UserSelect1,
		UserSelect2,
	},
	mounted() {
		this.$nextTick(() => {
			// 将表格和工具栏进行关联
			const $table = this.$refs.infoTable;
			const $toolbar = this.$refs.toolbarRef;
			$table.connect($toolbar);
		});
		this.refreshList();
	},
	activated() {
		this.refreshList()
	},
	computed: {
		userName() {
			return this.$store.state.user.name
		},
		user() {
			// this.create = JSON.parse(localStorage.getItem('user')).id
			// console.log('createId', this.create)
			// return JSON.parse(localStorage.getItem('user'))
			return this.$store.state.user
		}
	},
	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 = '展示'
			}
		},
		viewContract(id) {
			this.$refs.contractNameForm.init('view', id)
		},
		// 新增
		add() {
			let newStartDate = this.$dictUtils.getDictLabel("new_version_reimbursement_date", '1', '-')
			let today = dayjs().format('YYYY-MM-DD');
			let newVersionFlag = this.validateXG.compareDate(today, newStartDate) == 'same' || this.validateXG.compareDate(today, newStartDate) == 'after'
			// 读取流程表单
			let tabTitle = `发起流程【中审-报销审批】`
			let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [中审-报销审批]`
			console.log(this.processDefinitionId)
			if (this.isZj || this.isDgsbxBmzr) {
				taskService.getTaskDef({
					procDefId: this.processDefinitionIdSzbx,
					status: 'startAndHold'
				}).then((data) => {
					// 根据时间判断formUrl
					if (newVersionFlag) {
						data.formUrl = this.formUrl
					}
					this.$router.push({
						path: '/flowable/task/TaskForm',
						query: {
							...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
							procDefId: this.processDefinitionIdSzbx,
							procDefKey: this.procDefKeySzbx,
							status: 'startAndHold',
							title: tabTitle,
							formType: data.formType,
							formUrl: data.formUrl,
							formTitle: processTitle,
							businessId: 'false',
							isShow: false,
							routePath: '/zs/reimbursement/info/InfoList'
						}
					})
				})
			} else if (this.isZjbry) {
				taskService.getTaskDef({
					procDefId: this.processDefinitionIdZjb,
					status: 'startAndHold'
				}).then((data) => {
					// 根据时间判断formUrl
					if (newVersionFlag) {
						data.formUrl = this.formUrl
					}
					this.$router.push({
						path: '/flowable/task/TaskForm',
						query: {
							...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
							procDefId: this.processDefinitionIdZjb,
							procDefKey: this.procDefKeyZjb,
							status: 'startAndHold',
							title: tabTitle,
							formType: data.formType,
							formUrl: data.formUrl,
							formTitle: processTitle,
							businessId: 'false',
							isShow: false,
							routePath: '/zs/reimbursement/info/InfoList'
						}
					})
				})
			} else {
				taskService.getTaskDef({
					procDefId: this.processDefinitionId,
					status: 'startAndHold'
				}).then((data) => {
					// 根据时间判断formUrl
					if (newVersionFlag) {
						data.formUrl = this.formUrl
					}
					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: '/zs/reimbursement/info/InfoList'
						}
					})
				})
			}

		},
		// 修改
		edit(row) {
			let newStartDate = this.$dictUtils.getDictLabel("new_version_reimbursement_date", '1', '-')
			let newVersionFlag = this.validateXG.compareDate(row.approvalTime, newStartDate) == 'same' || this.validateXG.compareDate(row.approvalTime, newStartDate) == 'after'
			// 读取流程表单
			// 暂存修改
			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')} 发起了 [中审-报销审批]`
			if (this.isZj || this.isDgsbxBmzr) {
				taskService.getTaskDef({
					procDefId: this.processDefinitionIdSzbx,
					businessId: row.id,
					businessTable: 'zs_reimbursement_info',
					status: status
				}).then((data) => {
					if (newVersionFlag) {
						data.formUrl = this.formUrl
					}
					this.$router.push({
						path: '/flowable/task/TaskForm',
						query: {
							...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
							procDefId: this.processDefinitionIdSzbx,
							procDefKey: this.procDefKeySzbx,
							status: status,
							title: tabTitle,
							formType: data.formType,
							formUrl: data.formUrl,
							formTitle: processTitle,
							businessTable: 'zs_reimbursement_info',
							businessId: row.id,
							isShow: false,
							routePath: '/zs/reimbursement/info/InfoList'
						}
					})
				})
			} else if (this.isZjbry) {
				taskService.getTaskDef({
					procDefId: this.processDefinitionIdZjb,
					businessId: row.id,
					businessTable: 'zs_reimbursement_info',
					status: status
				}).then((data) => {
					if (newVersionFlag) {
						data.formUrl = this.formUrl
					}
					this.$router.push({
						path: '/flowable/task/TaskForm',
						query: {
							...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
							procDefId: this.processDefinitionIdZjb,
							procDefKey: this.procDefKeyZjb,
							status: status,
							title: tabTitle,
							formType: data.formType,
							formUrl: data.formUrl,
							formTitle: processTitle,
							businessTable: 'zs_reimbursement_info',
							businessId: row.id,
							isShow: false,
							routePath: '/zs/reimbursement/info/InfoList'
						}
					})
				})
			} else {
				taskService.getTaskDef({
					procDefId: this.processDefinitionId,
					businessId: row.id,
					businessTable: 'zs_reimbursement_info',
					status: status
				}).then((data) => {
					if (newVersionFlag) {
						data.formUrl = this.formUrl
					}
					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: 'zs_reimbursement_info',
							businessId: row.id,
							isShow: false,
							routePath: '/zs/reimbursement/info/InfoList'
						}
					})
				})
			}

		},
		todo(row) {
			let newStartDate = this.$dictUtils.getDictLabel("new_version_reimbursement_date", '1', '-')
			let newVersionFlag = this.validateXG.compareDate(row.approvalTime, newStartDate) == 'same' || this.validateXG.compareDate(row.approvalTime, newStartDate) == 'after'
			let cUser = false
			taskService.getTaskDefInfo({
				taskId: row.taskId
			}).then((data) => {
				if (newVersionFlag) {
					data.formUrl = this.formUrl
				}
				console.log(data)
				this.$router.push({
					path: '/flowable/task/TaskForm',
					query: {
						isShow: false,
						formReadOnly: true,
						formTitle: `${data.title}`,
						routePath: '/zs/reimbursement/info/InfoList',   // 数据处理后需要跳转的页面路径
						cUser: cUser,
						title: `审批【${data.taskName || ''}】`,
						...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title', 'businessId')
					}
				})
			})
		},
		// 撤回
		reback(row) {
			this.$confirm(`确定撤回流程吗?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				processService.revokeProcIns(row.procInsId).then(() => {
					let param = { type: '3', id: row.id }
					this.reimbursementService.updateStatusById(param)
					this.$message.success('回退成功')
					this.refreshList()
				})
			})
		},
		// 查看
		view(row) {
			let newStartDate = this.$dictUtils.getDictLabel("new_version_reimbursement_date", '1', '-')
			let newVersionFlag = this.validateXG.compareDate(row.approvalTime, newStartDate) == 'same' || this.validateXG.compareDate(row.approvalTime, newStartDate) == 'after'
			if (newVersionFlag) {
				this.$refs.newInfoForm.init('view', row.id)
			} else {
				this.$refs.infoForm.init('view', row.id)
			}
		},
		//修改
		editForm(row) {
			let newStartDate = this.$dictUtils.getDictLabel("new_version_reimbursement_date", '1', '-')
			let newVersionFlag = this.validateXG.compareDate(row.approvalTime, newStartDate) == 'same' || this.validateXG.compareDate(row.approvalTime, newStartDate) == 'after'
			if (newVersionFlag) {
				this.$refs.newInfoUpdateForm.init('edit', row.id)
			} else {
				this.$refs.infoUpdateForm.init('edit', row.id)
			}
		},
		// 查看报销项目
		viewProject(id) {
			// this.$refs.projectForm.init('view', id)
			//this.$refs.projectRecordsForm.init('view', id)
			this.$refs.projectListForm.init(id)
		},
		checkIsZj() {
			userService.isZj().then((data) => {
				this.isZj = data
				console.log('this.isZj', this.isZj)
			})
		},
		checkIsZjbry() {
			userService.isZjbry().then((data) => {
				this.isZjbry = data
			})
		},
		// 查询当前用户是否是管理员用户
		checkIsAdmin() {
			userService.is().then((data) => {
				this.isAdmin = data
			})
		},
		//查询当前用户是否是多公司报销(部门主任)
		checkIsDgsbxBmzr() {
			userService.isDgsbxBmzr().then((data) => {
				this.isDgsbxBmzr = data
			})
		},
		// 获取数据列表
		refreshList() {
			this.loading = true
			this.reimbursementService.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.reimbursementService.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.checkIsZj()
			this.checkIsDgsbxBmzr()
			this.checkIsZjbry()
			this.checkIsAdmin()
			processService.getByName('中审-报销审批').then((data) => {
				if (!this.commonJS.isEmpty(data.id)) {
					this.processDefinitionId = data.id
					this.procDefKey = data.key
				}
			})
			processService.getByName('中审-报销审批-电子发票').then((data) => {
				if (!this.commonJS.isEmpty(data.id)) {
					this.processDefinitionIdInvoice = data.id
					this.procDefKeyInvoice = data.key
				}
			})
			processService.getByName('中审-所长报销').then((data) => {
				console.log('data', data)
				if (!this.commonJS.isEmpty(data.id)) {
					this.processDefinitionIdSzbx = data.id
					this.procDefKeySzbx = data.key
				}
			})

			processService.getByName('中审-所长报销-电子发票').then((data) => {
				if (!this.commonJS.isEmpty(data.id)) {
					this.processDefinitionIdSzbxInvoice = data.id
					this.procDefKeySzbxInvoice = data.key
				}
			})
			processService.getByName('中审-总经办报销').then((data) => {
				if (!this.commonJS.isEmpty(data.id)) {
					this.processDefinitionIdZjb = data.id
					this.procDefKeyZjb = data.key
				}
			})
			processService.getByName('中审-报销文件补充').then((data) => {
				console.log('file', data)
				if (!this.commonJS.isEmpty(data.id)) {
					this.processDefinitionIdFile = data.id
					this.procDefKeyFile = data.key
				}
			})
		},
		// 删除
		del(id) {
			let ids = id || this.$refs.infoTable.getCheckboxRecords().map(item => {
				return item.id
			}).join(',')
			this.$confirm(`确定删除所选项吗?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.loading = true
				this.reimbursementService.remove(ids).then((data) => {
					this.$message.success(data)
					this.refreshList()
					this.loading = false
				})
				// this.reimbursementService.remove(ids).then(({data}) => {
				//   this.$message.success(data)
				//   this.refreshList()
				//   this.loading = false
				// })
			})
		},
		resetSearch() {
			this.$refs.searchForm.resetFields()
			this.refreshList()
		},
		// 流程详情
		detail(row) {
			if (!this.commonJS.isEmpty(row.type) && row.type !== '1') {
				if (this.isZj || this.isDgsbxBmzr) {
					if (row.reimbursementType === '1') {
						this.procDefId = this.processDefinitionIdSzbxInvoice
					} else if (row.reimbursementType === '0') {
						{
							this.procDefId = this.processDefinitionIdSzbx
						}
					}
				} else if (this.isZjbry) {
					this.procDefId = this.processDefinitionIdZjb
				} else {
					if (row.reimbursementType === '1') {
						this.procDefId = this.processDefinitionIdInvoice
					} else if (row.reimbursementType === '0') {
						{
							this.procDefId = this.processDefinitionId
						}
					}
				}

				let newStartDate = this.$dictUtils.getDictLabel("new_version_reimbursement_date", '1', '-')
				let newVersionFlag = this.validateXG.compareDate(row.approvalTime, newStartDate) == 'same' || this.validateXG.compareDate(row.approvalTime, newStartDate) == 'after'
				taskService.getTaskDef({
					procInsId: row.procInsId,
					procDefId: this.procDefId
				}).then((data) => {
					if (newVersionFlag) {
						data.formUrl = this.formUrl
					}
					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'
						}
					})
				})
			}
		},
		openProgramPageForm(rowIndex) {
			// 打开单选组件
			// this.$refs.programPageForm.init(null, false)
			this.$refs.projectChooseForm.init(null, false)
		},
		getProgram(rows) {
			// rows[0].name // 项目名称、开票详情
			// rows[0].contractName // 合同名称
			// rows[0].no // 项目编号
			// rows[0].clientName // 客户名称
			// rows[0].client // 客户id
			// rows[0].id // 项目id
			// rows[0].location // 项目所在地
			this.searchForm.project = rows.projectName
		},
		// 下载文档
		exportFile() {
			this.loading = true
			this.reimbursementService.exportFile({
				'itemType': '1',
				...this.searchForm
			}).then((res) => {
				// 将二进制流文件写入excel表，以下为重要步骤
				this.$utils.downloadExcel(res, '中审-报销审批列表信息')
				this.loading = false
			}).catch(function (err) {
				this.loading = false
				if (err.response) {
					console.log(err.response)
				}
			})
			// this.reimbursementService.exportFile({
			//   'itemType': '1',
			//   ...this.searchForm
			// }).then((res) => {
			//   // 将二进制流文件写入excel表，以下为重要步骤
			//   this.$utils.downloadExcel(res.data, '中审-报销审批列表信息')
			//   this.loading = false
			// }).catch(function (err) {
			//   this.loading = false
			//   if (err.response) {
			//     console.log(err.response)
			//   }
			// })
		},

		// 下载文档
		exportInvoiceReimbursementFile() {
			this.loading = true
			this.reimbursementService.exportInvoiceReimbursementFile({
				'itemType': '1',
				...this.searchForm
			}).then((res) => {
				// 将二进制流文件写入excel表，以下为重要步骤
				this.$utils.downloadExcel(res, '中审-报销数电发票报销列表')
				this.loading = false
			}).catch(function (err) {
				this.loading = false
				if (err.response) {
					console.log(err.response)
				}
			})
		},
		// 当前页
		currentChangeHandle({ currentPage, pageSize }) {
			this.tablePage.currentPage = currentPage
			this.tablePage.pageSize = pageSize
			this.refreshList()
		},

		// 自定义服务端导出
		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.data.map(item => item.id) : [],
				exportFields: options.columns.map(column => column.property)
			}
			return this.reimbursementService.exportFile(params).then((res) => {
				// 将二进制流文件写入excel表，以下为重要步骤
				this.$utils.downloadExcel(res, options.filename)
			}).catch(function (err) {
				if (err.response) {
					console.log(err.response)
				}
			})
		},
		// 查询当前登录人是否是数据的审核人
		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
		},
		openUserDia1() {
			this.$refs.userSelect1.init()
		},
		selectUser1(user) {
			console.log(user[0].name)
			this.searchForm.handled = user[0].name
		},
		openUserDia2() {
			this.$refs.userSelect2.init()
		},
		selectUser2(user) {
			console.log(user[0].name)
			this.searchForm.reimBy = user[0].name
		},
		//付款
		payment(row) {
			this.$confirm(`确定付款吗?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				let param = { paymentStatus: '1', id: row.id }
				this.reimbursementService.updatePaymentStatus(param).then((data) => {
					this.$message.success(data)
					this.refreshList()
				})
			})
		},
		//撤回付款
		rePayment(row) {
			this.$confirm(`确定撤回付款吗?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				let param = { paymentStatus: '0', id: row.id }
				this.reimbursementService.updatePaymentStatus(param).then((data) => {
					this.$message.success(data)
					this.refreshList()
				})
			})
		},
		//文件补充
		addFile(row) {
			// 读取流程表单
			let tabTitle = `发起流程【中审-报销文件补充】`
			let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [中审-报销文件补充]`
			taskService.getTaskDef({
				procDefId: this.processDefinitionIdFile,
				status: 'startAndClose'
			}).then((data) => {
				this.$router.push({
					path: '/flowable/task/TaskForm',
					query: {
						...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
						procDefId: this.processDefinitionIdFile,
						procDefKey: this.procDefKeyFile,
						status: 'startAndClose',
						title: tabTitle,
						formType: data.formType,
						formUrl: data.formUrl,
						formTitle: processTitle,
						businessId: row.id,
						isShow: false,
						routePath: '/zs/reimbursement/info/InfoList'
					}
				})
			})
		},
		//查询文件补充审核人
		checkIsAuditFile(row) {
			let loginUserId = this.$store.state.user.id  // 获取当前登录用户id
			if (this.commonJS.isNotEmpty(row.auditFileUserIds)) {
				for (const userId of row.auditFileUserIds) {
					if (userId === loginUserId) {  // 当数据的审核人中包含当前登录人id时，返回true
						return true
					}
				}
			}
			return false
		},
		//文件补充  重新调整
		todoFile(row) {
			let cUser = false
			taskService.getTaskDefInfo({
				taskId: row.taskIdFile
			}).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: '/zs/reimbursement/info/InfoList'   // 数据处理后需要跳转的页面路径
					}
				})
			})
		},
		//文件补充 审核
		examineFile(row) {
			this.reimbursementService.findFileById(row.fileSuppleId).then((data) => {
				if (data.fileStatus !== '2') { // status的值不等于“审核中”，就弹出提示
					this.$message.error('数据已发生改变或不存在，请刷新数据')
					this.refreshList()
				} else {
					this.todoFile(row)
				}
			})
		},
		//文件补充 驳回调整
		adjustFile(row) {
			this.reimbursementService.findFileById(row.fileSuppleId).then((data) => {
				console.log('data', data)
				if (data.fileStatus !== '4') { // status的值不等于“驳回”，就弹出提示
					this.$message.error('数据已发生改变或不存在，请刷新数据')
					this.refreshList()
				} else {
					this.todoFile(row)
				}
			})
		},
		//文件补充流程详情
		detailFile(row) {
			taskService.getTaskDef({
				procInsId: row.procInsIdFile,
				procDefId: this.processDefinitionIdFile
			}).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.fileSuppleId,
						status: 'reback'
					}
				})
			})
		},
		//文件补充撤回
		rebackFile(row) {
			this.$confirm(`确定撤回流程吗?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				processService.revokeProcIns(row.procInsIdFile).then((data) => {
					let param = { fileStatus: '3', fileSuppleId: row.fileSuppleId }
					this.reimbursementService.updateFileStatusById(param)
					this.$message.success('回退成功')
					this.refreshList()
				})
			})
		},
		//文件补充 修改
		editFile(row) {
			status = 'startAndClose'
			let tabTitle = `发起流程【中审-报销文件补充】`
			let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [中审-报销文件补充]`

			taskService.getTaskDef({
				procDefId: this.processDefinitionIdFile,
				businessId: row.fileSuppleId,
				businessTable: 'zs_reimbursement_file_supplement',
				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.processDefinitionIdFile,
						procDefKey: this.procDefKeyFile,
						status: status,
						title: tabTitle,
						formType: data.formType,
						formUrl: data.formUrl,
						formTitle: processTitle,
						businessTable: 'zs_reimbursement_file_supplement',
						businessId: row.fileSuppleId,
						isShow: false,
						routePath: '/zs/reimbursement/info/InfoList'
					}
				})
			})
		},
	}
}
</script>
