<template>
  <div class="page">
    <el-form :inline="true" class="query-form m-b-10" v-if="searchVisible" 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 label="项目名称" prop="projectName">
        <el-input v-model="searchForm.projectName" placeholder="请输入项目名称" clearable></el-input>
      </el-form-item>
      <el-form-item v-if="showHideItem" label="项目经理1" prop="projectMasterName">
        <UserSelect :limit='1' :modelValue="searchForm.projectMasterName" @update:modelValue='(value, label) => {searchForm.projectMasterName = value}'></UserSelect>
      </el-form-item>
      <el-form-item v-if="showHideItem" label="项目经理2" prop="projectMaster2Name">
        <UserSelect :limit='1' :modelValue="searchForm.projectMaster2Name" @update:modelValue='(value, label) => {searchForm.projectMaster2Name = value}'></UserSelect>
      </el-form-item>
<!--      <el-form-item label="创建人" prop="createBy">-->
<!--        <el-input v-model="searchForm.createBy" placeholder="请输入创建人" clearable></el-input>-->
<!--      </el-form-item>-->
      <el-form-item v-if="showHideItem" label="创建人" prop="createBy">
        <SelectUserTree
          ref="companyTree"
          :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"
          :url="`/system-server/sys/user/treeUserDataAllOffice?type=2`"
          :value="searchForm.createBy"
          :clearable="true"
          :accordion="true"
		  size="default"
          @getValue="(value) => {searchForm.createBy=value}"/>
      </el-form-item>
      <el-form-item v-if="showHideItem" label="创建时间" prop="contractDates">
        <el-date-picker
          placement="bottom-start"
          value-format="YYYY-MM-DD h:m:s"
          v-model="searchForm.contractDates"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="作废归档状态" prop="applyFileType">
        <el-select v-model="searchForm.applyFileType" placeholder="请选择报告作废归档状态" style="width:100%;" clearable>
          <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>
        <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}" ref="toolbarRef" export custom>
<!--        <template #buttons>-->
<!--          <el-button v-if="hasPermission('cw_work_client:info:add')" type="primary" icon="el-icon-plus" @click="start()">新建</el-button>-->
<!--        </template>-->
		  <template #tools>
			  <vxe-button
				  text
				  type="primary"
				  :title="searchVisible ? '收起检索' : '展开检索'"
				  icon="vxe-icon-search"
				  class="tool-btn"
				  @click="searchVisible = !searchVisible"
			  ></vxe-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="documentNo">
            <template #default="scope">
              <el-link  type="primary" :underline="false" v-if="hasPermission('cwProjectReport:list')" @click="view(scope.row.id)">{{scope.row.documentNo}}</el-link>
              <el-link  type="primary" :underline="false" v-else-if="hasPermission('cwProjectReport:list')"  @click="view(scope.row.id,)">{{scope.row.documentNo}}</el-link>
              <span v-else>{{scope.row.documentNo}}</span>
            </template>
          </vxe-column>
          <vxe-column min-width="160" align="center" title="项目编号" field="projectNumber"></vxe-column>
          <vxe-column min-width="160" align="center" title="项目名称" field="projectName"></vxe-column>
          <vxe-column min-width="160" align="center" title="报告文号" field="reportNo">
            <template #default="scope">
              <el-link  type="primary" :underline="false" v-if="hasPermission('cwProjectReport:list')&&commonJS.isNotEmpty(scope.row.reportId)" @click="viewReport(scope.row.reportId)">{{scope.row.reportNo}}</el-link>
              <el-link  type="primary" :underline="false" v-else-if="hasPermission('cwProjectReport:list')&&commonJS.isNotEmpty(scope.row.reportId)"  @click="viewReport(scope.row.reportId)">{{scope.row.reportNo}}</el-link>
              <span v-else>{{scope.row.reportNo}}</span>
            </template>
          </vxe-column>
          <vxe-column min-width="160" align="center" title="报告所属部门" field="departmentName"></vxe-column>
			<vxe-column min-width="230" align="center" title="案卷号" field="number"></vxe-column>
          <vxe-column min-width="160" align="center" title="项目经理1" field="projectMasterName"></vxe-column>
          <vxe-column min-width="160" align="center" title="项目经理2" field="projectMaster2Name"></vxe-column>
          <vxe-column min-width="160" align="center" title="报告主办人" field="reportSponsor"></vxe-column>
          <vxe-column min-width="160" align="center" title="创建人" field="userName"></vxe-column>
          <vxe-column min-width="160" align="center" title="创建时间" field="createTime"></vxe-column>
