<template>
  <van-popup
    v-model="dialogVisible"
    class="ibps-fullscreen-popup"
    position="bottom"
    @opened="openDialog"
  >
    <div v-if="!dialogLoading" class="ibps-fixed-top">
      <van-nav-bar
        :title="actionTitle"
        fixed
        @click-left="closeDialog"
      >
        <template #left>
          <van-icon name="cross" class="ibps-nav-bar__close-icon" />
        </template>
      </van-nav-bar>
      <van-form
        ref="form"
        label-width="120px"
      >
        <!--不隐藏路径，审批意见-->
        <template v-if="noCommonJumpType">
          <ibps-checker
            v-model="form.jumpType"
            label="跳转方式"
            :options="jumpTypeOptions"
            checker
            radio-required
            label-class="ibps-pt-10"
          />
          <!--正常跳转-->
          <template v-if="form.jumpType ==='common'">
            <jump-type-common
              v-if="pathOutgoingNodes && pathOutgoingNodes.length > 0"
              ref="jumpTypeNode"
              :jump-type="form.jumpType"
              :outgoing-nodes="pathOutgoingNodes "
              :outgoing-nodes-users-map="pathOutgoingNodesUsersMap"
            />
          </template>
          <!--选择路径跳转-->
          <template v-else-if="form.jumpType ==='select'">
            <jump-type-select
              ref="jumpTypeNode"
              :jump-type="form.jumpType"
              :outgoing-nodes="outgoingNodes"
              :outgoing-nodes-users-map="outgoingNodesUsersMap"
            />
          </template>
          <!--自由跳转-->
          <template v-else-if="form.jumpType ==='free'">
            <jump-type-select
              ref="jumpTypeNode"
              :jump-type="form.jumpType"
              :outgoing-nodes="allNodeDef"
              :outgoing-nodes-users-map="allNodeDefUsersMap"
            />
          </template>
        </template>

        <approval-opinion
          v-if="!hideOpinion"
          v-model="form.opinion"
          :action="action"
          label="审批意见"
        />

      </van-form>
      <ibps-toolbar
        v-if="$utils.isNotEmpty(toolbars)"
        :actions="toolbars"
      />
    </div>
  </van-popup>
</template>
<script>

import { agreeData } from '@/api/platform/bpmn/bpmTask'
import { queryIncludeNull } from '@/api/platform/bpmn/bpmCommonStatment'
import ActionUtils from '@/utils/action'

import JumpTypeCommon from './jump-type/common'
import JumpTypeSelect from './jump-type/select'
import ApprovalOpinion from '@/business/platform/bpmn/components/approval-opinion'
import IbpsToolbar from '@/components/ibps-toolbar'

