<template>
  <van-popup
    v-model="dialogVisible"
    position="bottom"
    class="ibps-fullscreen-popup"
    @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">
        <ibps-radio
          v-if="action === 'revoke'"
          v-model="backHandMode"
          :options="backHandModeOptions"
          label="返回方式"
          placeholder="请选择"
          clearable
          required
          :rules="[{ required: true, message: '必填' }]"
        />

        <approval-opinion
          v-if="!hideOpinion"
          v-model="approve.opinion"
          :action="action"
          :label="opinionLabel"
          :required="opinionRequired"
          :rules="opinionRequired?[{ required: true, message: '必填' }]:null"
        />
      </van-form>
      <ibps-toolbar
        v-if="$utils.isNotEmpty(toolbars)"
        :actions="toolbars"
      />
    </div>
  </van-popup>
</template>

<script>
import { doEndProcess, agreeBatch, revoke } 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: {
    ApprovalOpinion,
    IbpsToolbar
  },
  props: {
    className: String,
    visible: Boolean,
    action: String,
    title: String,
    taskId: String,
    data: [String, Object],
    hideOpinion: { // 隐藏意见
      type: Boolean,
      default: false
    },
    formOpinion: { // 表单意见
      type: String
    },
    sameTitleName: { // 标题和按钮名称相同
      type: Boolean,
      default: false
    },
    callbackEvent: { // 是否回调事件，还是默认的方法
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogLoading: true,
      formName: 'form',
      backHandMode: 'normal',
      backHandModeOptions: [{
        value: 'normal',
        label: '按流程图执行'
      }, {
        value: 'direct',
        label: '回到本节点'
      }],
      defaultForm: {},
      approve: {
        opinion: ''
      },
      opinionRequired: false

    }
  },
  computed: {
    actionTitle() {
      if (this.title) {
        return this.title
      }
      let title = '审批流程'
      switch (this.action) {
        case 'agree':
          title = '批量同意审批'
          break
        case 'endProcess':
          title = '终止流程'
          break
        case 'stop':
          title = '批量终止流程'
          break
        case 'revoke':
          title = '撤销'
          break
        default:
          break
      }
      return title
    },
    buttonLabel() {
      if (this.sameTitleName) {
        return this.actionTitle
      }
      let label = '保存'
      switch (this.action) {
        case 'agree':
          label = '同意'
          break
        case 'endProcess':
        case 'stop':
          label = '终止'
          break
        case 'revoke':
          label = '撤销'
          break
        default:
          break
      }
      return label
    },
    opinionLabel() {
      let label = '审批意见'
      switch (this.action) {
        case 'agree':
          label = '审批意见'
          break
        case 'endProcess':
        case 'stop':
          label = '终止原因'
          break
        case 'revoke':
          label = '撤销原因'
          break
        default:
          break
      }
      return label + ':'
    },
    toolbars() {
      if (!this.action) {
        return []
      }
      return [{
        'name': this.buttonLabel,
        'type': 'primary',
        'callback': this.handleSave
      }]
    }
  },
  watch: {
    visible: {
      handler: function(val, oldVal) {
        this.dialogVisible = this.visible
      },
      immediate: true
    }
  },
  created() {
    this.defaultForm = JSON.parse(JSON.stringify(this.approve))
  },
  methods: {
    closeDialog() {
      this.$emit('close', false)
    },
    /**
     * 加载常用语
     */
    loadCommonStatment() {
      this.dialogLoading = true
      let action = this.action
      if (action === 'endProcess' || action === 'stop') {
        action = 'manualend'
      }
      queryIncludeNull(
        ActionUtils.formatParams({
          'Q^ACTION_^S': action,
          'Q^CREATE_BY_^S': this.$store.getters.userId
        })).then(response => {
        this.dialogLoading = false
        const data = response.variables !== {} && response.variables.def ? response.variables.def.value : ''
        this.approve.opinion = data
      }).catch(() => {
        this.dialogLoading = false
      })
    },
    /**
     * 获取表单数据
     */
    getFormData() {
      this.loadCommonStatment()
      if (this.$utils.isEmpty(this.formId)) {
        // 重置表单
        if (this.action === 'agree') {
          this.opinionRequired = false
        } else {
          this.opinionRequired = true
        }
        this.approve = JSON.parse(JSON.stringify(this.defaultForm))
        this.formValidate()
      }
    },
    /**
     * 表单验证
     */
    formValidate() {
      this.$nextTick(() => {
        this.$refs[this.formName] ? this.$refs[this.formName].validate().then(() => {}).catch(() => {}) : null
      })
    },
    // 保存数据
    handleSave() {
      this.$refs[this.formName].validate().then(() => {
        this.saveData()
      }).catch((e) => {
        console.error(e)
        ActionUtils.saveErrorMessage()
      })
    },
    // 提交保存数据
    saveData() {
      if (this.callbackEvent) {
        this.$emit('action-event', this.action, {
          opinion: this.approve.opinion
        })
        return
      }

      switch (this.action) {
        case 'agree':
          this.agreeBatch()
          break
        case 'endProcess':
        case 'stop':
          this.doEndProcess()
          break
        case 'revoke':
          this.revoke()
          break
        default:
          break
      }
    },
    /**
     * 批量同意
     */
    agreeBatch() {
      agreeBatch({
        taskIds: this.taskId,
        opinion: this.approve.opinion
      }).then(response => {
        this.callback(response)
      }).catch((err) => {
        console.error(err)
      })
    },
    /**
     * 批量终止
     */
    doEndProcess() {
      doEndProcess({
        taskId: this.taskId,
        endReason: this.approve.opinion
      }).then(response => {
        this.callback(response)
      }).catch((err) => {
        console.error(err)
      })
    },
    /**
     * 撤销任务
     */
    revoke() {
      revoke({
        taskId: this.taskId,
        backHandMode: this.backHandMode,
        opinion: this.approve.opinion
      }).then(response => {
        this.callback(response)
      }).catch((err) => {
        console.error(err)
      })
    },
    callback(response) {
      this.$emit('callback', this)
      this.$notify({
        type: 'success',
        message: response.message
      })
      this.closeDialog()
    }
  }
}
</script>
