<template>
  <div class="page">
    <el-form size="small" :inline="true" class="query-form" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
      <!-- 搜索框-->
      <el-form-item prop="rosterId" label="姓名">
        <RosterSelectForm :limit='1' :value="searchForm.rosterId" @getValue='(value) => {searchForm.rosterId=value}'></RosterSelectForm>
      </el-form-item>
      <el-form-item prop="rosterBaseDTO.officeId">
        <SelectTree
          ref="officeTree"
          :props="{
                value: 'id',             // ID字段名
                label: 'name',         // 显示名称
                children: 'children'    // 子级字段名
              }"
          :url="`/sys/office/treeData?type=2`"
          :value="searchForm.rosterBaseDTO.officeId"
          :clearable="true"
          :accordion="true"
          @getValue="(value) => {searchForm.rosterBaseDTO.officeId=value}"/>
      </el-form-item>
      <el-form-item prop="rosterBaseDTO.mobile">
        <el-input size="small" v-model="searchForm.rosterBaseDTO.mobile" placeholder="手机号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="refreshList()" size="small" icon="el-icon-search">查询</el-button>
        <el-button @click="resetSearch()" size="small" icon="el-icon-refresh-right">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="bg-white top">
      <vxe-toolbar :refresh="{query: refreshList}" custom>
        <template #buttons>
          <el-button v-if="hasPermission('changes:dimission:add')" type="primary" size="small" icon="el-icon-plus" @click="add()">办理员工离职</el-button>
<!--          <el-button v-if="hasPermission('changes:dimission:del')" type="danger"   size="small" icon="el-icon-delete" @click="del()" :disabled="$refs.dimissionTable && $refs.dimissionTable.getCheckboxRecords().length === 0" plain>删除</el-button>-->
        </template>
      </vxe-toolbar>
      <div style="height: calc(100% - 140px);">
        <vxe-table
          border="inner"
          auto-resize
          resizable
          height="auto"
          :loading="loading"
          size="small"
          ref="dimissionTable"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :menu-config="{}"
          :print-config="{}"
          :export-config="{}"
          @sort-change="sortChangeHandle"
          :sort-config="{remote:true}"
          :data="dataList"
          :import-config="{}"
          :checkbox-config="{}">
          <vxe-column type="seq" width="60" title="序号"></vxe-column>