export default {
  components: {
    IbpsToolbar,
    ApprovalOpinion,
    JumpTypeCommon,
    JumpTypeSelect
  },
  props: {
    className: String,
    visible: Boolean,
    action: String,
    title: String,
    taskId: String,
    data: [String, Object],
    isCommon: {
      type: Boolean,
      default: true
    },
    hideOpinion: { // 隐藏意见
      type: Boolean,
      default: false
    },
    hidePath: { // 隐藏路径
      type: Boolean,
      default: true
    },
    formOpinion: { // 表单意见
      type: String
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      dialogLoading: true,
      formName: 'form',
      formLabelWidth: '130px',
      form: {
        jumpType: 'common',
        opinion: ''
      },
      rules: {},
      jumpTypes: {},

      pathOutgoingNodes: [],
      pathOutgoingNodesUsersMap: {},

      outgoingNodes: [],
      outgoingNodesUsersMap: {},

      allNodeDef: [],
      allNodeDefUsersMap: {}
    }
  },
  computed: {
    actionTitle() {
      if (this.title) {
        return this.title
      }
      if (this.action === 'agree') {
        return '同意'
      } else if (this.action === 'oppose') {
        return '反对'
      } else if (this.action === 'abandon') {
        return '弃权'
      } else {
        return '审批'
      }
    },
    jumpTypeLength() {
      if (this.$utils.isEmpty(this.jumpTypes)) {
        return 0
      }
      return this.jumpTypes.length
    },
    jumpTypeOptions() {
      const options = []
      if (this.$utils.isEmpty(this.jumpTypes)) {
        return []
      }
      this.jumpTypes.forEach(jumpType => {
        let label = ''
        if (jumpType === 'common') {
          label = '正常跳转'
        } else if (jumpType === 'select') {
          label = '选择路径'
        } else if (jumpType === 'free') {
          label = '自由跳转'
        }
        options.push({
          value: jumpType,
          label: label
        })
      })
      return options
    },

    noCommonJumpType() {
      return (!this.isCommon || (this.isCommon && !this.hidePath)) && (this.action === 'agree' || this.action === 'oppose')
    },
    toolbars() {
      if (!this.action) {
        return []
      }
      return [{
        'name': this.$t('common.button.' + this.action),
        'type': 'primary',
        'callback': this.handleSave
      }]
    }
  },
  watch: {
    visible: {
      handler: function(val, oldVal) {
        this.dialogVisible = this.visible
      },
      immediate: true
    }
  },
  methods: {
    closeDialog() {
      this.form.opinion = ''
      this.dialogLoading = true
      this.$emit('close', false)
    },
    parseData(value) {
      const a = Object.prototype.toString
      if (this.$utils.isNotEmpty(value) && a.call(value) === '[object String]') {
        return JSON.parse(value)
      }
      return value
    },
    openDialog() {
      this.dialogLoading = true
      let loading1 = true
      let loading2 = true
      if (this.noCommonJumpType) {
        agreeData({
          taskId: this.taskId,
          busData: JSON.stringify(this.data),
          actionName: this.action
        }).then(response => {
          const variables = response.variables || {}

          this.pathOutgoingNodes = this.parseData(variables.pathOutgoingNodes)
          this.pathOutgoingNodesUsersMap = this.parseData(variables.pathOutgoingNodesUsersMap)

          this.outgoingNodes = this.parseData(variables.outgoingNodes)
          this.outgoingNodesUsersMap = this.parseData(variables.outgoingNodesUsersMap)

          this.allNodeDef = this.parseData(variables.allNodeDef)
          this.allNodeDefUsersMap = this.parseData(variables.allNodeDefUsersMap)

          const jumpType = this.$utils.isNotEmpty(variables.jumpType) ? variables.jumpType : ''
          const jumpTypes = []

          if (jumpType.includes('common')) {
            jumpTypes.push('common')
          }
          if (jumpType.includes('select')) {
            jumpTypes.push('select')
          }
          if (jumpType.includes('free')) {
            jumpTypes.push('free')
          }

          this.jumpTypes = jumpTypes
          if (this.$utils.isNotEmpty(this.jumpTypes)) {
            this.form.jumpType = this.jumpTypes[0]
          }
          loading1 = false
          if (!loading1 && !this.loading2) {
            this.dialogLoading = false
          }
        }).catch(() => {
          loading1 = false
          if (!loading1 && !loading2) {
            this.dialogLoading = false
          }
        })
      } else {
        loading1 = false
      }

      if (this.$utils.isNotEmpty(this.formOpinion)) {
        loading2 = false
        this.form.opinion = this.formOpinion
        if (!loading1 && !this.loading2) {
          this.dialogLoading = false
        }
      } else {
        queryIncludeNull(ActionUtils.formatParams(
          {
            'Q^ACTION_^S': this.action,
            'Q^CREATE_BY_^S': this.$store.getters.userId
          })).then(response => {
          const data = response.variables && response.variables.def ? response.variables.def.value || '' : ''
          if (this.$utils.isNotEmpty(data)) {
            this.form.opinion = data
          }
          loading2 = false
          if (!loading1 && !loading2) {
            this.dialogLoading = false
          }
        }).catch(() => {
          loading2 = false
          if (!loading1 && !loading2) {
            this.dialogLoading = false
          }
        })
      }
    },

    handleSave() {
      const params = {}
      if (this.noCommonJumpType) {
        const data = this.$refs.jumpTypeNode.getData()
        if (!data) {
          return
        }
        params.jumpType = this.form.jumpType
        params.destination = data.destination
        params.nodeUsers = data.nodeUsers
      }
      if (!this.hideOpinion) {
        params.opinion = this.form.opinion
      }

      this.$emit('action-event', this.action, params)
    }
  }
}
</script>
