<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="clientName">
              <el-input v-model="searchForm.clientName" placeholder="请输入客户名称" clearable></el-input>
       </el-form-item>

        <el-form-item label="合同名称" prop="name">
          <el-input  v-model="searchForm.name" placeholder="请输入合同名称" clearable></el-input>
        </el-form-item>

        <el-form-item v-if="showHideItem" label="签订日期" prop="contractDates">
          <el-date-picker
            placement="bottom-start"
            v-model="searchForm.contractDates"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item v-if="showHideItem" label="合同状态" prop="status">
          <el-select v-model="searchForm.status" placeholder="请选择" style="width:100%;">
            <el-option
              v-for="item in $dictUtils.getDictList('approval_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="filedType">
          <el-select v-model="searchForm.filedType" 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" label="合同金额" prop="contractAmounts">
          <InputNumber :disabled="false" :precision="num"
					   :value="searchForm.contractAmounts"
					   @changefrom="(val) => {searchForm.contractAmounts[0] = val}"
					   @changeto="(val) => {searchForm.contractAmounts[1] = val}"
		  >
		  </InputNumber>
        </el-form-item>

        <el-form-item v-if="showHideItem" label="创建人" prop="createById">
          <UserSelect :limit='1' :readonly="true" :modelValue="searchForm.createById" @update:modelValue='(value, label) => {searchForm.createById = value}'></UserSelect>
        </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">
        <vxe-toolbar ref="toolbarRef" :refresh="{query: refreshList}" custom>
          <template #buttons>
            <el-button v-if="hasPermission('sys:project:add')" type="primary" icon="el-icon-plus" @click="add()">新建</el-button>
		  </template>
        </vxe-toolbar>
        <div class="jp-table-body">
            <vxe-table
                border="inner"
                auto-resize
                resizable
                height="auto"
                :loading="loading"
                size="small"
                ref="workContractTable"
                show-header-overflow
                show-overflow
                highlight-hover-row
                :menu-config="{}"
                :print-config="{}"
                @sort-change="sortChangeHandle"
                :sort-config="{remote:true}"
                :data="dataList"
                :checkbox-config="{}">
                <vxe-column type="seq" width="60" title="序号"></vxe-column>
                <vxe-column type="checkbox" width="50px"></vxe-column>

                <vxe-column min-width="200px" title="合同编号" field="no" align="center"></vxe-column>
                <vxe-column min-width="200px" title="合同名称" field="name" align="center">
                  <template #default="scope">
                    <el-link  type="primary" :underline="false" v-if="hasPermission('sys:workContract:edit')" @click="view(scope.row.id)">{{scope.row.name}}</el-link>
                    <el-link  type="primary" :underline="false" v-else-if="hasPermission('sys:workContract:view')" @click="view(scope.row.id)">{{scope.row.name}}</el-link>
                    <span v-else>{{scope.row.name}}</span>
                  </template>
                </vxe-column>
                <vxe-column min-width="100px" title="案卷号" field="filedNo" align="center">
                  <template #default="scope">
                    <el-link  type="primary" :underline="false" v-if="hasPermission('sys:workContract:edit')" @click="view(scope.row.id)">{{scope.row.filedNo}}</el-link>
                    <el-link  type="primary" :underline="false" v-else-if="hasPermission('sys:workContract:view')" @click="view(scope.row.id)">{{scope.row.filedNo}}</el-link>
                    <span v-else>{{scope.row.filedNo}}</span>
                  </template>
                </vxe-column>
                <vxe-column min-width="200px" title="客户名称" field="clientName" align="center">
                  <template #default="scope">
                    <el-link  type="primary" :underline="false" v-if="hasPermission('sys:work_client:edit')" @click="viewInfo(scope.row.clientId)">{{scope.row.clientName}}</el-link>
                    <el-link  type="primary" :underline="false" v-else-if="hasPermission('sys:work_client:view')" @click="viewInfo(scope.row.clientId)">{{scope.row.clientName}}</el-link>
                    <span v-else>{{scope.row.clientName}}</span>
                  </template>
                </vxe-column>
                <vxe-column min-width="100px" title="合同金额(元)" field="contractAmount" align="center"></vxe-column>
                <vxe-column min-width="100px" title="创建人" field="createById" align="center"></vxe-column>
                <vxe-column min-width="150px" title="签订日期" field="contractDate" align="center"></vxe-column>
                <vxe-column  min-width="120px" title="登记状态" field="status" fixed="right" align="center">
                  <template #default="scope">
                    <el-button @click="detail(scope.row)" :type="$dictUtils.getDictLabel('approval_type_status', scope.row.status, '')" effect="dark">{{$dictUtils.getDictLabel("approval_type", scope.row.status, '-')}} </el-button>
                  </template>
                </vxe-column>
                <vxe-column min-width="100px"  title="归档状态" field="filedType" fixed="right" align="center">
                  <template #default="scope">
                    <el-button  @click="detailFiled(scope.row)" :type="$dictUtils.getDictLabel('filed_type_status', scope.row.filedType, '')" effect="dark">{{$dictUtils.getDictLabel("filed_type", scope.row.filedType, '未归档')}} </el-button>
                  </template>
                </vxe-column>
