<template>
  <div>
    <Modal
      v-drag
      v-model="showModal"
      title="流程启动表单"
      width="1000px"
    >
      <div>
        <DesignFormView ref="form" :processId="processId"/>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </Modal>
  </div>
</template>

<script>
import { processInstance } from '../../../api'
import DesignFormView from './DesignFormView'

/**
 * 流程中配置的启动表单
 */
export default {
  name: 'Index',
  components: { DesignFormView },
  data() {
    return {
      showModal: false,
      processDefinitionId: '',
      processId: '', // 临时
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '发起', type: 'primary' }
      ]
    }
  },
  methods: {
    _open(data, id) {
      this.showModal = true
      this.processDefinitionId = id
      this.processId = id + new Date().getTime()
      this._hideLoading()
      if (data.renderedStartForm) {
        this._initForm(JSON.parse(data.renderedStartForm))
      }
    },
    _initForm(data) {
      this.$nextTick(() => {
        this.$refs.form._open(data)
      })
    },
    // modal
    _footerResult(name) {
      switch (name) {
        case '取消':
          this.showModal = false
          break
        case '发起':
          this._ok()
          break
      }
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _ok: async function() {
      const obj = {
        processDefinitionId: this.processDefinitionId,
        values: {}
      }
      // 填写的表单数据
      const formObj = this.$refs.form.formObj
      formObj.processDefinitionId = this.processId
      obj.values = formObj
      // 验证必填项
      const formList = this.$refs.form.formList
      for (let i = 0; i < formList.length; i++) {
        const item = formList[i]
        if (item.required && !formObj[item.vModel]) {
          this.$message.error(item.label + '不能为空~')
          this._hideLoading()
          return false
        }
      }
      const result = await processInstance.start(obj)
      if (result) {
        this.$message.success('发起成功,请到系统管理进行审批')
        this.showModal = false
        this.$emit('on-result-change')
      }
      this._hideLoading()
    }
  }
}
</script>