<!--          <vxe-column  min-width="150px"align="center" fixed="right" title="状态" field="status" >-->
<!--            <template #default="scope">-->
<!--              <el-button  text type="primary" @click="detail(scope.row)" effect="dark" -->
<!--                          :type="$dictUtils.getDictLabel('cw_status_flag', scope.row.status, '-')">-->
<!--                {{$dictUtils.getDictLabel("cw_status", scope.row.status, '-')}}-->
<!--              </el-button>-->
<!--            </template>-->
<!--          </vxe-column>-->
          <vxe-column  min-width="150px" align="center" fixed="right" title="作废归档状态" field="applyFileType" >
            <template #default="scope">
              <el-button  @click="detail(scope.row)" effect="dark"
                          :type="$dictUtils.getDictLabel('filed_type_status', scope.row.applyFileType, '')">
                {{$dictUtils.getDictLabel("filed_type", scope.row.applyFileType, '-')}}
              </el-button>
<!--              <template slot-scope="scope">-->
<!--                <el-button  text type="primary" @click="detailPaperFiled(scope.row)" :type="$dictUtils.getDictLabel('filed_type_status', scope.row.applyFileType, '-')" effect="dark" >{{$dictUtils.getDictLabel("filed_type", scope.row.applyFileType, '未归档')}} </el-button>-->
<!--              </template>-->
            </template>
          </vxe-column>

          <vxe-column title="操作" width="150px" fixed="right" align="center">
            <template  #default="scope">
              <el-button v-if="hasPermission('cw:cwProjectReport:filed')&&scope.row.createById === $store.state.user.id&&scope.row.status==='5'&& (scope.row.applyFileType === undefined || scope.row.applyFileType === '0')" text type="primary" @click="archived(scope.row)">归档</el-button>
              <!--归档暂存修改-->
              <el-button v-if="hasPermission('cw:cwProjectReport:filed') && scope.row.status === '5'  && scope.row.createId === $store.state.user.id && scope.row.applyFileType === '1'" text type="primary" @click="archived(scope.row)">修改</el-button>
              <el-button v-else-if="hasPermission('cw:cwProjectReport:edit')&&isAdmin&&(scope.row.applyFileType==='1'||scope.row.applyFileType==='3'||scope.row.applyFileType==='5')" text type="primary"  @click="edit(scope.row.id)">修改</el-button>
              <!--纸质归档撤回驳回修改-->
              <el-button v-if="hasPermission('cw:cwProjectReport:filed') && scope.row.status === '5'  && scope.row.createId === $store.state.user.id && (scope.row.applyFileType === '3' )" text type="primary" @click="paperFiledAndClose(scope.row.id)">修改</el-button>
              <!--纸质归档撤回-->
              <el-button v-if="hasPermission('cw:cwProjectReport:back') && scope.row.status === '5' && scope.row.createId === $store.state.user.id && scope.row.applyFileType === '2'" text type="primary"  @click="rebackPaperFiled(scope.row)">撤回</el-button>
<!--              <el-button v-else-if="hasPermission('cw:cwProjectReport:del')&&isAdmin&&(scope.row.applyFileType==='1'||scope.row.applyFileType==='3'||scope.row.applyFileType==='4'||scope.row.applyFileType==='5')" text type="primary"   @click="del(scope.row.id)">删除</el-button>-->
<!--              审核-->
              <el-button v-if="scope.row.applyFileType==='2' && checkIsAudit(scope.row)" text type="primary"  @click="examine(scope.row)">审核</el-button>
<!--              被驳回后当前申请人重新调整-->
              <el-button v-if="scope.row.createId === $store.state.user.id&&scope.row.applyFileType === '4'" text type="primary" @click="adjust(scope.row)">驳回调整</el-button>
            </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>
    <ReportManagementForm ref="reportManagementForm"></ReportManagementForm>
    <ReportCancellApplyForm ref="reportCancellApplyForm"></ReportCancellApplyForm>
  </div>
</template>