<!--                <vxe-column width="100px"  title="借用状态" field="borrowType" >-->
<!--                  <template slot-scope="scope">-->
<!--                    <el-button @click="detailBorrow(scope.row)" :type="$dictUtils.getDictLabel('borrow_type_status', scope.row.borrowType, '-')" effect="dark" size="small">{{$dictUtils.getDictLabel("borrow_type", scope.row.borrowType, '未借用')}} </el-button>-->
<!--                  </template>-->
<!--                </vxe-column>-->

                <vxe-column title="操作" width="200px" fixed="right" align="center">
                    <template  #default="scope">
<!--                      <el-button v-if="hasPermission('sys:workContract:view')" text type="primary"  @click="view(scope.row.id)">查看</el-button>-->
                      <el-button v-if="hasPermission('sys:workContract:edit') && scope.row.status !== '2' && scope.row.status !== '5' && scope.row.status !== '4' && scope.row.createId === $store.state.user.id" text type="primary"  @click="edit(scope.row)">修改</el-button>
                      <el-button v-if="hasPermission('sys:workContract:edit') && scope.row.status === '5' && isAdmin" text type="primary"  @click="editForm(scope.row.id)">修改</el-button>
                      <el-button v-if="hasPermission('sys:workContract:del') && (scope.row.status === '1' || scope.row.status === '3' )  && scope.row.createId === $store.state.user.id" text type="primary"  @click="del(scope.row.id)">删除</el-button>
                      <el-button v-if="hasPermission('sys:workContract:back') && scope.row.status === '2'  && scope.row.createId === $store.state.user.id" text type="primary"  @click="reback(scope.row)">撤回</el-button>
    <!--              合同登记  审核-->
                      <el-button v-if="scope.row.status==='2' && checkIsAudit(scope.row)" text type="primary"   @click="examine(scope.row)">登记审核</el-button>
    <!--              合同登记  被驳回后当前申请人重新调整-->
                      <el-button v-if="hasPermission('sys:workContract:edit')&&scope.row.createId === $store.state.user.id&&scope.row.status === '4'" text type="primary"   @click="adjust(scope.row)">驳回调整</el-button>

                      <el-button v-if="hasPermission('sys:workContract:filed') && scope.row.status === '5' && scope.row.createId === $store.state.user.id && (scope.row.filedType === '0' || scope.row.filedType === undefined)" text type="primary"  @click="filed(scope.row.id)">归档</el-button>
                      <!--归档暂存修改-->
                      <el-button v-if="hasPermission('sys:workContract:filed') && scope.row.status === '5' && scope.row.createId === $store.state.user.id && scope.row.filedType === '1'" text type="primary"  @click="filed(scope.row.id)">修改</el-button>
                      <!--归档撤回驳回修改-->
                      <el-button v-if="hasPermission('sys:workContract:filed') && scope.row.status === '5' && scope.row.createId === $store.state.user.id && (scope.row.filedType === '3')" text type="primary"  @click="filedAndClose(scope.row)">修改</el-button>
                      <!--归档撤回-->
                      <el-button v-if="hasPermission('sys:workContract:back') && scope.row.status === '5' && scope.row.filedType === '2'  && scope.row.createId === $store.state.user.id" text type="primary"   @click="rebackFiled(scope.row)">撤回</el-button>
      <!--              合同归档  审核-->
                      <el-button v-if="scope.row.filedType==='2' && checkIsAuditFiled(scope.row)" text type="primary"   @click="examineFiled(scope.row)">归档审核</el-button>
      <!--              合同归档  被驳回后当前申请人重新调整-->
                      <el-button v-if="hasPermission('sys:workContract:edit')&&scope.row.createId === $store.state.user.id&&scope.row.filedType === '4'" text type="primary"   @click="adjustFiled(scope.row)">驳回调整</el-button>

                      <!--合同借用-->
