<template>
  <div class="page">
    <el-form :inline="true" class="query-form m-b-10" v-if="searchVisible" ref="searchForm" :model="searchForm"
      @keyup.enter="refreshList()" @submit.prevent>
      <!-- 搜索框-->
      <el-form-item prop="contractNo" label="合同编号：">
        <el-input v-model="searchForm.contractNo" placeholder="请输入合同编号" clearable></el-input>
      </el-form-item>
      <el-form-item prop="contractName" label="合同名称：">
        <el-input v-model="searchForm.contractName" placeholder="请输入合同名称" clearable></el-input>
      </el-form-item>
      <el-form-item v-if="showHideItem" prop="filedNo" label="案卷号：">
        <el-input v-model="searchForm.filedNo" placeholder="请输入案卷号" clearable></el-input>
      </el-form-item>
      <el-form-item v-if="showHideItem" prop="clientContactsName" label="委托方：">
        <el-input v-model="searchForm.clientContactsName" placeholder="请输入委托方" clearable>
          <template #suffix>
            <el-button slot="suffix" type="text" icon="el-icon-search" @click="openWorkClient2()"></el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="showHideItem" prop="contractAmounts" label="合同金额：">
        <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" prop="contractDates" label="签约时间：">
        <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" prop="createById" label="创建人：">
        <!--			  <SelectUserTree-->
        <!--				  ref="companyTree"-->
        <!--				  :props="{-->
        <!--                  value: 'id',             // ID字段名-->
        <!--                  label: 'name',         // 显示名称-->
        <!--                  children: 'children'    // 子级字段名-->
        <!--                }"-->
        <!--				  :url="`/system-server/sys/user/treeUserDataAllOffice?type=2`"-->
        <!--				  :value="searchForm.createById"-->
        <!--				  :clearable="true"-->
        <!--				  :accordion="true"-->
        <!--				  size="default"-->
        <!--				  @getValue="(value) => {searchForm.createById=value}"/>-->
        <el-input v-model="searchForm.createById" placeholder="请选择创建人">
          <template #suffix>
            <el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary" slot="append"
              icon="el-icon-search" @click="openUserDia">
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="showHideItem" prop="department" label="所属部门：">
        <SelectTree ref="officeTree" :props="{
          value: 'id',             // ID字段名
          label: 'name',         // 显示名称
          children: 'children'    // 子级字段名
        }" :url="`/system-server/sys/office/treeData?type=1`" :value="searchForm.department" :accordion="true"
          size="default" @getValue="(value) => { searchForm.department = value }" />
      </el-form-item>
      <el-form-item v-if="showHideItem" label="纸质归档" prop="filedPaperType">
        <el-select v-model="searchForm.filedPaperType" 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>
        <el-button type="default" @click="showHide" :icon="showHideIcon">{{ showHideName }}</el-button>
        <el-button type="primary" @click="refreshList()" icon="search">查询</el-button>
        <el-button type="default" @click="resetSearch()" icon="refresh-right">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="jp-table top">
      <vxe-toolbar :refresh="{ query: refreshList }" ref="toolbarRef" export print custom>
        <template #buttons>
          <el-button v-if="hasPermission('cw:workContract:add')" type="primary" icon="el-icon-plus"
            @click="add()">新建</el-button>
          <el-button v-if="hasPermission('cw:workContract:del')" type="danger" hidden icon="el-icon-delete"
            @click="del()" plain>删除</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% - 80px);">
        <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" :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']
          }" :sort-config="{ remote: true }" :data="dataList" :checkbox-config="{}">
          <vxe-column type="seq" width="60" title="序号"></vxe-column>
          <!--          <vxe-column type="checkbox" width="40px"></vxe-column>-->

          <vxe-column min-width="200px" align="center" title="合同名称" field="contractName">
            <template #default="scope">
              <el-link type="primary" :underline="false" v-if="hasPermission('cw:workContract:edit')"
                @click="view(scope.row.id)">{{ scope.row.contractName }}</el-link>
              <el-link type="primary" :underline="false" v-else-if="hasPermission('cw:workContract:view')"
                @click="view(scope.row.id)">{{ scope.row.contractName }}</el-link>
              <span v-else>{{ scope.row.contractName }}</span>
            </template>
          </vxe-column>
          <vxe-column min-width="150" align="center" title="合同编号" field="contractNo"></vxe-column>
          <vxe-column min-width="150" align="center" title="委托方" field="clientContactsName"></vxe-column>
          <vxe-column min-width="150" align="center" title="案卷号" field="filedNo"></vxe-column>
          <vxe-column min-width="150" align="center" title="签约日期" field="signingDate"></vxe-column>
          <vxe-column min-width="150" align="center" title="合同金额(元)" field="contractAmount"></vxe-column>
          <vxe-column min-width="150" align="center" title="所属部门" field="departmentName"></vxe-column>
          <vxe-column min-width="150" align="center" title="创建人" field="createBy"></vxe-column>
          <vxe-column min-width="150" align="center" title="创建日期" field="createTime"></vxe-column>
          <vxe-column min-width="100px" title="状态" field="status" fixed="right" align="center">
            <template #default="scope">
              <el-button @click="detail(scope.row)"
                :type="$dictUtils.getDictLabel('cw_status_flag', scope.row.status, '-')" effect="dark" size="small">{{
                  $dictUtils.getDictLabel("cw_status", scope.row.status, '-') }} </el-button>
            </template>
          </vxe-column>
          <!--          <vxe-column width="200px" title="电子归档" field="filedType">-->
          <!--            <template slot-scope="scope">-->
          <!--              <el-button  text type="primary" @click="detailFiled(scope.row)" :type="$dictUtils.getDictLabel('filed_type_status', scope.row.filedType, '-')" effect="dark" size="mini">{{$dictUtils.getDictLabel("filed_type", scope.row.filedType, '未归档')}} </el-button>-->
          <!--            </template>-->
          <!--          </vxe-column>-->
          <vxe-column min-width="100px" title="纸质归档" fixed="right" align="center" field="filedPaperType">
            <template #default="scope">
              <el-button @click="detailPaperFiled(scope.row)"
                :type="$dictUtils.getDictLabel('filed_type_status', scope.row.filedPaperType, '-')" effect="dark"
                size="small">{{ $dictUtils.getDictLabel("filed_type", scope.row.filedPaperType, '未归档') }} </el-button>
            </template>
          </vxe-column>
          <vxe-column min-width="100px" title="借用状态" fixed="right" align="center" field="borrowType">
            <template #default="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="操作" min-width="250px" fixed="right" align="center">
            <template #default="scope">
              <div v-if="isAdmin">
                <el-button v-if="scope.row.status === '5'" text type="primary" size="small"
                  @click="edit(scope.row)">修改</el-button>
                <el-button v-if="scope.row.status === '5'" text type="primary" size="small"
                  @click="del(scope.row.id)">删除</el-button>

                <el-button v-if="scope.row.status === '5'" text type="primary" size="small"
                  @click="rebackAllByAdmin(scope.row)">撤回合同登记</el-button>
                <el-button v-if="scope.row.status === '5' && scope.row.filedPaperType === '5'" text type="primary"
                  size="small" @click="rebackPaperFiled(scope.row)">撤回归档</el-button>
              </div>
              <div v-else>
                <!--              <el-button v-if="hasPermission('cw:workContract:view')" text type="primary" size="small" @click="view(scope.row.id)">查看</el-button>-->
                <el-button
                  v-if="hasPermission('cw:workContract:edit') && (scope.row.createId === $store.state.user.id) &&
                    (scope.row.filedPaperType !== '2' && scope.row.filedPaperType !== '5' && scope.row.filedPaperType !== '4')"
                  text type="primary" size="small" @click="edit(scope.row)">修改</el-button>
                <el-button v-if="hasPermission('cw:update:fileNumber') && scope.row.filedPaperType === '5'" text
                  type="primary" size="small" @click="editFileNumber(scope.row)">修改</el-button>
                <!--              <el-button v-if="hasPermission('cw:workContract:edit') && scope.row.status === '5' && isAdmin && (scope.row.filedPaperType === '0' || scope.row.filedPaperType === '1' || scope.row.filedPaperType === '3')" text type="primary" size="small" @click="editForm(scope.row.id)">修改</el-button>-->
                <!--<el-button v-else-if="hasPermission('cw:workContract:edit') && scope.row.status === '5' && scope.row.createId === $store.state.user.id && (scope.row.filedPaperType === '0' || scope.row.filedPaperType === '1' || scope.row.filedPaperType === '3' || commonJS.isEmpty(scope.row.filedPaperType))" text type="primary" size="small" @click="editForm(scope.row.id)">修改</el-button>-->
                <!--              审核-->
                <!--              <el-button v-if="scope.row.status==='2' && checkIsAudit(scope.row)" text type="primary"  size="small" @click="examine(scope.row)">审核</el-button>-->
                <!--              被驳回后当前申请人重新调整-->
                <!--              <el-button v-if="hasPermission('cw:workContract:edit')&&scope.row.createId === $store.state.user.id&&scope.row.status === '4'" text type="primary"  size="small" @click="adjust(scope.row)">驳回调整</el-button>-->
                <!--              <el-button v-if="hasPermission('cw:workContract:edit') && scope.row.status === '5' && scope.row.filedType === '5' && scope.row.filedPaperType === '5' && isAdmin" text type="primary" size="small" @click="editForm(scope.row.id)">修改</el-button>-->
                <el-button
                  v-if="hasPermission('cw:workContract:del') && (scope.row.filedPaperType === '1' || scope.row.filedPaperType === '3' || scope.row.filedPaperType === '0') && scope.row.createId === $store.state.user.id"
                  text type="primary" size="small" @click="del(scope.row.id)">删除</el-button>
                <el-button
                  v-if="hasPermission('cw:workContract:back') && scope.row.status === '2' && scope.row.createId === $store.state.user.id"
                  text type="primary" size="small" @click="reback(scope.row)">撤回</el-button>
                <!--              <el-button v-if="hasPermission('cw:workContract:filed') && scope.row.status === '5' && scope.row.createId === $store.state.user.id && (scope.row.filedType === '0' || scope.row.filedType === undefined)" text type="primary" size="small" @click="filed(scope.row.id)">归档</el-button>-->
                <!--归档暂存修改-->
                <!--              <el-button v-if="hasPermission('cw:workContract:filed') && scope.row.status === '5' && scope.row.createId === $store.state.user.id && scope.row.filedType === '1'" text type="primary" size="small" @click="filed(scope.row.id)">修改</el-button>-->
                <!--归档撤回驳回修改-->
                <!--              <el-button v-if="hasPermission('cw:workContract:filed') && scope.row.status === '5' && scope.row.createId === $store.state.user.id && (scope.row.filedType === '3' || scope.row.filedType === '4')" text type="primary" size="small" @click="filedAndClose(scope.row.id)">修改</el-button>-->
                <!--归档撤回-->
                <!--              <el-button v-if="hasPermission('cw:workContract:back') && scope.row.status === '5' && scope.row.filedType === '2'" text type="primary"  size="small" @click="rebackFiled(scope.row)">撤回</el-button>-->
                <!--合同借用-->
                <el-button
                  v-if="hasPermission('cw:workContract:borrow') && scope.row.status === '5' && scope.row.filedPaperType === '5' && (scope.row.borrowType === undefined || scope.row.borrowType === '0' || scope.row.borrowType === '1')"
                  text type="primary" size="small" @click="borrow(scope.row)">借用</el-button>
                <!--借用撤回-->
                <el-button
                  v-if="hasPermission('cw:workContract:back') && scope.row.status === '5' && scope.row.filedPaperType === '5' && scope.row.borrowType === '2' && (scope.row.borrowUserId === $store.state.user.id)"
                  text type="primary" size="small" @click="rebackBorrow(scope.row)">撤回借用申请</el-button>
                <!--借用归还-->
                <el-button
                  v-if="hasPermission('cw:workContract:reture') && scope.row.status === '5' && scope.row.filedPaperType === '5' && scope.row.borrowType === '5'"
                  text type="primary" size="small" @click="retureBorrow(scope.row)">归还合同</el-button>

                <el-button
                  v-if="hasPermission('cw:workContract:filed') && scope.row.status === '5' && scope.row.createId === $store.state.user.id && (scope.row.filedPaperType === '0' || scope.row.filedPaperType === undefined)"
                  text type="primary" size="small" @click="paperFiled(scope.row)">纸质归档</el-button>
                <!--纸质归档暂存修改-->
                <el-button
                  v-if="hasPermission('cw:workContract:filed') && scope.row.status === '5' && scope.row.createId === $store.state.user.id && scope.row.filedPaperType === '1'"
                  text type="primary" size="small" @click="paperFiled(scope.row)">纸质归档</el-button>
                <!--纸质归档撤回驳回修改-->
                <el-button
                  v-if="hasPermission('cw:workContract:filed') && scope.row.status === '5' && scope.row.createId === $store.state.user.id && (scope.row.filedPaperType === '3')"
                  text type="primary" size="small" @click="paperFiledAndClose(scope.row.id)">纸质归档</el-button>
                <!--纸质归档撤回-->
                <el-button
                  v-if="hasPermission('cw:workContract:back') && scope.row.status === '5' && scope.row.filedPaperType === '2'"
                  text type="primary" size="small" @click="rebackPaperFiled(scope.row)">撤回纸质归档</el-button>
                <!--              审核-->
                <el-button v-if="scope.row.filedPaperType === '2' && checkIsAuditFiledPaper(scope.row)" text
                  type="primary" size="small" @click="examineFiledPaper(scope.row)">审核</el-button>
                <!--              被驳回后当前申请人重新调整-->
                <el-button
                  v-if="hasPermission('cw:workContract:edit') && scope.row.createId === $store.state.user.id && scope.row.filedPaperType === '4'"
                  text type="primary" size="small" @click="adjustFiledPaper(scope.row)">驳回调整</el-button>
              </div>
            </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>
    <!-- 弹窗, 新增 / 修改 -->
    <ContractNameForm ref="contractNameForm" @refreshDataList="refreshList"></ContractNameForm>
    <ContractAddForm ref="contractAddForm" @refreshDataList="refreshList"></ContractAddForm>
    <WorkClientForm ref="workClientForm" @refreshDataList="refreshList"></WorkClientForm>
    <WorkClientChooseRadio ref="workClientChooseRadio" @getWorkClientRadioChoose="getWorkClientChoose2">
    </WorkClientChooseRadio>
    <WorkContractBorrowMessageForm ref="workContractBorrowMessageForm" @refreshDataList="refreshList">
    </WorkContractBorrowMessageForm>
    <user-select ref="userSelect2" @doSubmit="selectUser"></user-select>
    <ContractUpdateFileNumberForm ref="contractUpdateFileNumberForm" @refreshDataList="refreshList">
    </ContractUpdateFileNumberForm>
  </div>
