<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>合作单位录入</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 {findLatestDeploymentTimeIndex } from '@/api/scientific/project_application_plan'
import { addHandbook } from '@/api/scientific/handbook'
import {addDepartment} from "@/api/scientific/department";

export default {
  name: 'departmentApply',
  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: "008"
      },
    }
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      /** 查询流程定义列表 */
      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) {
        console.log(data.valData)
        // 启动流程并将表单数据加入流程变量
        startProcess_(this.definitionId, JSON.stringify(data.valData)).then(res => {
          if (res.code !== 200) {
            this.$modal.msgError("操作失败");
            return;
          }
          let departmentData = data.valData;
          departmentData.departmentProcId = res.msg;
          // zqjia:默认刚录入指南时状态为审核中，但后端会改为未审核
          departmentData.departmentStatus = 1;

          // zqjia:解析handbookFile，不然无法存到数据库中
          const files = departmentData.departmentFile;

          if (files !== null && files !== undefined) {
            let formatedFiles = {};
            files.forEach(file => {
              if(file.response.code === 200 && file.ossId) {
                formatedFiles[file.name] = file.ossId;
              }
            })
            departmentData.departmentFile = JSON.stringify(formatedFiles);
          }

          addDepartment(JSON.stringify(departmentData)).then(resp => {
            if (res.code !== 200) {
              this.$modal.msgError("操作失败");
              return;
            }
            this.$modal.msgSuccess(resp.msg);
            this.$tab.closeOpenPage({
              path: '/scientific/department/list'
            })
          });
        })
      }
    },

  }
}
</script>

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