<template>
  <view class="page">
    <!-- 表单 -->
    <l-customform v-if="ready" :initFormValue="formValue" :scheme="scheme" :rel="rel" ref="form" />

    <!-- 设置标题和优先级 -->
    <view v-if="ready && type !== 'again'">
      <view style="height:15px"></view>
      <l-input v-if="needTitle" v-model="title" title="流程标题" placeholder="请为流程设置一个标题" required />
      <l-select v-model="level" :range="levelRange" title="流程优先级" placeholder="请选择一个优先级" required />
    </view>

    <!-- 发起流程/重新发起流程按钮 -->
    <view v-if="ready" class="padding margin-top bg-white" style="padding-top: 0; overflow: hidden;">
      <l-button v-if="type !== 'again'" @click="draft" size="lg" color="orange" class="block margin-top" block>
        保存草稿
      </l-button>
      <l-button @click="submit" size="lg" color="green" class="block margin-top" block>
        {{ type === 'again' ? `重新发起流程` : `发起流程` }}
      </l-button>
    </view>
  </view>
</template>

<script>
import get from 'lodash/get'
import workflowFormMixins from '../workflow.js'

export default {
  mixins: [workflowFormMixins],

  data() {
    return {
      ready: false,
      type: 'create',
      code: null,
      processId: '',

      formValue: {},
      scheme: [],
      rel: {},

      level: '0',
      levelRange: [{ value: '0', text: '普通' }, { value: '1', text: '重要' }, { value: '2', text: '紧急' }],
      title: '',
      needTitle: false
    }
  },

  async onLoad({ type }) {
    await this.init(type)
  },

  methods: {
    // 初始化页面
    async init(type = 'create') {
      // type 表示打开页面的方式，create=新建，draft=编辑草稿，again=重新发起
      // 新建的场合最简单，直接渲染出空的表单即可；
      // 重新发起流程/编辑草稿的场合，比新建多出一个拉取表单已经输入的内容的步骤，把内容填充到表单中；

      this.LOADING('加载表单中…')
      this.type = type
      const currentTask = this.GET_PARAM()
      const { F_Code: code, F_Id: pid } = currentTask

      // 设置页面标题
      const title = {
        create: `创建[${currentTask.F_Name}]流程`,
        draft: `编辑[${currentTask.F_Title || currentTask.F_SchemeName}]流程草稿`,
        again: `重新发起[${currentTask.F_Title}]流程`
      }[this.type]
      this.SET_TITLE(title)

      // 拉取流程信息，提取出当前节点；如果是新建表单则生成 processId
      const processId = this.type === 'create' ? this.GUID('-') : pid
      const processInfo = await this.fetchProcessInfo({ code, processId: this.type === 'create' ? null : processId })
      const currentNode = this.getCurrentNode(processInfo)

      // wfForms 的数组成员 t，表示表单数据项（TAB页），t.type 表示类别，注意它是字符串型，用 Number(t.type) 转换
      // 为 1 则使用工作流表单，依据它的 .formId
      // 不为 1 则使用系统表单，依据它的 .appurl
      const { wfForms } = currentNode

      // 处理没有有效表单的情况，停止加载
      if (!wfForms || wfForms.length <= 0) {
        this.HIDE_LOADING()
        this.TOAST('移动表单数据(wfForms)中无有效表单')
        return
      }

      // 处理移动端本地表单（也就是系统表单）的情况，直接跳转过去
      const appSysPage = wfForms.find(t => Number(t.type) !== 1)
      if (appSysPage) {
        this.HIDE_LOADING()
        this.TOAST('跳转至移动端本地表单（即系统表单）')

        let pagePath = appSysPage.appurl || ''
        if (!pagePath.startsWith('/pages')) {
          pagePath = '/pages' + pagePath
        }

        this.JUMP_TO(
          `${pagePath}?type=${this.type}`,
          { currentNode, currentTask, logList: get(processInfo, 'info.TaskLogList', []) },
          true
        )

        return
      }

      this.needTitle = this.type !== 'again' && Number(currentNode.isTitle) === 1
      const formData = await this.fetchFormData(currentNode, processId)

      const schemeData = await this.fetchSchemeData(currentNode)
      const { formValue, scheme, rel } = await this.getCustomForm({
        schemeData,
        processId,
        formData,
        currentNode: this.currentNode,
        code: this.type === 'again' ? null : code,
        useDefault: true
      })
      this.rel = rel
      this.scheme = scheme
      this.formValue = formValue

      this.code = code
      this.processId = processId

      this.ready = true
      this.HIDE_LOADING()
    },

    // 提交草稿按钮
    async draft() {
      if (!(await this.CONFIRM('提交确认', '确定要提交草稿吗？', true))) {
        return
      }

      this.LOADING('正在提交…')
      const formValue = this.$refs.form.getFormValue()
      const postData = await this.getPostData(formValue, this.scheme)

      this.HTTP_POST('/newwf/draft', postData, '提交草稿时发生失败，未能成功保存').then(success => {
        this.HIDE_LOADING()
        if (!success) {
          return
        }

        this.EMIT('task-list-change')
        this.NAV_BACK()
        this.TOAST('草稿已保存', 'success')
      })
    },

    // 发起流程按钮
    async submit() {
      const isAgain = this.type === 'again'

      // 先验证表单，验证不通过则提示
      const verifyResult = this.verifyValue()
      if (verifyResult.length > 0) {
        this.CONFIRM('表单验证失败', verifyResult.join('\n'))
        return
      }

      if (!(await this.CONFIRM('提交确认', `确定要${isAgain ? '重新' : ''}发起流程吗？`, true))) {
        return
      }

      this.LOADING('正在提交…')

      const formValue = this.$refs.form.getFormValue()
      const postData = await this.getPostData(formValue, this.scheme)
      if (this.needTitle) {
        postData.title = this.title
      }
      postData.level = this.level
      postData.auditors = JSON.stringify({})

      const url = isAgain ? '/newwf/againcreate' : '/newwf/create'
      const tips = `流程${isAgain ? '重新' : ''}发起失败`
      this.HTTP_POST(url, postData, tips).then(success => {
        this.HIDE_LOADING()
        if (!success) {
          return
        }

        this.EMIT('task-list-change')
        this.NAV_BACK()
        this.TOAST(`流程${isAgain ? '重新' : ''}发起成功`, 'success')
      })
    },

    // 获取表单验证结果，是一个包含错误信息的数组，长度为 0 则没有错误
    verifyValue() {
      const errList = this.$refs.form.verifyValue()
      if (this.needTitle && !this.title) {
        errList.push(`流程的标题不能为空`)
      }

      return errList
    }
  }
}
</script>
