<template>
  <!-- 选择领导代审批,发起人弹窗 -->
  <el-dialog
    :title="dialogTitle"
    :visible.sync="leaderDialogVisible"
    :before-close="handleLeaderDialogClose"
    :close-on-click-modal="false"
    append-to-body
    width="30%"
    custom-class="leader-dialog"
  >
    <el-form data-vv-scope="leaderForm">
      <ht-form-item>
        <el-select
          v-model="selectLeaderId"
          validate="required"
          placeholder="请选择"
        >
          <el-option
            v-for="item in leaderList"
            v-show="!(!hasStartRight && item.id == '0' && item.type == 'user')"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </ht-form-item>
      <ht-form-item class="dialog-footer__btns">
        <el-button type="primary" @click="submitLeader">
          {{ $t('Common.Confirm') }}
        </el-button>
        <el-button @click="handleLeaderDialogClose">
          {{ $t('Common.Cancel') }}
        </el-button>
      </ht-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
  import { mapState } from 'vuex'
  import { validObject } from '@/utils'
  import { checkStartRight, getMainByDefIdOrKey } from '@/api/process'
  const HANDLE_JUMPS_EVENTS_MAP = {
    SHARE: 'handleShareOrBackShareJumps',
    BACKSHARE: 'handleShareOrBackShareJumps',
    AGENT: 'handleAgentJumps',
    FOLLOW: 'handleFollowJumps',
  }
  export default {
    name: 'LeaderDialog',
    props: {
      dialogTitle: {
        type: String,
        default: '选择代审批领导',
      },
    },
    data() {
      return {
        leaderDialogVisible: false,
        selectLeaderId: '',
        leaderList: [],
        id: '', //当前点击流程id
        isNewProcess: '',
        isFromBatch: false,
        isFromLeaderTodo: false,
        hasStartRight: false,
        defId: '',
      }
    },
    computed: {
      ...mapState('user', ['userInfo']),
      userId() {
        return this.userInfo?.user?.userId
      },
    },
    watch: {
      id: {
        handler(val) {
          if (val) {
            this.initData()
          } else {
            this.hasStartRight = false
          }
        },
        immediate: true,
      },
    },
    methods: {
      //选择领导后跳转
      submitLeader() {
        if (!this.selectLeaderId)
          return this.$message.warning('请选择代为审批的领导')
        const routerQuery = {
          taskId: this.id,
          leaderId: this.selectLeaderId,
        }
        if (this.isNewProcess) {
          // 获取流程的主版本发起。
          getMainByDefIdOrKey(this.id).then((resp) => {
            let defId = this.id
            if (resp && resp.id) {
              defId = resp.id
            }
            this.$router.push({
              path: '/matter/startProcess',
              query: {
                defId: defId,
                leaderId: this.selectLeaderId,
                __isFull__: false,
              },
            })
          })
        } else {
          const url = `/matter/approvalForm?taskId=${this.id}&leaderId=${this.selectLeaderId}`
          this.isFromBatch
            ? this.openNewPage(url)
            : this.handleJumps(routerQuery)
        }
        this.leaderDialogVisible = false
      },
      openLeaderDialog() {
        this.leaderDialogVisible = true
      },
      getIsFromLeaderTodo() {
        return this.isFromLeaderTodo
      },
      //处理根据不同任务状态跳转对应页面
      handleJumpsTodoPage(data, extraQuery = {}, replace) {
        const query = {
          taskId: data.id,
          instId: data.procInstId,
          leaderId: data.leaderIds,
          ...extraQuery,
        }
        this.isFromLeaderTodo = extraQuery.key === 'leaderTodo'
        this.isFromBatch = extraQuery.key === 'notAuth'
        const url = `/matter/approvalForm?taskId=${data.id}&leaderId=${data.leaderIds}&isGetApprovalBtn=true`
        this[HANDLE_JUMPS_EVENTS_MAP[data.status]]?.(data) || this.isFromBatch
          ? this.openNewPage(url)
          : this.handleJumps(validObject(query), replace)
      },
      //处理共享和驳回共享跳转
      handleShareOrBackShareJumps(data) {
        this.defId = data.procDefId
        this.id = data.id
        if (data.identityList && data.identityList.length == 1) {
          const routerQuery = {
            taskId: data.id,
            leaderId: data.identityList[0].id,
          }
          const url = `/matter/approvalForm?taskId=${data.id}&leaderId=${data.identityList[0].id}&isGetApprovalBtn=true`
          this.isFromBatch
            ? this.openNewPage(url)
            : this.handleJumps(routerQuery)
        } else {
          this.leaderList = data.identityList
          //打开选择领导代审批弹窗
          this.leaderDialogVisible = true
        }
      },
      //处理委托任务跳转
      handleAgentJumps(data) {
        const { ownerId, assigneeId, procInstId } = data
        if (ownerId && !assigneeId && ownerId === this.userId) {
          const routerQuery = {
            instId: procInstId,
          }
          const url = `/matter/approvalForm?instId=${procInstId}`
          this.isFromBatch
            ? this.openNewPage(url)
            : this.handleJumps(routerQuery)
        }
      },
      //处理跟踪任务
      handleFollowJumps(data) {
        const url = `/matter/approvalForm?taskId=${
          data.id
        }&isGetApprovalBtn=${true}`
        this.isFromBatch ? this.openNewPage(url) : this.$router.push(url)
      },
      //处理新建流程可选择发起人时跳转
      async handleNewProcessJumps(data) {
        this.id = data.id
        let response = await checkStartRight(this.userId, data.id, '')
        if (response.state) {
          this.hasStartRight = response.value
        }
        this.isNewProcess = true
        if (data.leaders && data.leaders.length > 0) {
          this.leaderList = data.leaders
          this.leaderDialogVisible = true
        } else {
          let resp = await getMainByDefIdOrKey(this.id)
          let defId = data.id
          // 获取流程的主版本发起。
          if (resp && resp.id) {
            defId = resp.id
          }
          this.$router.push({
            path: '/matter/startProcess',
            query: {
              defId: defId,
              name: data.name,
            },
          })
        }
      },
      initData() {
        if (this.defId) {
          // 判断发起权限
          checkStartRight(this.userId, this.defId, '').then((response) => {
            if (response.state) {
              this.hasStartRight = response.value
            }
          })
        }
      },
      handleJumps(query, replace) {
        const _route = {
          path: '/matter/approvalForm',
          query: {
            ...query,
          },
        }
        if (replace) {
          this.$tabs.replace(_route)
        } else {
          this.$router.push(_route)
        }
      },
      openNewPage(url) {
        window.open(url, '_blank')
      },
      //关闭选择领导弹窗
      handleLeaderDialogClose() {
        this.leaderDialogVisible = false
      },
    },
  }
</script>

<style lang="scss" scoped>
  .leader-dialog {
    .dialog-footer__btns {
      ::v-deep .el-form-item__content {
        text-align: right;
      }
    }
  }
</style>
