<template>
  <view class="page">
    <!-- 顶部页签 -->
    <l-nav v-model="tab" :items="['表单信息', '流程信息']" type="flex" class="solid-bottom" />

    <!-- 表单区 -->
    <view v-if="ready && tab === 0" class="form">
      <!-- 表单内容 -->
      <l-datetime-picker
        @input="setValue('lr_demo_formleave.F_Begin', $event)"
        :value="getValue('lr_demo_formleave.F_Begin')"
        :disabled="!edit"
        title="开始日期"
        required
      />
      <l-datetime-picker
        @input="setValue('lr_demo_formleave.F_End', $event)"
        :value="getValue('lr_demo_formleave.F_End')"
        :disabled="!edit"
        title="结束日期"
        required
      />
      <l-input
        @input="setValue('lr_demo_formleave.F_Num', $event)"
        :value="getValue('lr_demo_formleave.F_Num')"
        :disabled="!edit"
        title="请假天数"
        required
      />
      <l-textarea
        @input="setValue('lr_demo_formleave.F_Reason', $event)"
        :value="getValue('lr_demo_formleave.F_Reason')"
        :readonly="!edit"
        title="请假理由"
      />

      <!-- 流程标题与优先级 -->
      <view v-if="['child', 'create', 'draft', 'again'].includes(type)" class="lr-hidden" style="margin-top: 15px;">
        <l-input v-if="needTitle" v-model="title" title="流程标题" placeholder="请为流程设置一个标题" required />
        <l-select v-model="level" :range="levelRange" title="流程优先级" placeholder="请选择一个优先级" required />
      </view>

      <!-- 表单操作区 -->
      <l-workflow-action
        @audit="audit"
        @action="action"
        :type="type"
        :currentNode="currentNode"
        :currentTask="currentTask"
      />
    </view>

    <!-- Tab #2：流程图页 -->
    <view v-if="ready && tab === 1" class="progress"><l-workflow-timeline :processList="processList" /></view>
  </view>
</template>

<script>
/**
 * 系统表单示例
 *
 */
import get from 'lodash/get'
import set from 'lodash/set'
import moment from 'moment'
import customPageMixins from '@/common/custompage.js'

