<template>
  <!-- 选择领导代审批,发起人弹窗 -->
  <van-popup
    v-model="LeaderPopupVisible"
    position="bottom"
    get-container="body"
    round
  >
    <van-picker
      show-toolbar
      :title="dialogTitle"
      :columns="leaderList"
      value-key="name"
      @cancel="handleLeaderPopupClose"
      @confirm="submitLeader"
    />
  </van-popup>
</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: 'LeaderPopup',
    props: {
      dialogTitle: {
        type: String,
        default: '选择代审批领导',
      },
    },
    data() {
      return {
        LeaderPopupVisible: 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(e) {
        this.selectLeaderId = e.id
        if (!this.selectLeaderId)
          return this.$notify({
            type: 'danger',
            message: '请选择代为审批的领导',
          })
        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.LeaderPopupVisible = false
      },
      openLeaderPopup() {
        this.LeaderPopupVisible = 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.LeaderPopupVisible = 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.LeaderPopupVisible = 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')
      },
      //关闭选择领导弹窗
      handleLeaderPopupClose() {
        this.LeaderPopupVisible = false
      },
    },
  }
</script>

<style lang="scss" scoped></style>