</template>

<script>
import InputNumber from '@/views/workContract/InputNumber.vue'
import ContractNameForm from "./ContractNameForm";
import ContractAddForm from './contractRegisitionAddForm/ContractAddForm'
import WorkClientForm from '../../workClient/WorkClientForm'
import WorkContractBorrowMessageForm from './WorkContractBorrowMessageForm'
import contractInfoService from "@/api/cw/workContract/ContractInfoService";
import ContractFileService from '@/api/cw/workContract/ContractFileService'
import ContractFilePaperService from '@/api/cw/workContract/ContractFilePaperService'
import CwWorkContractBorrowService from '@/api/cw/workContract/CwWorkContractBorrowService'
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 SelectTree from '@/components/treeSelect/treeSelect.vue'
import WorkClientChooseRadio from '@/views/cw/workClientInfo/WorkClientChooseRadioList'
import UserSelect from '@/views/utils/UserTreeSelect'
import ContractUpdateFileNumberForm from "./contractRegisitionAddForm/ContractUpdateFileNumberForm"
export default {
  data() {
    return {
      searchVisible: true,
      showHideItem: false,
      showHideIcon: 'el-icon-arrow-down',
      showHideName: '展示',
      visible: false,
      num: 0,
      searchForm: {
        filedPaperType: '',
        contractNo: '',
        contractName: '',
        filedNo: '',
        contractAmount: '',
        contractDates: [],
        type: '',
        filedType: '',
        contractAmounts: [],
        createById: '',
        createId: '',
        department: '',
        status: '',
        procInsId: '',
        processDefinitionId: '',
        clientContactsName: '',
      },
      dataList: [],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        orders: []
      },
      processDefinitionId: '',
      procDefKey: '',
      loading: false,
      create: '',
      isAdmin: false
    }
  },
  contractFileService: null,
  contractFilePaperService: null,
  cwWorkContractBorrowService: null,
  created() {
    this.contractFileService = new ContractFileService()
    this.contractFilePaperService = new ContractFilePaperService()
    this.cwWorkContractBorrowService = new CwWorkContractBorrowService()
  },
  components: {
    InputNumber,
    ContractNameForm,
    ContractAddForm,
    WorkClientForm,
    WorkContractBorrowMessageForm,
    SelectUserTree,
    SelectTree,
    WorkClientChooseRadio,
    UserSelect,
    ContractUpdateFileNumberForm
  },
  activated() {
    this.is()
    this.refreshList()
  },
  computed: {
    userName() {
      return this.$store.state.user.name
    },
    user() {
      this.create = this.$store.state.user.id
      // console.log('createId', this.create)
      return this.$store.state.user
    }
  },
  mounted() {
    this.$nextTick(() => {
      //将表格和工具栏进行关联
      const $table = this.$refs.workContractTable;
      const $toolbar = this.$refs.toolbarRef;
      $table.connect($toolbar);
    })
  },
  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() {
      console.log('user', this.$store.state.user.id)
      this.loading = true
      contractInfoService
        .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.$refs.contractAddForm.init('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: {
              readOnly: true,
              title: '流程详情',
              formTitle: '流程详情',
              businessId: row.id,
              ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title', 'businessId')
            }
          })
        })
      }
    },
    // 修改
    edit(row) {
      this.$refs.contractAddForm.init('edit', row.id)
      // if (row.status === '3' || row.status === '4') {
      //   this.editWithClose(row)
      // } else {
      //   this.editWithHold(row)
      // }
    },
    editFileNumber(row) {
      this.$refs.contractUpdateFileNumberForm.init('edit', row.id)
    },
    // 管理员修改
    editForm(id) {
      id = id || this.$refs.workClientTable.getCheckboxRecords().map(item => {
        return item.id
      })[0]
      this.$refs.contractNameForm.init('edit', id)
    },
    // 查看
    view(id) {
      this.$refs.contractNameForm.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
        contractInfoService.remove(ids).then((data) => {
          if (data === '删除成功') {
            this.$message.success(data)
          } else {
            this.$message.error(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.processDefinitionId,
        status: 'startAndHold'
      }).then((data) => {
        this.$router.push({
          path: '/flowable/task/TaskForm',
          query: {
            ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
            procDefId: this.processDefinitionId,
            procDefKey: this.procDefKey,
            status: 'startAndHold',
            title: tabTitle,
            formType: data.formType,
            formUrl: data.formUrl,
            formTitle: processTitle,
            businessId: 'false',
            isShow: false,
            routePath: '/cw/workContract/ContractRegistration'
          }
        })
      })
    },
    editWithHold(row) {
      // 读取流程表单
      let tabTitle = `发起流程【会计-合同登记】`
      let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [会计-合同登记]`
      taskService.getTaskDef({
        procDefId: this.processDefinitionId,
        businessId: row.id,
        businessTable: 'cw_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.formType,
            formUrl: data.formUrl,
            formTitle: processTitle,
            businessTable: 'cw_work_contract_info',
            businessId: row.id,
            isShow: false,
            routePath: '/cw/workContract/ContractRegistration'
          }
        })
      })
    },
    editWithClose(row) {
      // 读取流程表单
      let tabTitle = `发起流程【会计-合同登记】`
      let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [会计-合同登记]`
      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.formType,
            formUrl: data.formUrl,
            formTitle: processTitle,
            businessTable: 'work_contract_info',
            businessId: row.id,
            isShow: false,
            statusFlag: row.status,
            routePath: '/cw/workContract/ContractRegistration',
            ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title')
          }
        })
      })
    },
    reback(row) {
      // console.log('row', row.procInsId)
      this.$confirm(`确定撤回流程吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        processService.revokeProcIns(row.procInsId).then((data) => {
          // console.log('updateStatusById')
          let form = { status: '3', id: row.id }
          this.updateStatusById(form, 'reback')
          this.$message.success(data)
          this.refreshList()
        })
      })
    },
    rebackFiled(row) {
      // console.log('row.taskFiledProcInsId' + row.taskFiledProcInsId)
      this.$confirm(`确定撤回流程吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        processService.revokeProcIns(row.taskFiledProcInsId).then((data) => {
          // let form = {filedType: '3', id: row.id}
          this.updateStatusById(row, 'rebackFiled')
          this.$message.success(data)
          this.refreshList()
        })
      })
    },
    rebackAllByAdmin(row) {
      this.$confirm(`确定撤回流程吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 撤回合同登记
        const res = await processService.revokeProcIns(row.procInsId)
        let form = { status: '3', id: row.id }
        this.updateStatusById(form, 'reback')
        // 撤回归档
        if (row.taskFiledPaperProcInsId && row.taskFiledPaperProcInsId != null) {
          const res1 = await processService.revokeProcIns(row.taskFiledPaperProcInsId)
          this.updateStatusById(row, 'rebackFiledPaperAll')
        }
        this.$message.success("撤回成功")
        this.refreshList()
      })
    },
    updateStatusById(row, type) {
      // console.log('updateStatusByIdupdateStatusById')
      // console.log(type)
      if (type === 'agree') {
        row.status = '5'
        contractInfoService.updateStatusById(row)
      }
      if (type === 'reject') {
        row.status = '4'
        contractInfoService.updateStatusById(row)
      }
      if (type === 'reback') {
        row.status = '3'
        contractInfoService.updateStatusById(row)
      }
      if (type === 'rebackFiled') {
        row.filedType = '3'
        this.contractFileService.updateStatusById(row)
      }
      if (type === 'rebackFiledPaper') {
        row.filedPaperType = '3'
        row.createTime = '';
        this.contractFilePaperService.updateStatusById(row)
      }
      if (type === 'rebackFiledPaperAll') {
        row.filedPaperType = '0'
        row.createTime = '';
        this.contractFilePaperService.updateStatusById(row)
      }
      if (type === 'rebackBorrow') {
        row.borrowType = '0'
        row.createTime = '';
        this.cwWorkContractBorrowService.updateStatusByContractInfoId(row).then(() => {
          this.cwWorkContractBorrowService.deleteById(row.id)
        })
      }
      if (type === 'retureBorrow') {
        row.createTime = '';
        row.borrowType = '0'
        this.cwWorkContractBorrowService.updateStatusByContractInfoId(row).then(() => {
          row.type = 'reture'
          row.createTime = '';
          row.borrowType = '5'
          this.cwWorkContractBorrowService.updateMessageStatusById(row)
        })
      }
    },
    is() {
      userService.is().then((data) => {
        this.isAdmin = data
      })
    },
    // 归档
    /* filed (id) {
      this.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')} 发起了 [会计-合同电子归档]`
          this.taskService.getTaskDef({ procDefId: data.id,
            businessId: id,
            businessTable: 'cw_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.formType,
                  formUrl: reture.formUrl,
                  formTitle: processTitle,
                  businessTable: 'cw_work_contract_file',
                  businessId: id,
                  isShow: false,
                  routePath: '/cw/workContract/ContractRegistration'
                }
              })
            })
        }
      })
    }, */
    // 归档
    /* filedAndClose (id) {
      this.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')} 发起了 [会计-合同电子归档]`
          this.taskService.getTaskDef({ procDefId: data.id,
            businessId: id,
            businessTable: 'cw_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.formType,
                  formUrl: reture.formUrl,
                  formTitle: processTitle,
                  businessTable: 'cw_work_contract_file',
                  businessId: id,
                  isShow: false,
                  routePath: '/cw/workContract/ContractRegistration'
                }
              })
            })
        }
      })
    }, */
    // 归档详情
    /* detailFiled (row) {
      // console.log('row.id', row.id)
      // eslint-disable-next-line eqeqeq
      if (!this.commonJS.isEmpty(row.filedType) && row.filedType != '1') {
        this.contractFileService.findByContractInfoId(row.id).then((data) => {
          if (!this.commonJS.isEmpty(data.id)) {
            // console.log('data', data)
            this.taskService.getTaskDef({
              procInsId: data.procInsId,
              procDefId: data.processDefinitionId
            }).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')}
              })
            })
          }
        })
      }
    }, */
    // 借用
    borrow(row) {
      processService.getByName('会计-合同借用').then((data) => {
        if (!this.commonJS.isEmpty(data.id)) {
          // console.log('data', data)
          // 读取流程表单
          let tabTitle = ' ' + row.contractNo + ' - ' + row.contractName
          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_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: 'cw_work_contract_borrow',
                businessId: row.id,
                isShow: false,
                routePath: '/cw/workContract/ContractRegistration'
              }
            })
          })
        }
      })
    },
    // 借用详情
    detailBorrow(row) {
      this.$refs.workContractBorrowMessageForm.findList(row.id)
    },
    // 借用撤回
    rebackBorrow(row) {
      this.$confirm(`确定撤回流程吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        taskId: row.taskBorrowId,
        type: 'warning'
      }).then(() => {
        // console.log('datas', row.taskBorrowId)
        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()
      })
    },
    // 纸质归档
    paperFiled(row) {
      console.log('row', row)
      processService.getByName('会计-合同纸质归档').then((data) => {
        if (!this.commonJS.isEmpty(data.id)) {
          // console.log('data', data)
          // 读取流程表单
          let tabTitle = ' ' + row.contractNo + ' - ' + row.contractName
          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_work_contract_file_paper',
            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_work_contract_file_paper',
                businessId: row.id,
                isShow: false,
                routePath: '/cw/workContract/ContractRegistration'
              }
            })
          })
        }
      })
    },
    // 纸质归档撤回驳回修改
    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_work_contract_file_paper',
            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_work_contract_file_paper',
                businessId: id,
                isShow: false,
                routePath: '/cw/workContract/ContractRegistration'
              }
            })
          })
        }
      })
    },
    // 纸质归档撤回
    rebackPaperFiled(row) {
      console.log('row.taskFiledProcInsId', row)
      this.$confirm(`确定撤回流程吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        processService.revokeProcIns(row.taskFiledPaperProcInsId).then((data) => {
          // let form = {filedType: '3', id: row.id}
          this.updateStatusById(row, 'rebackFiledPaper')
          this.$message.success(data)
          this.refreshList()
        })
      })
      this.refreshList()
    },
    // 纸质归档详情
    detailPaperFiled(row) {
      // console.log('row.id', row.id)
      // eslint-disable-next-line eqeqeq
      if (!this.commonJS.isEmpty(row.filedPaperType) && row.filedPaperType != '1') {
        this.contractFilePaperService.findByContractInfoId(row.id).then((data) => {
          if (!this.commonJS.isEmpty(data.id)) {
            console.log('data', data)
            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'),
                  isShow: 'false',
                  readOnly: true,
                  title: '纸质归档流程详情',
                  formTitle: '纸质归档流程详情',
                  businessId: row.id,
                  status: 'reback'
                }
              })
            })
          }
        })
      }
    },
    // 驳回后调整
    adjust(row) {
      contractInfoService.findById(row.id).then((data) => {
        if (data.status !== '4') { // status的值不等于“驳回”，就弹出提示
          this.$message.error('数据已发生改变或不存在，请刷新数据')
          this.refreshList()
        } else {
          this.todo(row)
        }
      })
    },
    // 审核
    examine(row) {
      contractInfoService.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) => {
        console.log(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/workContract/ContractRegistration'   // 数据处理后需要跳转的页面路径
          }
        })
      })
    },
    // 查询当前登录人是否是数据的审核人
    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
    },
    // 驳回后调整
    adjustFiledPaper(row) {
      contractInfoService.findById(row.id).then((data) => {
        if (data.filedPaperType !== '4') { // status的值不等于“驳回”，就弹出提示
          this.$message.error('数据已发生改变或不存在，请刷新数据')
          this.refreshList()
        } else {
          this.todoFiledPaper(row)
        }
      })
    },
    // 审核
    examineFiledPaper(row) {
      contractInfoService.findById(row.id).then((data) => {
        if (data.filedPaperType !== '2') { // status的值不等于“审核中”，就弹出提示
          this.$message.error('数据已发生改变或不存在，请刷新数据')
          this.refreshList()
        } else {
          this.todoFiledPaper(row)
        }
      })
    },
    // 审核或重新调整跳转
    todoFiledPaper(row) {
      let cUser = false
      taskService.getTaskDefInfo({
        taskId: row.filePaperTaskId
      }).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/workContract/ContractRegistration'   // 数据处理后需要跳转的页面路径
          }
        })
      })
    },
    // 查询当前登录人是否是数据的审核人
    checkIsAuditFiledPaper(row) {
      let loginUserId = this.$store.state.user.id  // 获取当前登录用户id
      if (this.commonJS.isNotEmpty(row.auditUserIdsFP)) {
        for (const userId of row.auditUserIdsFP) {
          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.data.map(item => item.id) : [],
        exportFields: options.columns.map(column => column.property)
      }
      return contractInfoService.exportFile(params).then((res) => {
        // 将二进制流文件写入excel表，以下为重要步骤
        this.$utils.downloadExcel(res, options.filename)
      }).catch(function (err) {
        if (err.response) {
          console.log(err.response)
        }
      })
    },
    openWorkClient2() {
      this.$refs.workClientChooseRadio.init()
    },
    getWorkClientChoose2(row) {
      this.searchForm.clientContactsName = row.name
    },
    openUserDia() {
      this.$refs.userSelect2.init()
    },
    selectUser(user) {
      console.log(user[0].name)
      this.searchForm.createById = user[0].name
    },
  }
}
</script>