<!--                      <el-button v-if="hasPermission('sys:workContract:borrow') && scope.row.status === '5' && scope.row.filedType === '5' && (scope.row.borrowType === undefined || scope.row.borrowType === '0' || scope.row.borrowType === '1')" type="text"  @click="borrow(scope.row.id)">借用</el-button>-->
<!--                      &lt;!&ndash;借用撤回&ndash;&gt;-->
<!--                      <el-button v-if="hasPermission('sys:workContract:back') && scope.row.status === '5' && scope.row.filedType === '5' && scope.row.borrowType === '2'" type="text"  @click="rebackBorrow(scope.row)">撤回</el-button>-->
<!--                      &lt;!&ndash;借用归还&ndash;&gt;-->
<!--                      <el-button v-if="hasPermission('sys:workContract:reture') && scope.row.status === '5' && scope.row.filedType === '5' && scope.row.borrowType === '5'" type="text"  @click="retureBorrow(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>
        </div>
     </div>
        <!-- 弹窗, 新增 / 修改 -->
    <WorkContractForm2 ref="workContractForm2" @refreshDataList="refreshList"></WorkContractForm2>
    <WorkClientForm ref="workClientForm" @refreshDataList="refreshList"></WorkClientForm>
    <WorkContractBorrowMessageForm ref="workContractBorrowMessageForm" @refreshDataList="refreshList"></WorkContractBorrowMessageForm>
  </div>
</template>