<!--          <vxe-column type="checkbox"  width="40px"></vxe-column>-->
          <vxe-column width="150" title="姓名" field="rosterBaseDTO.name">
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false" v-if="hasPermission('changes:dimission:view')"  @click="view(scope.row.id)">{{!commonJS.isEmpty(scope.row.rosterBaseDTO.name)?scope.row.rosterBaseDTO.name:'--'}}</el-link>
              <span v-else>{{!commonJS.isEmpty(scope.row.rosterBaseDTO.name)?scope.row.rosterBaseDTO.name:'--'}}</span>
            </template>
          </vxe-column>

          <vxe-column width="200" title="工号" field="rosterBaseDTO.jobNo"></vxe-column>
          <vxe-column width="200" title="部门" field="soName"></vxe-column>
          <vxe-column width="200" title="职位" field="jpName"></vxe-column>
          <vxe-column width="200" title="手机号" field="rosterBaseDTO.mobile"></vxe-column>
          <vxe-column width="200" title="入职日期" field="rosterBaseDTO.onboardingDate">
            <template slot-scope="scope">
              {{moment(scope.row.rosterBaseDTO.onboardingDate).format('YYYY-MM-DD')}}
            </template>
          </vxe-column>
          <vxe-column width="200" title="最后工作日" field="lastWorkDate">
            <template slot-scope="scope">
              {{moment(scope.row.lastWorkDate).format('YYYY-MM-DD')}}
            </template>
          </vxe-column>
          <vxe-column width="200" title="离职日期" field="dimissionDate">
            <template slot-scope="scope">
              {{moment(scope.row.dimissionDate).format('YYYY-MM-DD')}}
            </template>
          </vxe-column>
          <vxe-column width="200" title="离职原因" field="changesDimissionReaDTOList">
            <template slot-scope="scope">
              {{getDimissionReaList(scope.row.changesDimissionReaDTOList)}}
            </template>
          </vxe-column>
          <vxe-column width="200" title="原因说明" field="reasonDesc"></vxe-column>
          <vxe-column width="200" title="离职类型" field="type">
            <template slot-scope="scope">
              {{$dictUtils.getDictLabel('dimission_type', scope.row.type, '-')}}
            </template>
          </vxe-column>
          <vxe-column width="200" title="备注" field="remarks"></vxe-column>

          <vxe-column width="120" title="离职审批" fixed="right" align="center" field="vettingStatus">
            <template slot-scope="scope">
              <el-button v-if="scope.row.vettingStatus === '4'" type="primary" @click="auditDetail(scope.row)" size="mini">
                {{$dictUtils.getDictLabel("vetting_status", scope.row.vettingStatus, '-')}}
              </el-button>
              <el-button v-else-if="scope.row.vettingStatus === '6'" type="success" @click="auditDetail(scope.row)" size="mini">
                {{$dictUtils.getDictLabel("vetting_status", scope.row.vettingStatus, '-')}}
              </el-button>
              <el-button v-else-if="scope.row.vettingStatus === '7'" type="warning" @click="auditDetail(scope.row)" size="mini">
                {{$dictUtils.getDictLabel("vetting_status", scope.row.vettingStatus, '-')}}
              </el-button>
              <el-button v-else-if="scope.row.vettingStatus === '2'" type="info" size="mini" plain>
                {{$dictUtils.getDictLabel("vetting_status", scope.row.vettingStatus, '-')}}
              </el-button>
              <el-button v-else-if="scope.row.vettingStatus === '3'" type="info" size="mini">
                {{$dictUtils.getDictLabel("vetting_status", scope.row.vettingStatus, '-')}}
              </el-button>
              <el-button v-else-if="scope.row.vettingStatus === '5'" type="danger" @click="auditDetail(scope.row)" size="mini">
                {{$dictUtils.getDictLabel("vetting_status", scope.row.vettingStatus, '-')}}
              </el-button>
              <el-button v-else size="mini">
                {{$dictUtils.getDictLabel("vetting_status", scope.row.vettingStatus, '-')}}
              </el-button>
            </template>
          </vxe-column>
          <vxe-column width="120" title="离职交接" fixed="right" align="center" field="handoverStatus">
            <template slot-scope="scope">
              <el-button v-if="scope.row.handoverStatus === '3'" type="primary"  @click="handoverDetail(scope.row)" size="mini">
                {{$dictUtils.getDictLabel('handover_status', scope.row.handoverStatus, '-')}}
              </el-button>
              <el-button v-else-if="scope.row.handoverStatus === '4'" type="success"  @click="handoverDetail(scope.row)" size="mini">
                {{$dictUtils.getDictLabel('handover_status', scope.row.handoverStatus, '-')}}
              </el-button>
              <el-button v-else-if="scope.row.handoverStatus === '6'" type="warning"  @click="handoverDetail(scope.row)" size="mini">
                {{$dictUtils.getDictLabel('handover_status', scope.row.handoverStatus, '-')}}
              </el-button>
              <el-button v-else-if="scope.row.handoverStatus === '2'" type="info" size="mini">
                {{$dictUtils.getDictLabel('handover_status', scope.row.handoverStatus, '-')}}
              </el-button>
              <el-button v-else-if="scope.row.handoverStatus === '5'" type="danger" @click="handoverDetail(scope.row)" size="mini">
                {{$dictUtils.getDictLabel('handover_status', scope.row.handoverStatus, '-')}}
              </el-button>
              <el-button v-else size="mini">
                {{$dictUtils.getDictLabel('handover_status', scope.row.handoverStatus, '-')}}
              </el-button>

            </template>
          </vxe-column>
          <vxe-column width="120" title="离职状态" fixed="right" align="center" field="status">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status === '2'" type="success" size="mini">
                {{$dictUtils.getDictLabel('dimission_status', scope.row.status, '-')}}
              </el-button>
              <el-button v-else size="mini">
                {{$dictUtils.getDictLabel('dimission_status', scope.row.status, '-')}}
              </el-button>
            </template>
          </vxe-column>
          <vxe-column title="操作" width="50px" fixed="right" align="center">
            <template  slot-scope="scope">
              <el-dropdown size="small"  @command="handleCommand">
                    <span class="el-dropdown-link">
                      更多
                    </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item  v-if="hasPermission('changes:dimission:view')" :command="{method:'view', id:scope.row.id}">
                    查看
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission('changes:dimission:edit')&&
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '1')||
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '3')||
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '5')
                                          "
                                    :command="{method:'edit', id:scope.row.id}">
                    修改
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission('changes:dimission:del')&&
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '1')||
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '3')||
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '5')||
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '6')
                                          "
                                    :command="{method:'del', id:scope.row.id}">
                    放弃离职
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission('changes:dimission:edit')&&
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '1')||
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '3')||
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '5')||
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '6')
                                          "
                                    :command="{method:'sure', id:scope.row.id}">
                    确认离职
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission('changes:dimission:edit')&&
                                              (scope.row.handoverStatus === '1'&&scope.row.status === '2')||
                                              (scope.row.handoverStatus === '2'&&scope.row.status === '2')||
                                              (scope.row.handoverStatus === '5'&&scope.row.status === '2')||
                                              (scope.row.handoverStatus === '6'&&scope.row.status === '2')"
                                    :command="{method:'removeSure', row:scope.row}">
                    取消确认
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission('changes:dimission:edit')&&
                                              scope.row.status === '2'&&
                                              scope.row.handoverStatus === '1'||scope.row.handoverStatus === '2'||scope.row.handoverStatus === '5'||scope.row.handoverStatus === '6'"
                                    :command="{method:'handover', row:scope.row}">
                    {{scope.row.handoverStatus === '1'?'发起工作交接审批':'修改工作交接审批'}}
                  </el-dropdown-item>