<script>
  // import ProjectReportService from '@/api/cw/reportManagement/ProjectReportService'
  // import ReportCancellApplyService from '@/api/cw/reportCancellApply/ReportCancellApplyService'
  import officeService from '@/api/sys/officeService'
  import ReportCancellApplyArchivedService from '@/api/cw/reportCancellApplyArchived/ReportCancellApplyArchivedService'
  import taskService from '@/api/flowable/taskService'
  import processService from '@/api/flowable/processService'
  import ReportManagementForm from '../reportManagement/ReportManagementForm'
  import ReportCancellApplyForm from './ReportCancellApplyArchivedForm'
  // eslint-disable-next-line no-unused-vars
  import pick from 'lodash.pick'
  import userService from '@/api/sys/userService'
  import SelectUserTree from '@/views/utils/treeUserSelect'
  import UserSelect from '@/views/cw/workClientInfo/clientUserSelect'

  export default {
    data () {
      return {
		searchVisible: true,
        showHideItem: false,
        showHideIcon: 'el-icon-arrow-down',
        showHideName: '展示',
        searchForm: {
          projectNumber: '',
		  applyFileType: '',
          projectName: '',
          projectMasterId: '',
          projectMaster2Id: '',
          createBy: '',
          contractDates: [],
          projectMasterName: '', // 项目经理1
          projectMaster2Name: '' // 项目经理2
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        tableKey: '',
        loading: false,
        processDefinitionAuditId: '',
        procDefAuditKey: '',
		  processDefinitionAuditIdSZ: '',
		  procDefAuditKeySZ: '',
        isAdmin: false,
        create: ''
      }
    },
    // projectReportService: null,
    reportCancellApplyService: null,
    reportCancellApplyArchivedService: null,
    created () {
      // this.projectReportService = new ProjectReportService()
      // this.reportCancellApplyService = new ReportCancellApplyService()
      this.reportCancellApplyArchivedService = new ReportCancellApplyArchivedService()
    },
    components: {
      ReportManagementForm,
      ReportCancellApplyForm,
      SelectUserTree,
      UserSelect
    },
    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: {
      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 () {
        // this.$refs.reportManagementForm.init('add', '')
        this.$refs.reportCancellApplyForm.init('add', '')
      },
      // 修改
      edit (id) {
        id = id || this.$refs.clientTable.getCheckboxRecords().map(item => {
          return item.id
        })[0]
        // this.$refs.reportManagementForm.init('edit', id)
        this.$refs.reportCancellApplyForm.init('edit', id)
      },
      // 查看
      view (id) {
        // this.$refs.reportManagementForm.init('view', id)
        this.$refs.reportCancellApplyForm.init('view', id)
      },
      // 根据报告id查看报告详情
      viewReport (id) {
        this.$refs.reportManagementForm.init('view', id)
        // this.$refs.reportCancellApplyForm.init('view', id)
      },
      // 查询当前用户是否是管理员用户
      checkIsAdmin () {
        userService.is().then((data) => {
          this.isAdmin = data
        })
      },
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.reportCancellApplyArchivedService.findList({
          '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.tableKey = Math.random()
          this.loading = false
        })
        // this.reportCancellApplyService.findList({
        //   '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.tableKey = Math.random()
        //   this.loading = false
        // })
        this.checkIsAdmin()
        processService.getByName('会计-报告作废归档').then((data) => {
          if (!this.commonJS.isEmpty(data.id)) {
            this.processDefinitionAuditId = data.id
            this.procDefAuditKey = data.key
          }
        })
		  processService.getByName('会计-报告作废归档-苏州').then((data) => {
			  if (!this.commonJS.isEmpty(data.id)) {
				  this.processDefinitionAuditIdSZ = data.id
				  this.procDefAuditKeySZ = 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()
      },
      // 删除
      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
          this.reportCancellApplyArchivedService.delete(ids).then((data) => {
            this.$message.success(data)
            this.refreshList()
            this.loading = false
          })
          // this.reportCancellApplyService.delete(ids).then((data) => {
          //   this.$message.success(data)
          //   this.refreshList()
          //   this.loading = false
          // })
        })
      },
      resetSearch () {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      },
      /* 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.procDefAuditKey,
                status: 'startAndHold',
                title: tabTitle,
                formType: data.formType,
                formUrl: data.formUrl,
                formTitle: processTitle,
                businessId: 'false',
                isShow: false,
                routePath: '/cw/reportCancellApply/ReportCancellApplyList'
              }
            })
          })
      }, */
      // 发起客户登记
      /* push (row) {
        // 读取流程表单
        let title = `发起流程【报告作废归档】`
        let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了[报告作废归档]`
        let status = 'startAndHold'
        if (row.status === '3' || row.status === '4') {
          status = 'startAndClose'
        }
        taskService.getTaskDef({ procDefId: this.processDefinitionAuditId,
          businessId: row.id,
          businessTable: 'cw_project_report_cancell_apply'}).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.procDefAuditKey,
                title: title,
                formType: data.formType,
                formUrl: data.formUrl,
                formTitle: processTitle,
                businessTable: 'cw_project_report_cancell_apply',
                businessId: row.id,
                isShow: 'false',
                status: status,
                routePath: '/cw/reportCancellApply/ReportCancellApplyList'
              }
            })
          })
      }, */
      // 查看流程结果
      detail (row) {
        console.log('row', row)
        if (row.applyFileType !== '0' && row.applyFileType !== '1') {
			officeService.queryById(this.$store.state.user.office.id).then((byId) => {
				// 判断当前人的所属部门是否为苏州分部，根据部门的机构编码(szfb)来判断是不是苏州分部
				if (byId.code === 'szfb') {
					this.procDefId = this.processDefinitionAuditIdSZ
				} else {
					this.procDefId = this.processDefinitionAuditId
				}
			})
          this.reportCancellApplyArchivedService.findByContractInfoId(row.id).then((data) => {
            if (!this.commonJS.isEmpty(data.id)) {
              console.log('data', data)
              taskService.getTaskDef({
                procInsId: data.cwProcInsId,
                procDefId: this.procDefId
              }).then((data) => {
                this.$router.push({
                  path: '/flowable/task/TaskFormDetail',
                  query: {
                    ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
                    readOnly: true,
                    title: '会计-报告作废归档流程详情',
                    formTitle: '会计-报告作废归档流程详情',
                    businessId: row.id
                  }
                })
              })
            }
          })
          // eslint-disable-next-line eqeqeq
          // taskService.getTaskDef({
          //   procInsId: row.cwProcInsId,
          //   procDefId: row.cwProDefId
          // }).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'
          //     }
          //   })
          // })
        }
      },
      // 撤回报告流程
      /* reback (row) {
        this.$confirm(`确定要撤回该申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await this.reportCancellApplyService.queryById(row.id).then((data) => {
            if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
              this.$message.error('数据已发生改变或不存在，请刷新数据')
              this.refreshList()
            } else {
              processService.revokeProcIns(row.procInsId).then((data) => {
                let form = {status: '3', id: row.id}
                this.reportCancellApplyService.updateStatusById(form)
                this.$message.success(data)
                this.refreshList()
              })
            }
          })
          // await this.projectReportService.queryById(row.id).then((data) => {
          //   if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
          //     this.$message.error('数据已发生改变或不存在，请刷新数据')
          //     this.refreshList()
          //   } else {
          //     processService.revokeProcIns(row.procInsId).then((data) => {
          //       let form = {status: '3', id: row.id}
          //       this.projectReportService.updateStatusById(form)
          //       this.$message.success(data)
          //       this.refreshList()
          //     })
          //   }
          // })
        })
      } */
      // 报告作废归档
      archived (row) {
        processService.getByName('会计-报告作废归档').then((data) => {
          if (!this.commonJS.isEmpty(data.id)) {
            // console.log('data', data)
            // 读取流程表单
            let tabTitle = ' ' + row.reportNo + ' - ' + row.projectName
            let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 ` + tabTitle + '[会计-报告作废归档]'
            taskService.getTaskDef({ procDefId: data.id,
              businessId: row.id,
              businessTable: 'cw_project_report_cancell_apply_archived',
              status: 'startAndHoldFiled'}).then((reture) => {
                this.$router.push({
                  path: '/flowable/task/TaskForm',
                  query: {
                    ...pick(reture, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
                    procDefId: data.id,
                    procDefKey: data.key,
                    status: 'startAndHoldFiled',
                    title: tabTitle,
                    formType: reture.formType,
                    formUrl: reture.formUrl,
                    formTitle: processTitle,
                    businessTable: 'cw_project_report_cancell_apply_archived',
                    businessId: row.id,
                    isShow: false,
                    routePath: '/cw/reportCancellApplyArchived/ReportCancellApplyArchivedList'
                  }
                })
              })
          }
        })
      },
      // 归档撤回驳回修改
      paperFiledAndClose (id) {
        processService.getByName('会计-报告作废归档').then((data) => {
          if (!this.commonJS.isEmpty(data.id)) {
            // console.log('data', data)
            // 读取流程表单
            let tabTitle = `发起流程【会计-报告作废归档】`
            let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [会计-报告作废归档]`
            taskService.getTaskDef({ procDefId: data.id,
              businessId: id,
              businessTable: 'cw_project_report_cancell_apply_archived',
              status: 'startAndCloseFiled'}).then((reture) => {
                this.$router.push({
                  path: '/flowable/task/TaskForm',
                  query: {
                    ...pick(reture, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
                    procDefId: data.id,
                    procDefKey: data.key,
                    status: 'startAndCloseFiled',
                    title: tabTitle,
                    formType: reture.formType,
                    formUrl: reture.formUrl,
                    formTitle: processTitle,
                    businessTable: 'cw_project_report_cancell_apply_archived',
                    businessId: id,
                    isShow: false,
                    routePath: '/cw/reportCancellApplyArchived/ReportCancellApplyArchivedList'
                  }
                })
              })
          }
        })
      },
      // 归档撤回
      rebackPaperFiled (row) {
        // console.log('row.taskFiledProcInsId' + row.taskFiledProcInsId)
        this.$confirm(`确定撤回流程吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          processService.revokeProcIns(row.cwProcInsId).then((data) => {
            // let form = {filedType: '3', id: row.id}
            this.updateStatusById(row, 'rebackFiledPaper')
            this.$message.success(data)
            this.refreshList()
          })
        })
      },
      updateStatusById (row, type) {
        if (type === 'rebackFiledPaper') {
          row.applyFileType = '3'
          this.reportCancellApplyArchivedService.updateStatusById(row)
        }
      },
      // 归档详情
      // detailPaperFiled (row) {
      //   // console.log('row.id', row.id)
      //   // eslint-disable-next-line eqeqeq
      //   if (!this.commonJS.isEmpty(row.applyFileType) && row.applyFileType != '1') {
      //     this.reportCancellApplyService.findByContractInfoId(row.id).then((data) => {
      //       if (!this.commonJS.isEmpty(data.id)) {
      //         // console.log('data', data)
      //         taskService.getTaskDef({
      //           procInsId: data.cwProcInsId,
      //           procDefId: data.cwProDefId
      //         }).then((data) => {
      //           this.$router.push({
      //             path: '/flowable/task/TaskFormDetail',
      //             query: {
      //               readOnly: true,
      //               title: '纸质归档流程详情',
      //               formTitle: '纸质归档流程详情',
      //               businessId: row.id,
      //               ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title')}
      //           })
      //         })
      //       }
      //     })
      //   }
      // }
      // 驳回后调整
      adjust (row) {
        this.reportCancellApplyArchivedService.queryById(row.id).then((data) => {
          if (data.applyFileType !== '4') { // status的值不等于“驳回”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todo(row)
          }
        })
      },
      // 审核
      examine (row) {
        this.reportCancellApplyArchivedService.queryById(row.id).then((data) => {
          if (data.applyFileType !== '2') { // status的值不等于“审核中”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todo(row)
          }
        })
      },
      // 审核或重新调整跳转
      todo (row) {
        let cUser = false
        taskService.getTaskDefInfo({
          taskId: row.archivedTaskId
        }).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/reportCancellApplyArchived/ReportCancellApplyArchivedList'   // 数据处理后需要跳转的页面路径
            }
          })
        })
      },
      // 查询当前登录人是否是数据的审核人
      checkIsAudit (row) {
        let loginUserId = this.$store.state.user.id  // 获取当前登录用户id
        if (this.commonJS.isNotEmpty(row.auditUserIdsArchived)) {
          for (const userId of row.auditUserIdsArchived) {
            if (userId === loginUserId) {  // 当数据的审核人中包含当前登录人id时，返回true
              return true
            }
          }
        }
        return false
      },
      // 自定义服务端导出
      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 this.reportCancellApplyArchivedService.exportExcel(params).then((res) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(res, options.filename)
        }).catch(function (err) {
          if (err.response) {
            // console.log(err.response)
          }
        })
      }
    }
  }
</script>
