<template>
  <view class="page">
    <!-- 顶部页签 -->
    <l-nav v-model="tab" :items="['表单信息', '流程信息']" type="flex" class="solid-bottom" />
    <!-- Tab #1：表单页 -->
    <view v-if="ready && tab === 0" class="form">
      <!-- 表单 -->
      <l-customform :initFormValue="formValue" :editMode="editMode" :scheme="scheme" rel="rel" ref="form" />
      <!-- 操作区按钮 -->
      <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 pick from 'lodash/pick'
import workflowFormMixins from '../workflow.js'

export default {
  data() {
    return {
      tab: 0,
      editMode: false,
      type: 'view',
      ready: false,
      code: null,
      currentTask: null,
      taskId: null,
      processList: [],
      processId: null,
      processInfo: null,
      currentNode: null,
      scheme: [],
      formValue: {},
      rel: {}
    }
  },

  mixins: [workflowFormMixins],
  async onLoad({ type }) {
    await this.init(type)
  },
  // 小程序专有，分享任务到聊天
  // #ifdef MP
  onShareAppMessage() {
    const props = ['F_Id', 'F_Title', 'F_TaskId', 'F_ProcessId', 'F_IsStart', 'F_IsFinished', 'F_EnabledMark']
    const taskInfo = { ...pick(this.currentTask, props), mark: 'pre' }
    // 获取页面参数
    const queryString = this.MP_SHARE_ENCODE(taskInfo, { type: this.type })
    return {
      title: `${this.GET_GLOBAL('loginUser').realName}发起的${this.currentTask.F_Title}工作流程`,
      desc: '我发起了一个工作流程，快来看看吧',
      path: `pages/home?${queryString}`
    }
  },
  // #endif
  methods: {
    // 页面初始化
    async init(type = 'view') {
      // type 表示打开方式：view=查看普通流程，child=子流程，refer=审阅
      // 当前任务相关信息用 GET_PARAM 获取
      // 需要字段： F_Title、F_Id、F_TaskId、F_ProcessId、F_IsFinished、F_IsStart、F_EnabledMark
      // 需要字段： mark （是 my 或者不是，表示是否自「我的」列打开）
      this.type = type
      this.currentTask = this.GET_PARAM()
      this.LOADING('加载表单中…')
      this.SET_TITLE(this.currentTask.F_Title)
      // 未完成的子流程，可以编辑
      if (get(this.currentTask, 'mark') !== 'maked' && this.type === 'child') {
        this.editMode = true
      }
	  // 如果是代办任务是可编辑的
	  if (get(this.currentTask, 'mark') === 'pre' ) {
	    this.editMode = true
	  }
      // 获得流程信息
      this.processId = this.currentTask.F_Id
      this.taskId = this.currentTask.F_TaskId
      this.processInfo = await this.fetchProcessInfo({
        processId: this.processId,
        taskId: this.taskId
      })
	  this.currentTask = {
		  ...this.currentTask,
		  F_TaskType:(this.processInfo.task&&this.processInfo.task[0])?this.processInfo.task[0].F_Type:undefined,
	  }
      this.currentNode = this.getCurrentNode(this.processInfo)
      this.processList = get(this.processInfo, 'info.TaskLogList', [])
      // wfForms 的数组成员 t，表示表单数据项（TAB页）
      //   t.formId 使用表单，根据这个 formId 来获取 scheme 等信息
      //   t.appurl 使用移动页面，直接跳转到本地的页面；表单结构等均写死在页面里
      const { wfForms } = this.currentNode
      // 处理没有有效表单的情况，停止加载
      if (!wfForms || wfForms.every(t => !t.formId && !t.appurl)) {
        this.HIDE_LOADING()
        this.TOAST('移动表单数据(wfForms)中无有效表单')
        return
      }
	  
	  const fetchFolderkeyData=await this.fetchFolderkeyData(this.currentNode , this.processId);
	  uni.setStorageSync('guids',JSON.stringify(fetchFolderkeyData));

    //   // 处理移动端本地表单（也就是系统表单）的情况，直接跳转过去
    //   const appSysPage = wfForms.find(t => t.appurl)
    //   if (this.type !== 'child' && appSysPage) {
    //     this.sysFormJump(appSysPage.appurl, {
    //       currentNode: this.currentNode,
    //       currentTask: this.currentTask,
    //       logList: this.processList,
		  // processInfo:this.processInfo
    //     })
    //     return
    //   }
	  
      if (this.type === 'child') {
        // 发起子流程的场合
        // 获取子流程的流程信息，提取出时间线和表单模板 code
        const childProcessInfo = await this.fetchProcessInfo({ processId: this.processId })
        this.processList = get(childProcessInfo, 'info.TaskLogList', [])
        this.code = this.currentNode.childFlow

        // 提取出子流程 Id；因为是发起新的流程，所以 processInfo 只传入表单模板 code
        const childProcessId = this.processInfo.info.childProcessId
        const childCurrentNode = this.getCurrentNode(await this.fetchProcessInfo({ code: this.code }))
        // 处理系统表单跳转，使用子流程相关信息
        if (appSysPage) {
          this.sysFormJump(appSysPage.appurl, {
            currentNode: this.currentNode,
            currentTask: this.currentTask,
            parentProcessId: this.processId,
            logList: this.processList
          })
          return
        }
        const schemeData = await this.fetchSchemeData(childCurrentNode)
        const formData = await this.fetchFormData(childCurrentNode, childProcessId)
        const { formValue, scheme, rel, options } = await this.getCustomForm({
          formData,
          schemeData,
          currentNode: childCurrentNode,
          processId: childProcessId,
          code: this.code,
          useDefault: true
        })
		
		// 处理移动端本地表单（也就是系统表单）的情况，直接跳转过去
		const appSysPage = wfForms.find(t => t.appurl)
		if (this.type !== 'child' && appSysPage) {
		  this.sysFormJump(appSysPage.appurl, {
		    currentNode: this.currentNode,
		    currentTask: this.currentTask,
		    logList: this.processList,
			processInfo:this.processInfo,
			formValue,
			scheme,
		  })
		  return
		}
		
        this.scheme = scheme
        this.formValue = formValue
        this.rel = rel
      } else {
        // 不是子流程，可以直接渲染
        const schemeData = await this.fetchSchemeData(this.currentNode)
        const formData = await this.fetchFormData(this.currentNode, this.processId)
        const { formValue, scheme, rel } = await this.getCustomForm({
          formData,
          schemeData,
          currentNode: this.currentNode,
          processId: this.processId,
          code: null
        })
		
		// 处理移动端本地表单（也就是系统表单）的情况，直接跳转过去
		const appSysPage = wfForms.find(t => t.appurl)
		if (this.type !== 'child' && appSysPage) {
		  this.sysFormJump(appSysPage.appurl, {
		    currentNode: this.currentNode,
		    currentTask: this.currentTask,
		    logList: this.processList,
			processInfo:this.processInfo,
			formValue,
			scheme,
		  })
		  return
		}
		
        this.scheme = scheme
        this.formValue = formValue
        this.rel = rel
      }
      this.ready = true
      this.HIDE_LOADING()
	  
    },

    // 跳转到系统表单页面
    sysFormJump(url, param) {
      this.HIDE_LOADING()
      this.TOAST('跳转至移动端本地表单（即系统表单）')

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

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

          if (!(await this.CONFIRM(`${actionText}确认`, `确定要提交${actionText}吗？`, true))) {
            return
          }
          this.LOADING(`提交${actionText}中…`)
          this.HTTP_POST(`/learun/adms/newwf${actionUrl}`, actionData, `提交${actionText}失败`).then(success => {
            this.HIDE_LOADING()
            if (success) {
              this.EMIT('task-list-change')
              this.TOAST(`成功提交${actionText}`, 'success')
              if (taskType === 'revoke') {
                this.NAV_BACK()
              }
            }
          })
          break
        // 点击「提交草稿」按钮
        case 'draft':
          if (!(await this.CONFIRM('提交确认', '确定要提交草稿吗？', true))) {
            return
          }
          this.LOADING('正在提交…')
          const draftFormValue = this.$refs.form.getFormValue()
          const draftPostData = await this.getPostData(draftFormValue, this.scheme)
          this.HTTP_POST('/learun/adms/newwf/draft', draftPostData, '提交草稿失败').then(success => {
            this.HIDE_LOADING()
            if (success) {
              this.EMIT('task-list-change')
              this.NAV_BACK()
              this.TOAST('草稿已保存', 'success')
            }
          })
          break
        // 点击「发起流程」按钮
        case 'submit':
          const verifyResult = this.$refs.form.verifyValue()
          if (verifyResult.length > 0) {
            this.CONFIRM('表单验证失败', verifyResult.join('\n'))
            return
          }
          if (!(await this.CONFIRM('提交确认', '确定要发起流程吗？', true))) {
            return
          }
          this.LOADING('正在提交…')
          const formValue = this.$refs.form.getFormValue()
          const postData = await this.getPostData(formValue, this.scheme)
          postData.auditors = JSON.stringify({})

          if (this.type === 'child') {
            postData.parentProcessId = this.processId
            postData.parentTaskId = this.taskId
          }
          const errorTips = '流程发起失败'
          this.HTTP_POST('/learun/adms/newwf/createchildflow', postData, errorTips).then(success => {
            this.HIDE_LOADING()
            if (success) {
              this.EMIT('task-list-change')
              this.NAV_BACK()
              this.TOAST('流程发起成功', 'success')
            }
          })
          break
        default:
          break
      }
    },
    
    // 点击审批相关按钮
    async audit(action) {
      this.LOADING('加载中…')
      const currentTask = this.processInfo.task.find(t => t.F_NodeId === this.currentNode.id)
      const postData = await this.getPostData(this.formValue, this.scheme)
      const pageParam = {
        type: 'sign',
        processId: currentTask.F_ProcessId,
        taskId: currentTask.F_Id,
        formreq: postData.formreq,
        taskName: this.currentTask.F_Title,
		currentNode:this.currentNode,
		schemeCode:this.code||''
      }
      // 不是加签
      if (action.code !== '__sign__') {
        Object.assign(pageParam, action)
        pageParam.type = 'verify'
        pageParam.auditors = JSON.stringify({})
        pageParam.isFromSignAudit = Number(this.currentTask.F_TaskType) === 3
      }
      this.HIDE_LOADING()
      this.NAV_TO('./sign', pageParam, true)
    }
  }
}
</script>