<!--                  <el-dropdown-item v-if="hasPermission('changes:dimission:view')&&-->
<!--                                              scope.row.status === '2'&&-->
<!--                                              (scope.row.handoverStatus === '3'||scope.row.handoverStatus === '4'||scope.row.handoverStatus === '5'||scope.row.handoverStatus === '6')"-->
<!--                                    :command="{method:'handoverDetail', row:scope.row}">-->
<!--                    工作交接审批结果-->
<!--                  </el-dropdown-item>-->
                  <el-dropdown-item v-if="hasPermission('changes:dimission:view')&&
                                              scope.row.status === '2'&&
                                              scope.row.handoverStatus === '3'"
                                    :command="{method:'handoverReback', row:scope.row}">
                    撤销工作交接审批
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission('changes:dimission:edit')&&
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '1')||
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '3')||
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '5')||
                                              (scope.row.status === '1'&&scope.row.vettingStatus === '7')"
                                    :command="{method:'audit', row:scope.row}">
                    {{scope.row.vettingStatus === '1'?'发起离职审批':'修改离职审批'}}
                  </el-dropdown-item>
<!--                  <el-dropdown-item v-if="hasPermission('changes:dimission:view')&&-->
<!--                                              (scope.row.vettingStatus === '4'||scope.row.vettingStatus === '5'||scope.row.vettingStatus === '6'||scope.row.vettingStatus === '7')"-->
<!--                                    :command="{method:'auditDetail', row:scope.row}">-->
<!--                    离职审批结果-->
<!--                  </el-dropdown-item>-->
                  <el-dropdown-item v-if="hasPermission('changes:dimission:view')&&
                                              (scope.row.vettingStatus === '4')"
                                    :command="{method:'auditReback', row:scope.row}">
                    撤销离职审批
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </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>
    <!-- 弹窗, 新增 / 修改 -->
    <component is="DimissionForm"  ref="dimissionForm" @refreshDataList="refreshList"></component>
    <component is="DimissionHandoverFormDialog"  ref="dimissionHandoverFormDialog" @refreshDataList="refreshList"></component>
  </div>
</template>

