<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 { getProcessForm, startProcess } from '@/api/workflow/process'
import Parser from '@/utils/generator/parser'
import { addPlan, findLatestDeploymentTimeIndex } from '@/api/scientific/project_application_plan'


export default {
  name: 'planApply',
  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() {
      this.handbook = this.$route.params && this.$route.params.handbook;

      /** 查询流程定义列表 */
      listProcess(this.queryParams).then(response => {
        findLatestDeploymentTimeIndex(response).then((latestIndex) => {
          this.processParams = response.rows[latestIndex];
          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 planData = data.valData;
          planData.planProcId = res.msg;
          // zqjia:默认刚录入指南时状态为审核中，但后端会改为未审核
          planData.planStatus = 1;
          // zqjia:现在表单里的日期选择没有精确到小时，所以需要处理日期格式，后续要去掉
          const date1 = new Date(planData.projectAppStTime);
          const date2 = new Date(planData.projectAppEndTime);
          planData.projectAppStTime = this.formatDateTime(date1);
          planData.projectAppEndTime = this.formatDateTime(date2);
          const date3 = new Date(planData.reviewStTime);
          const date4 = new Date(planData.reviewEndTime);
          planData.reviewStTime = this.formatDateTime(date3);
          planData.reviewEndTime = this.formatDateTime(date4);
          // zqjia:解析planFile，不然无法存到数据库中
          const files = planData.planFile;
          if (files !== null) {
            let formatedFiles = {};
            files.forEach(file => {
              if(file.response.code === 200 && file.ossId) {
                formatedFiles[file.name] = file.ossId;
              }
            })
            planData.planFile = JSON.stringify(formatedFiles);
          }

          if (this.handbook !== undefined) {
            planData.handbookId = this.handbook.handbookId
          }

          addPlan(JSON.stringify(planData)).then(resp => {
            if (res.code !== 200) {
              this.$modal.msgError("操作失败");
              return;
            }
            this.$modal.msgSuccess(resp.msg);
            this.$tab.closeOpenPage({
              // zqjia:这个路径由菜单管理里设置的路由决定
              path: '/scientific/project_application_plan/list'
            })
          });
        })
      }
    },
    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>
