<template>
  <van-popup
    v-model="dialogVisible"
    class="ibps-fullscreen-popup"
    position="bottom"
    @opened="getFormData"
  >
    <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">
        <van-cell-group>
          <ibps-radio
            v-if="action=='reject'"
            v-model="form.rejectMode"
            :options="rejectOptions"
            label="驳回方式"
            placeholder="请选择"
            clearable
            required
            :rules="[{ required: true, message: '必填' }]"
            @change="changeBackHandMode"
          />
          <ibps-radio
            v-if="action==='reject'||action==='rejectToStart'"
            v-model="form.backHandMode"
            :options="backOptions"
            label="返回方式"
            placeholder="请选择"
            clearable
            required
            :rules="[{ required: true, message: '必填' }]"
            @change="changeBackHandMode"
          />
          <ibps-radio
            v-if="form.rejectMode=='rejectDest'"
            v-model="form.destination"
            :options="userNodeOptions"
            value-key="nodeId"
            label-key="name"
            label="驳回到节点"
            placeholder="请选择"
            clearable
            required
            :rules="[{ required: true, message: '必填' }]"
          />
          <approval-opinion
            v-if="!hideOpinion"
            v-model="form.opinion"
            :action="action"
            label="审批意见"
            :required="opinionRequired"
            :rules="opinionRequired?[{ required: true, message: '必填' }]:null"
          />
        </van-cell-group>
      </van-form>

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

<script>
import { toRejectToPrevious, toRejectToStart, toReject } from '@/api/platform/bpmn/bpmTask'
import { queryIncludeNull } from '@/api/platform/bpmn/bpmCommonStatment'
import ActionUtils from '@/utils/action'

import ApprovalOpinion from '@/business/platform/bpmn/components/approval-opinion'
import IbpsToolbar from '@/components/ibps-toolbar'

export default {
  components: {
    IbpsToolbar,
    ApprovalOpinion
  },
  props: {
    className: String,
    visible: Boolean,
    action: String,
    title: String,
    taskId: String,
    data: [String, Object],
    hideOpinion: { // 隐藏意见
      type: Boolean,
      default: false
    },
    formOpinion: { // 表单意见
      type: String
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      dialogLoading: true,
      formName: 'form',
      actionName: '',
      userNodeList: [],
      bpmExecUserNode: [],
      bpmExecGoMapUserNode: [],
      form: {
        rejectMode: 'reject',
        backHandMode: 'direct',
        destination: '',
        opinion: ''
      },
      rejectOptions: [{
        label: '驳回上一步',
        value: 'reject'
      }, {
        label: '驳回指定节点',
        value: 'rejectDest'
      }],
      backOptions: [{
        label: '回到本节点',
        value: 'direct'
      }, {
        label: '按流程图执行',
        value: 'normal'
      }],
      rules: {
        destination: [{ required: true, message: this.$t('validate.required') }],
        opinion: [{ required: true, message: this.$t('validate.required') }]
      },
      actions: [],
      opinionRequired: true

    }
  },
  computed: {
    actionTitle() {
      if (this.title) {
        return this.title
      }
      if (this.actionName === 'rejectToPrevious') {
        return '驳回上一步'
      } else if (this.actionName === 'rejectToStart') {
        return '驳回发起人'
      } else if (this.actionName === 'reject') {
        return '驳回审批'
      } else {
        return '驳回'
      }
    },
    buttonLabel() {
      return this.actionTitle
    },
    toolbars() {
      if (!this.action) {
        return []
      }
      return [{
        'name': this.buttonLabel,
        'type': 'primary',
        'callback': this.handleSave
      }]
    },
    userNodeOptions() {
      if (this.$utils.isEmpty(this.userNodeList)) {
        return []
      }
      return this.userNodeList
    }
  },
  watch: {
    visible: {
      handler: function(val, oldVal) {
        this.dialogVisible = this.visible
        this.actionName = this.action
      },
      immediate: true
    }
  },
  methods: {
    openedDialog() {
      if (this.$utils.isNotEmpty(this.formOpinion)) {
        this.form.opinion = this.formOpinion
      } 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
          }
        })
      }
    },
    changeBackHandMode() {
      if (this.actionName === 'reject' && this.form.rejectMode === 'rejectDest') {
        this.formValidate()
        this.userNodeList = this.form.backHandMode === 'normal' ? this.bpmExecGoMapUserNode : this.bpmExecUserNode
      }
    },
    closeDialog() {
      this.form.opinion = ''
      this.$emit('close', false)
      this.dialogLoading = true
    },
    handleSave() {
      this.$refs[this.formName].validate().then(() => {
        this.$emit('action-event', this.action, this.form)
      }).catch(() => {
        ActionUtils.saveErrorMessage()
      })
    },
    /**
     * 表单验证
     */
    formValidate() {
      this.$nextTick(() => {
        this.$refs[this.formName] ? this.$refs[this.formName].validate(() => {}).catch(() => {}) : null
      })
    },
    getFormData() {
      this.dialogLoading = true
      this.openedDialog()
      switch (this.actionName) {
        case 'reject': // 驳回
          toReject({
            taskId: this.taskId
          }).then(response => {
            this.dialogLoading = false
            this.formValidate()
            const data = response.data
            this.userNodeList = this.bpmExecUserNode = data.bpmExecUserNode
            this.bpmExecGoMapUserNode = data.bpmExecGoMapUserNode
          }).catch(() => {
            this.dialogLoading = false
          })
          break
        case 'rejectToPrevious': // 驳回上一步
          toRejectToPrevious({
            taskId: this.taskId
          }).then(response => {
            this.dialogLoading = false
            this.formValidate()
            // TODO:默认意见
          }).catch(() => {
            this.dialogLoading = false
          })
          break
        case 'rejectToStart':
          toRejectToStart({
            taskId: this.taskId
          }).then(response => {
            this.dialogLoading = false
            this.formValidate()
            // TODO:默认意见
          }).catch(() => {
            this.dialogLoading = false
          })
          break
        default:
          break
      }
    }
  }

}
</script>