<script>
  import DimissionService from '@/api/changes/dimission/DimissionService'
  import DimissionForm from './DimissionForm'
  import DimissionHandoverFormDialog from './DimissionHandoverFormDialog'
  import TaskService from '@/api/flowable/TaskService'
  import ProcessService from '@/api/flowable/ProcessService'
  import DimissionHandoverService from '@/api/changes/dimission/DimissionHandoverService'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import RosterSelectForm from '@/views/common/RosterSelectForm'
  import pick from 'lodash.pick'
  export default {
    data () {
      return {
        searchForm: {
          rosterId: '',
          rosterBaseDTO: {
            name: '',
            officeId: '',
            mobile: ''
          }
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPag1e: 1,
          pageSize: 10,
          orders: []
        },
        loading: false,
        processDefinitionId: '',
        procDefKey: '',
        processDefinitionAuditId: '',
        procDefAuditKey: ''
      }
    },
    dimissionService: null,
    taskService: null,
    processService: null,
    dimissionHandoverService: null,
    created () {
      this.dimissionService = new DimissionService()
      this.taskService = new TaskService()
      this.processService = new ProcessService()
      this.dimissionHandoverService = new DimissionHandoverService()
    },
    computed: {
      userName () {
        return JSON.parse(localStorage.getItem('user')).name
      }
    },
    components: {
      DimissionForm,
      DimissionHandoverFormDialog,
      SelectTree,
      RosterSelectForm
    },
    activated () {
      this.refreshList()
    },
    methods: {
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.dimissionService.list({
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          ...this.searchForm
        }).then(({data}) => {
          this.dataList = data.records
          this.tablePage.total = data.total
          this.loading = false
        })
        this.processService.getByName('离职归档交接审批').then(({data}) => {
          if (!this.commonJS.isEmpty(data.id)) {
            this.processDefinitionId = data.id
            this.procDefKey = data.key
          }
        })
        this.processService.getByName('离职审批').then(({data}) => {
          if (!this.commonJS.isEmpty(data.id)) {
            this.processDefinitionAuditId = data.id
            this.procDefAuditKey = data.key
          }
        })
      },
      // 当前页
      currentChangeHandle ({ currentPage, pageSize }) {
        this.tablePage.currentPage = currentPage
        this.tablePage.pageSize = pageSize
        this.refreshList()
      },
      // 排序
      sortChangeHandle (column) {
        this.tablePage.orders = []
        if (column.order != null) {
          this.tablePage.orders.push({column: this.$utils.toLine(column.property), asc: column.order === 'asc'})
        }
        this.refreshList()
      },
      // 新增
      add () {
        this.$refs.dimissionForm.init('add', '')
      },
      // 修改
      edit (id) {
        id = id || this.$refs.dimissionTable.getCheckboxRecords().map(item => {
          return item.id
        })[0]
        this.$refs.dimissionForm.init('edit', id)
      },
      // 查看
      view (id) {
        this.$refs.dimissionForm.init('view', id)
      },
      // 确认离职
      sure (id) {
        this.$refs.dimissionForm.init('sure', id)
      },
      // 发起工作交接审批
      handover (row) {
        // this.$refs.dimissionHandoverFormDialog.init('handover', id)
        // 读取流程表单
        let title = `发起流程【离职归档交接审批】`
        let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [\`` + row.rosterBaseDTO.name + `\`的离职归档交接审批]`
        let status = 'startAndHold'
        if (row.handoverStatus === '5' || row.handoverStatus === '6') {
          status = 'startAndClose'
        }
        this.taskService.getTaskDef({ procDefId: this.processDefinitionId,
          businessId: row.id,
          businessTable: 'changes_dimission'}).then((data) => {
            this.$router.push({
              path: '/flowable/task/TaskForm',
              query: {
                procDefId: this.processDefinitionId,
                procDefKey: this.procDefKey,
                title: title,
                formType: data.data.formType,
                formUrl: data.data.formUrl,
                formTitle: processTitle,
                businessTable: 'changes_dimission',
                businessId: row.id,
                isShow: 'false',
                status: status,
                routePath: '/changes/dimission/DimissionList'
              }
            })
          })
      },
      // 查看交接审批流程结果
      handoverDetail (row) {
        // eslint-disable-next-line eqeqeq
        if (!this.commonJS.isEmpty(row.status)) {
          this.taskService.getTaskDef({
            procInsId: row.procInsId,
            procDefId: this.processDefinitionId
          }).then(({data}) => {
            this.$router.push({
              path: '/flowable/task/TaskFormDetail',
              query: {
                status: 'reback',
                isShow: 'false',
                readOnly: true,
                title: '离职归档交接审批' + '流程详情',
                formTitle: '离职归档交接审批' + '流程详情',
                businessId: row.id,
                ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'title', 'businessId')
              }
            })
          })
        }
      },
      // 撤回工作交接审批
      handoverReback (row) {
        this.$confirm(`确定要撤回该申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.processService.revokeProcIns(row.procInsId).then(({data}) => {
            let form = {handoverStatus: '6', id: row.id}
            this.dimissionHandoverService.updateStatusById(form)
            this.$message.success(data)
            this.refreshList()
          })
        })
      },
      // 发起离职审批
      audit (row) {
        // 读取流程表单
        let title = `发起流程【离职审批】`
        let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [\`` + row.rosterBaseDTO.name + `\`的离职审批]`
        let status = 'startAndHold'
        if (row.vettingStatus === '5' || row.vettingStatus === '7') {
          status = 'startAndClose'
        }
        this.taskService.getTaskDef({ procDefId: this.processDefinitionAuditId,
          businessId: row.id,
          businessTable: 'changes_dimission_audit'}).then((data) => {
            this.$router.push({
              path: '/flowable/task/TaskForm',
              query: {
                procDefId: this.processDefinitionAuditId,
                procDefKey: this.procDefAuditKey,
                title: title,
                formType: data.data.formType,
                formUrl: data.data.formUrl,
                formTitle: processTitle,
                businessTable: 'changes_dimission_audit',
                businessId: row.id,
                isShow: 'false',
                status: status,
                routePath: '/changes/dimission/DimissionList'
              }
            })
          })
      },
      // 查看离职审批流程结果
      auditDetail (row) {
        // eslint-disable-next-line eqeqeq
        if (!this.commonJS.isEmpty(row.vettingStatus)) {
          this.taskService.getTaskDef({
            procInsId: row.changesDimissionAuditDTO.procInsId,
            procDefId: this.processDefinitionAuditId
          }).then(({data}) => {
            this.$router.push({
              path: '/flowable/task/TaskFormDetail',
              query: {
                isShow: 'false',
                readOnly: true,
                title: '离职审批' + '流程详情',
                formTitle: '离职审批' + '流程详情',
                businessId: row.id,
                status: 'reback',
                ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'title', 'businessId')
              }
            })
          })
        }
      },
      // 撤回离职审批
      auditReback (row) {
        this.$confirm(`确定要撤回该申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.processService.revokeProcIns(row.changesDimissionAuditDTO.procInsId).then(({data}) => {
            let form = {vettingStatus: '7', id: row.id}
            this.dimissionService.updateVettingStatusById(form)
            this.$message.success(data)
            this.refreshList()
          })
        })
      },
      // 删除
      del (id) {
        let ids = id || this.$refs.dimissionTable.getCheckboxRecords().map(item => {
          return item.id
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.dimissionService.delete(ids).then(({data}) => {
            this.$message.success(data)
            this.refreshList()
            this.loading = false
          })
        })
      },
      resetSearch () {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      },
      // 把字符串集合用‘，’拼接
      getDimissionReaList (list) {
        let str = ''
        list.forEach(item => {
          str += this.$dictUtils.getDictLabel('dimission_reason', item.dimissionReason) + ','
        })
        if (str.length > 0) {
          str = str.substr(0, str.length - 1)
        }
        return str
      },
      handleCommand (command) {
        if (command.method === 'view') {
          this.view(command.id)
        } else if (command.method === 'edit') {
          this.edit(command.id)
        } else if (command.method === 'del') {
          this.del(command.id)
        } else if (command.method === 'sure') {
          this.sure(command.id)
        } else if (command.method === 'removeSure') {
          this.removeSure(command.row)
        } else if (command.method === 'handover') {
          this.handover(command.row)
        } else if (command.method === 'handoverDetail') {
          this.handoverDetail(command.row)
        } else if (command.method === 'audit') {
          this.audit(command.row)
        } else if (command.method === 'auditDetail') {
          this.auditDetail(command.row)
        } else if (command.method === 'auditReback') {
          this.auditReback(command.row)
        } else if (command.method === 'handoverReback') {
          this.handoverReback(command.row)
        }
      },
      async removeSure (row) {
        this.loading = true
        if (row.vettingStatus !== '6' && row.vettingStatus !== '4') {
          let obj = {id: row.id, vettingStatus: '1'}
          await this.dimissionService.updateVettingStatusById(obj)
        }
        let object = {id: row.id, handoverStatus: '1'}
        await this.dimissionHandoverService.updateStatusById(object)
        await this.dimissionService.updateStatus(row.id).then(() => {
          this.refreshList()
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      }
    }
  }
</script>