export default {
  mixins: [customPageMixins],
  data() {
    return {
      // 页面参数
      tab: 0,
      edit: false,
      type: 'view',
      ready: false,

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

      code: null,
      currentTask: null,
      currentNode: null,
      processList: [],
      processId: null,
      parentProcessId: null,

      // 表单数据
      current: {},
      origin: {},

      // 表单项数据结构
      scheme: {
        lr_demo_formleave: {
          F_Begin: { type: 'datetime', title: '开始日期', verify: 'NotNull', dateformat: '1' },
          F_End: { type: 'datetime', title: '结束日期', verify: 'NotNull', dateformat: '1' },
          F_Num: {
            type: 'datetimerange',
            title: '请假天数',
            verify: 'NotNull',
            startTime: 'lr_demo_formleave.F_Begin',
            endTime: 'lr_demo_formleave.F_End'
          },
          F_Reason: { type: 'textarea', title: '请假理由' },
          F_Id: { type: 'keyValue' }
        }
      },

      // 数据源
      dataSource: {
        lr_demo_formleave: {}
      }
    }
  },

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

  methods: {
    // 页面初始化
    async init(type = 'view') {
      this.type = type
      this.LOADING('加载表单中…')

      const pageParam = this.GET_PARAM()
      this.currentTask = pageParam.currentTask
      this.currentNode = pageParam.currentNode
      this.parentProcessId = pageParam.parentProcessId
      this.processList = pageParam.logList || []

      const title = this.currentTask.F_Name || this.currentTask.F_Title || this.currentTask.F_SchemeName
      this.SET_TITLE(title)

      this.edit = ['again', 'child', 'create', 'draft'].includes(this.type)
      this.code = this.currentTask.F_Code || this.currentTask.F_SchemeCode
      this.needTitle =
        ['again', 'child', 'create', 'draft'].includes(this.type) && Number(this.currentNode.isTitle) === 1
      this.processId = this.currentTask.F_SchemeCode ? this.currentTask.F_Id : this.GUID()

      // 拉取选单数据和表单数据
      await Promise.all([() => {}])
      await this.fetchForm()

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

    // 加载表单数据
    async fetchForm() {
      // 此处处理旧版无外层表结构的表单格式
      const formData = {}
      formData.lr_demo_formleave = await this.HTTP_GET('/demo/wfsys/form', this.processId)
      // 原版：
      // const formData = await this.HTTP_GET('/demo/wfsys/form', this.processId)

      if (['again', 'child', 'create'].includes(this.type)) {
        this.origin = await this.getDefaultForm()
      } else {
        this.origin = await this.formatFormData(formData)
      }
      this.current = this.COPY(this.origin)
    },

    // 点击操作按钮（非审批类按钮）
    async action(actionType) {
      switch (actionType) {
        // 点击「催办」/「撤销流程」/「标记已阅」按钮
        case 'urge':
        case 'revoke':
        case 'refer':
          const actionText = { urge: '催办', revoke: '撤销', refer: '已阅' }[actionType]
          const actionUrl = { urge: '/urge', revoke: '/revoke', refer: '/refer' }[actionType]
          const actionData = this.processId
          if (actionType === 'refer') {
            actionData = { processId: this.processId, taskId: this.taskId }
          }

          if (!(await this.CONFIRM(`${actionText}确认`, `确定要提交${actionText}吗？`, true))) {
            return
          }

          this.LOADING(`提交${actionText}中…`)
          this.HTTP_POST(`/newwf${actionUrl}`, actionData, `提交${actionText}失败`).then(success => {
            this.HIDE_LOADING()
            if (success) {
              this.EMIT('task-list-change')
              this.TOAST(`成功提交${actionText}`, 'success')
            }
          })
          break

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

          this.LOADING('正在提交草稿…')
          const draftPostData = await this.getPostData(this.processId)
          const pdSuccess = await this.HTTP_POST('/demo/wfsys/save', draftPostData, '提交表单失败')
          if (!pdSuccess) {
            return
          }

          const draftWorkflowInfo = {
            code: this.code,
            processId: this.processId,
            formreq: JSON.stringify({})
          }
          const draftSuccess = await this.HTTP_POST('/newwf/draft', draftWorkflowInfo, '提交草稿失败')
          if (!draftSuccess) {
            return
          }

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

        // 点击「发起流程」按钮
        case 'submit':
          const verifyResult = this.verifyForm(this.scheme)
          if (verifyResult.length > 0) {
            this.CONFIRM('表单验证失败', verifyResult.join('\n'))
            return
          }

          if (!(await this.CONFIRM('提交确认', '确定要发起流程吗？', true))) {
            return
          }

          this.LOADING('正在提交…')
          const postKv = ['create'].includes(this.type) ? '' : this.processId
          const postData = await this.getPostData(postKv)
          const pSuccess = await this.HTTP_POST('/demo/wfsys/save', postData, '表单提交失败')
          if (!pSuccess) {
            return
          }

          const workflowInfo = {
            code: this.code,
            processId: this.processId,
            level: this.level,
            auditors: JSON.stringify({}),
            formreq: JSON.stringify([])
          }
          if (this.needTitle) {
            workflowInfo.title = this.title
          }
          if (this.type === 'child') {
            workflowInfo.parentProcessId = this.parentProcessId
            workflowInfo.parentTaskId = this.currentTask.F_TaskId
          }
          const postUrl = {
            create: '/newwf/create',
            draft: '/newwf/draft',
            again: '/newwf​/againcreate',
            child: '/newwf/createchildflow'
          }[this.type]
          const success = await this.HTTP_POST(postUrl, workflowInfo, '流程提交失败')
          if (!success) {
            return
          }

          this.EMIT('task-list-change')
          this.NAV_BACK()
          this.TOAST('操作成功', 'success')

          break

        default:
          break
      }
    },

    // 点击审批相关按钮
    audit(action) {
      const pageParam = {
        type: 'sign',
        processId: this.currentTask.F_Id,
        taskId: this.currentTask.F_TaskId,
        taskName: this.currentTask.F_Title,
        formreq: JSON.stringify([])
      }

      if (action.code !== '__sign__') {
        Object.assign(pageParam, action)
        pageParam.type = 'verify'
        pageParam.auditors = JSON.stringify({})
      }

      this.NAV_TO('/pages/nworkflow/myflow/sign', pageParam, true)
    },

    // 子表格删除一行
    tableDelete(tableName, index) {
      this.current[tableName].splice(index, 1)
    },

    // 子表格添加一行
    async tableAdd(tableName) {
      const newVal = {}
      for (const [fieldName, schemeItem] of Object.entries(this.scheme[tableName])) {
        if (fieldName !== '__GIRDTABLE__') {
          newVal[fieldName] = await this.getDefaultValue(`${tableName}.${fieldName}`, schemeItem)
        }
      }
      this.current[tableName].push(newVal)
    },

    // 从表弹层输入，可一次性设置多个字段
    layerSet(tableIndex, table, field, layerValue) {
      const layerData = get(this.scheme, `${table}.${field}.layerData`, [])
      layerData.forEach(({ name, value }) => {
        this.setValue(`${table}.${tableIndex}.${value}`, layerValue[name] || '')
      })
    },

    // 获取表单值
    getValue(path) {
      return get(this.current, path)
    },

    // 设置表单值
    setValue(path, val) {
      set(this.current, path, val)
    }
  }
}
</script>