<script>
  import InputNumber from './InputNumber.vue'
  import WorkContractForm2 from './WorkContractForm2'
  import WorkClientForm from '@/views/workClient/WorkClientForm'
  import WorkContractBorrowMessageForm from './WorkContractBorrowMessageForm'
  import WorkContractService from '@/api/sys/WorkContractService'
  import WorkContractFileService from '@/api/sys/WorkContractFileService'
  import WorkContractBorrowService from '@/api/sys/WorkContractBorrowService'
  import SelectUserTree from '@/views/utils/treeUserSelect'
  import taskService from '@/api/flowable/taskService'
  import processService from '@/api/flowable/processService'
  import pick from 'lodash.pick'
  import userService from '@/api/sys/userService'
  import UserSelect from '@/components/userSelect'
  export default {
    data () {
      return {
        showHideItem: false,
        showHideIcon: 'el-icon-arrow-down',
        showHideName: '展示',
        visible: false,
        num: 0,
        searchForm: {
          clientName: '',
          name: '',
          contractDates: [],
          type: '',
          filedType: '',
          contractAmounts: [],
			createById: '',
          procInsId: '',
          processDefinitionId: ''
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        processDefinitionId: '',
        procDefKey: '',
        loading: false,
        create: '',
        isAdmin: false,
        applyUserName: ''
      }
    },
    workContractService: null,
    workContractFileService: null,
    workContractBorrowService: null,
    // taskService: null,
    // processService: null,
    // userService: null,
    created () {
      this.workContractService = new WorkContractService()
      this.workContractFileService = new WorkContractFileService()
      this.workContractBorrowService = new WorkContractBorrowService()
      // this.taskService = new TaskService()
      // this.processService = new ProcessService()
      // this.userService = new UserService()
    },
    components: {
      InputNumber,
      WorkContractForm2,
      WorkClientForm,
      WorkContractBorrowMessageForm,
      SelectUserTree,
      UserSelect
    },
    activated () {
      this.is()
      this.refreshList()
    },
    computed: {
      userName () {
        return this.$store.state.user.name
      },
      user () {
        this.create = this.$store.state.user.id
        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 = '展示'
        }
      },
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.workContractService.list({
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          'itemType': '1',
          ...this.searchForm
        }).then((data) => {
          this.dataList = data.records
          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
          }
        })
      },
      // 当前页
      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()
      },
      // 新增
      add () {
        this.start()
      },
      // 评估-合同登记详情
      detail (row) {
        // eslint-disable-next-line eqeqeq
        if (!this.commonJS.isEmpty(row.status) && row.status != '1') {
          taskService.getTaskDef({
            procInsId: row.procInsId,
            procDefId: row.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'
              }
            })
          })
        }
      },
      // 管理员修改
      editForm (id) {
        id = id || this.$refs.workClientTable.getCheckboxRecords().map(item => {
          return item.id
        })[0]
        this.$refs.workContractForm2.init('edit', id)
      },
      // 查看
      view (id) {
        this.$refs.workContractForm2.init('view', id)
      },
      // 客户信息查看
      viewInfo (id) {
        this.$refs.workClientForm.init('view', id)
      },
      // 删除
      del (id) {
        let ids = id || this.$refs.workContractTable.getCheckboxRecords().map(item => {
          return item.id
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.workContractService.remove(ids).then((data) => {
            this.$message.success(data)
            this.refreshList()
            this.loading = false
          })
        })
      },
      resetSearch () {
        this.applyUserName = ''
		  this.searchForm.createById = ''
        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.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: '/workContract/WorkContractList'
              }
            })
          })
      },
      // 评估-合同登记撤回驳回修改
      edit (row) {
        // if (row.status === '3' || row.status === '4') {
        //   this.editWithClose(row)
        // } else {
        //   this.editWithHold(row)
        // }
        // 读取流程表单
        let tabTitle = `发起流程【发票申请】`
        let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了[发票申请]`
        let status = 'startAndHold'
        if (row.status === '3') {
          status = 'startAndClose'
        } else if (row.status === '4') {
          status = 'reapplyFlag'
        }
        taskService.getTaskDef({ procDefId: this.processDefinitionId,
          businessId: row.id,
          businessTable: 'work_contract_info'}).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,
                title: tabTitle,
                formType: data.formType,
                formUrl: data.formUrl,
                formTitle: processTitle,
                businessTable: 'work_contract_info',
                businessId: row.id,
                isShow: 'false',
                status: status,
                routePath: '/workContract/WorkContractList'
              }
            })
          })
      },
      // editWithHold (row) {
      //   // 读取流程表单
      //   let tabTitle = `发起流程【评估-合同登记】`
      //   let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [评估-合同登记]`
      //   this.taskService.getTaskDef({ procDefId: this.processDefinitionId,
      //     businessId: row.id,
      //     businessTable: 'work_contract_info',
      //     status: 'startAndHold'}).then((data) => {
      //       this.$router.push({
      //         path: '/flowable/task/TaskForm',
      //         query: {
      //           procDefId: this.processDefinitionId,
      //           procDefKey: this.procDefKey,
      //           status: 'startAndHold',
      //           title: tabTitle,
      //           formType: data.data.formType,
      //           formUrl: data.data.formUrl,
      //           formTitle: processTitle,
      //           businessTable: 'work_contract_info',
      //           businessId: row.id,
      //           isShow: false,
      //           routePath: '/workContract/WorkContractList'
      //         }
      //       })
      //     })
      // },
      // editWithClose (row) {
      //   // 读取流程表单
      //   let tabTitle = `发起流程【评估-合同登记】`
      //   let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [评估-合同登记]`
      //   this.taskService.getTaskDef({ procDefId: this.processDefinitionId,
      //     businessId: row.id,
      //     businessTable: 'work_contract_info',
      //     status: 'startAndClose'
      //   }).then((data) => {
      //     this.$router.push({
      //       path: '/flowable/task/TaskForm',
      //       query: {
      //         procDefId: this.processDefinitionId,
      //         procDefKey: this.procDefKey,
      //         status: 'startAndClose',
      //         title: tabTitle,
      //         formType: data.data.formType,
      //         formUrl: data.data.formUrl,
      //         formTitle: processTitle,
      //         businessTable: 'work_contract_info',
      //         businessId: row.id,
      //         isShow: false,
      //         routePath: '/workContract/WorkContractList'
      //       }
      //     })
      //   })
      // },
      // 评估-合同登记撤回
      reback (row) {
        this.$confirm(`确定要撤回该申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await this.workContractService.findById(row.id).then((data) => {
            if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
              this.$message.error('数据已发生改变或不存在，请刷新数据')
              this.refreshList()
            } else {
              processService.revokeProcIns(row.procInsId).then(async (data) => {
                let form = {status: '3', id: row.id}
                await this.workContractService.updateStatusById(form)
                this.$message.success(data)
                this.refreshList()
              })
            }
          })
          // this.taskService.backNodes(row.taskId).then(({data}) => {
          //   let backNodes = data
          //   if (backNodes.length > 0) {
          //     let backTaskDefKey = backNodes[0].taskDefKey
          //     this.taskService.back({
          //       taskId: row.taskId,
          //       backTaskDefKey: backTaskDefKey,
          //       isShow: false,
          //       ...this.auditForm
          //     }).then(({data}) => {
          //       this.updateStatusById(row, 'reback')
          //       this.$message.success('回退成功')
          //     })
          //   }
          // })
        })
      },
      // 归档撤回
      rebackFiled (row) {
        this.$confirm(`确定要撤回该申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await this.workContractFileService.findByContractInfoId(row.id).then((data) => {
            if (data.filedType !== '2') { // status的值不等于“审核中”，就弹出提示
              this.$message.error('数据已发生改变或不存在，请刷新数据')
              this.refreshList()
            } else {
              processService.revokeProcIns(data.procInsId).then(async (data) => {
                let form = {filedType: '3', id: row.id}
                await this.workContractFileService.updateStatusById(form)
                this.$message.success(data)
                this.refreshList()
              })
            }
          })
        // this.$confirm(`确定撤回流程吗?`, '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   taskId: row.taskFiledId,
        //   type: 'warning'
        // }).then(() => {
        //   console.log('datas', row.taskFiledId)
        //   this.taskService.backNodes(row.taskFiledId).then(({data}) => {
        //     let backNodes = data
        //     if (backNodes.length > 0) {
        //       let backTaskDefKey = backNodes[0].taskDefKey
        //       this.taskService.back({
        //         taskId: row.taskFiledId,
        //         backTaskDefKey: backTaskDefKey,
        //         isShow: false,
        //         ...this.auditForm
        //       }).then(({data}) => {
        //         this.updateStatusById(row, 'rebackFiled')
        //         this.$message.success('回退成功')
        //       })
        //     }
        //   })
        })
      },
      updateStatusById (row, type) {
        if (type === 'agree') {
          row.status = '5'
          this.workContractService.updateStatusById(row)
        }
        if (type === 'reject') {
          row.status = '4'
          this.workContractService.updateStatusById(row)
        }
        if (type === 'reback') {
          row.status = '3'
          this.workContractService.updateStatusById(row)
        }
        if (type === 'rebackFiled') {
          row.filedType = '3'
          this.workContractFileService.updateStatusById(row)
        }
        if (type === 'rebackBorrow') {
          row.borrowType = '0'
          this.workContractBorrowService.updateStatusByContractInfoId(row).then(() => {
            this.workContractBorrowService.deleteById(row.id)
          })
        }
        if (type === 'retureBorrow') {
          row.borrowType = '0'
          this.workContractBorrowService.updateStatusByContractInfoId(row).then(() => {
            row.type = 'reture'
            row.borrowType = '5'
            this.workContractBorrowService.updateMessageStatusById(row)
          })
        }
      },
      is () {
        userService.is().then((data) => {
          this.isAdmin = data
        })
      },
      // 归档
      filed (id) {
        processService.getByName('评估-合同归档').then((data) => {
          if (!this.commonJS.isEmpty(data.id)) {
            // 读取流程表单
            let tabTitle = `发起流程【评估-合同归档】`
            let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [评估-合同归档]`
            taskService.getTaskDef({ procDefId: data.id,
              businessId: id,
              businessTable: 'work_contract_file',
              status: 'startAndHoldFiled'}).then((reture) => {
                this.$router.push({
                  path: '/flowable/task/TaskForm',
                  query: {
                    ...pick(data.data, '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: 'work_contract_file',
                    businessId: id,
                    isShow: false,
                    routePath: '/workContract/WorkContractList'
                  }
                })
              })
            // 读取流程表单
            // let tabTitle = `发起流程【合同登记归档】`
            // let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [合同登记归档]`
            // this.taskService.getTaskDef({ procDefId: data.id,
            //   businessId: id,
            //   businessTable: 'work_contract_file',
            //   status: 'startAndHoldFiled'}).then((reture) => {
            //     this.$router.push({
            //       path: '/flowable/task/TaskForm',
            //       query: {
            //         procDefId: data.id,
            //         procDefKey: data.key,
            //         status: 'startAndHoldFiled',
            //         title: tabTitle,
            //         formType: reture.data.formType,
            //         formUrl: reture.data.formUrl,
            //         formTitle: processTitle,
            //         businessTable: 'work_contract_file',
            //         businessId: id,
            //         isShow: false,
            //         routePath: '/workContract/WorkContractList'
            //       }
            //     })
            //   })
          }
        })
      },
      // 归档驳回撤回修改
      filedAndClose (row) {
        processService.getByName('评估-合同归档').then((data) => {
          if (!this.commonJS.isEmpty(data.id)) {
            // 读取流程表单
            let tabTitle = `发起流程【评估-合同归档】`
            let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了[评估-合同归档]`
            let status = 'startAndCloseFiled'
            if (row.filedType === '3') {
              status = 'startAndClose'
            } else if (row.filedType === '4') {
              status = 'reapplyFlag'
            }
            taskService.getTaskDef({ procDefId: data.id,
              businessId: row.id,
              businessTable: 'work_contract_file'}).then((reture) => {
                this.$router.push({
                  path: '/flowable/task/TaskForm',
                  query: {
                    ...pick(data.data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
                    procDefId: data.id,
                    procDefKey: data.key,
                    title: tabTitle,
                    formType: reture.formType,
                    formUrl: reture.formUrl,
                    formTitle: processTitle,
                    businessTable: 'work_contract_file',
                    businessId: row.id,
                    isShow: 'false',
                    status: status,
                    routePath: '/workContract/WorkContractList'
                  }
                })
              })
            // 读取流程表单
            // let tabTitle = `发起流程【合同登记归档】`
            // let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [合同登记归档]`
            // this.taskService.getTaskDef({ procDefId: data.id,
            //   businessId: id,
            //   businessTable: 'work_contract_file',
            //   status: 'startAndCloseFiled'}).then((reture) => {
            //     this.$router.push({
            //       path: '/flowable/task/TaskForm',
            //       query: {
            //         procDefId: data.id,
            //         procDefKey: data.key,
            //         status: 'startAndCloseFiled',
            //         title: tabTitle,
            //         formType: reture.data.formType,
            //         formUrl: reture.data.formUrl,
            //         formTitle: processTitle,
            //         businessTable: 'work_contract_file',
            //         businessId: id,
            //         isShow: false,
            //         routePath: '/workContract/WorkContractList'
            //       }
            //     })
            //   })
          }
        })
      },
      // 归档详情
      detailFiled (row) {
        if (row.filedType !== '4') {
          this.workContractFileService.findByContractInfoId(row.id).then((data) => {
            if (!this.commonJS.isEmpty(data.id)) {
              taskService.getTaskDef({
                procInsId: data.procInsId,
                procDefId: data.processDefinitionId
              }).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
                  }
                })
              })
            }
          })
        }
      },
      // 借用
      borrow (id) {
        processService.getByName('评估-合同借用').then((data) => {
          if (!this.commonJS.isEmpty(data.id)) {
            // 读取流程表单
            let tabTitle = `发起流程【评估-合同借用】`
            let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [评估-合同借用]`
            taskService.getTaskDef({ procDefId: data.id,
              businessId: id,
              businessTable: 'work_contract_borrow',
              status: 'startAndCloseBorrow'}).then((reture) => {
                this.$router.push({
                  path: '/flowable/task/TaskForm',
                  query: {
                    procDefId: data.id,
                    procDefKey: data.key,
                    status: 'startAndCloseBorrow',
                    title: tabTitle,
                    formType: reture.formType,
                    formUrl: reture.formUrl,
                    formTitle: processTitle,
                    businessTable: 'work_contract_borrow',
                    businessId: id,
                    isShow: false,
                    routePath: '/workContract/WorkContractList'
                  }
                })
              })
          }
        })
      },
      // 借用详情
      detailBorrow (row) {
        this.$refs.workContractBorrowMessageForm.findList(row.id)
      },
      // 借用撤回
      rebackBorrow (row) {
        this.$confirm(`确定撤回流程吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          taskId: row.taskBorrowId,
          type: 'warning'
        }).then(() => {
          taskService.backNodes(row.taskBorrowId).then((data) => {
            let backNodes = data
            if (backNodes.length > 0) {
              let backTaskDefKey = backNodes[0].taskDefKey
              taskService.back({
                taskId: row.taskBorrowId,
                backTaskDefKey: backTaskDefKey,
                isShow: false,
                ...this.auditForm
              }).then((data) => {
                this.updateStatusById(row, 'rebackBorrow')
                this.$message.success('回退成功')
              })
            }
          })
        })
      },
      // 归还合同
      retureBorrow (row) {
        this.$confirm(`确定归还合同吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.updateStatusById(row, 'retureBorrow')
          this.refreshList()
        })
      },
      // 驳回后调整
      adjust (row) {
        this.workContractService.findById(row.id).then((data) => {
          if (data.status !== '4') { // status的值不等于“驳回”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todo(row)
          }
        })
      },
      // 审核
      examine (row) {
        this.workContractService.findById(row.id).then((data) => {
          if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todo(row)
          }
        })
      },
      // 审核或重新调整跳转
      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: '/workContract/WorkContractList'   // 数据处理后需要跳转的页面路径
            }
          })
        })
      },
      // 查询当前登录人是否是数据的审核人
      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
      },
      // 驳回后调整
      adjustFiled (row) {
        this.workContractFileService.findByContractInfoId(row.id).then((data) => {
          if (data.filedType !== '4') { // status的值不等于“驳回”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todoFiled(row)
          }
        })
      },
      // 审核
      examineFiled (row) {
        this.workContractFileService.findByContractInfoId(row.id).then((data) => {
          if (data.filedType !== '2') { // status的值不等于“审核中”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todoFiled(row)
          }
        })
      },
      // 审核或重新调整跳转
      todoFiled (row) {
        let cUser = false
        taskService.getTaskDefInfo({
          taskId: row.taskFiledId
        }).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: '/workContract/WorkContractList'   // 数据处理后需要跳转的页面路径
            }
          })
        })
      },
      // 查询当前登录人是否是数据的审核人
      checkIsAuditFiled (row) {
        let loginUserId = this.$store.state.user.id  // 获取当前登录用户id
        if (this.commonJS.isNotEmpty(row.auditUserIdsFiled)) {
          for (const userId of row.auditUserIdsFiled) {
            if (userId === loginUserId) {  // 当数据的审核人中包含当前登录人id时，返回true
              return true
            }
          }
        }
        return false
      }
    }
  }
</script>
