<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ processName }}</span>
      </div>

      <el-col :span="18" :offset="3">
        <div class="form-conf" v-if="formOpen">
          <parser :key="new Date().getTime()" :form-conf="formData" @submit="submit" ref="parser" @getData="getData"/>
        </div>
      </el-col>
    </el-card>
  </div>
</template>

<script>
import { listProcess, startProcess_ } from '@/api/workflow/process'
import { listAllCategory } from '@/api/workflow/category'
import { getProcessForm, startProcess } from '@/api/workflow/process'
import Parser from '@/utils/generator/parser'
import { addHandbook } from '@/api/scientific/handbook'

export default {
  name: 'handbookApply',
  components: {
    Parser
  },
  data() {
    return {
      definitionId: null,
      deployId: null,
      procInsId: null,
      formOpen: false,
      formData: {},

      processName: '',
      categoryOptions: [],
      // 流程定义表格数据
      processParams: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        processKey: undefined,
        processName: "项目指南录入",
        category: "007"
      },
    }
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      /** 查询流程定义列表 */
      listProcess(this.queryParams).then(response => {
        this.processParams = response.rows[0];
        this.processName = this.processParams.processName;
        this.definitionId = this.processParams.definitionId;

        getProcessForm({
          definitionId: this.processParams.definitionId,
          deployId: this.processParams.deploymentId,
          procInsId: undefined
        }).then(res => {
          if (res.data) {
            this.formData = res.data;
            this.formOpen = true;
          }
        })
      })
    },

    /** 接收子组件传的值 */
    getData(data) {
      if (data) {
        const variables = [];
        data.fields.forEach(item => {
          let variableData = {};
          variableData.label = item.__config__.label
          // 表单值为多个选项时
          if (item.__config__.defaultValue instanceof Array) {
            const array = [];
            item.__config__.defaultValue.forEach(val => {
              array.push(val)
            })
            variableData.val = array;
          } else {
            variableData.val = item.__config__.defaultValue
          }
          variables.push(variableData)
        })
        this.variables = variables;
      }
    },
    submit(data) {
      if (data && this.definitionId) {
        // 启动流程并将表单数据加入流程变量
        startProcess_(this.definitionId, JSON.stringify(data.valData)).then(res => {
          if (res.code !== 200) {
            this.$modal.msgError("操作失败");
            return;
          }
          let handbookData = data.valData;
          handbookData.handbookProcId = res.msg;
          // zqjia:默认刚录入指南时状态为审核中，但后端会改为未审核
          handbookData.handbookStatus = 1;
          // zqjia:现在表单里的日期选择没有精确到小时，所以需要处理日期格式，后续要去掉
          const date1 = new Date(handbookData.projectAppStTime);
          const date2 = new Date(handbookData.projectAppEndTime);
          handbookData.projectAppStTime = this.formatDateTime(date1);
          handbookData.projectAppEndTime = this.formatDateTime(date2);
          const date3 = new Date(handbookData.reviewStTime);
          const date4 = new Date(handbookData.reviewEndTime);
          handbookData.reviewStTime = this.formatDateTime(date3);
          handbookData.reviewEndTime = this.formatDateTime(date4);
          // zqjia:解析handbookFile，不然无法存到数据库中
          const files = handbookData.handbookFile;
          if (files !== null) {
            let formatedFiles = {};
            files.forEach(file => {
              if(file.response.code === 200 && file.ossId) {
                formatedFiles[file.name] = file.ossId;
              }
            })
            handbookData.handbookFile = JSON.stringify(formatedFiles);
          }

          addHandbook(JSON.stringify(handbookData)).then(resp => {
            if (res.code !== 200) {
              this.$modal.msgError("操作失败");
              return;
            }
            this.$modal.msgSuccess(resp.msg);
            this.$tab.closeOpenPage({
              // zqjia:这个路径由菜单管理里设置的路由决定
              path: '/scientific/handbookList'
            })
          });
        })
      }
    },
    formatDateTime(date) {
      const padZero = (num) => (num < 10 ? '0' + num : num);

      const year = date.getFullYear();
      const month = padZero(date.getMonth() + 1); // getMonth() 返回值的范围是 0-11，所以需要加 1
      const day = padZero(date.getDate());
      const hours = padZero(date.getHours());
      const minutes = padZero(date.getMinutes());
      const seconds = padZero(date.getSeconds());

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
}
}
</script>

<style lang="scss" scoped>
.form-conf {
  margin: 15px auto;
  width: 80%;
  padding: 15px;
}
</style>
