<template>
  <div class="container">
    <el-card shadow="always">
      <template #header>
        <p>{{ config.customModel ? config.customModel.name : '办理' }}</p>
      </template>

      <template>
        <div class="form-container">
          <template v-if="device === 'desktop'">
            <DesktopForm :device="device" :sub-form="subConfig" :info="fields" :original-form="form"></DesktopForm>
          </template>
          <template v-else>
            <MobileForm :device="device" :info="fields"></MobileForm>
          </template>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script>
import DesktopForm from "./DesktopForm.vue";
import MobileForm from "./MobileForm.vue";
import { preConfig } from "@/api/flow"
export default {
  components: {
    DesktopForm,
    MobileForm
  },
  data() {
    return {
      info: [],
      config: {},
      subConfig: new Map(),

      form: {},
      fileList: {}
    }
  },
  methods: {
    generateForm(object,fields) {
      fields.forEach(field => {
        if(field.type === 'relation') {
          object[field.name] = [{}]

          this.generateForm(object[field.name][0], this.subConfig.get(field.sub_custom_model_id)?.customModel?.fields)
        } else {
          object[field.name] = ""
        }
      })
    },
    async getConfig() {
      const loading = this.$loading({
        lock: true,
        text: '拼命加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)'
      });
      try {
        const res = await preConfig(this.$route.query.id)
        const { fields } = res?.customModel;
        let subFormRequest = []
        const getSubForm = (id) => {
          subFormRequest.push(preConfig(id))
        }
        fields.forEach(field => {
          if(field.sub_custom_model_id) {
            getSubForm(field.sub_custom_model_id)
          }
        })
        const subConfigs = await Promise.all(subFormRequest)
        subConfigs.forEach(sub => {
          if(sub.customModel?.id) {
            this.subConfig.set(sub.customModel?.id, sub)
          }
        })
        this.config = res;
        this.generateForm(this.form, fields)
        this.form = Object.assign({},this.form)
        loading.close()
      } catch (err) {
        console.error(err)
        this.$message.error("配置失败")
        loading.close()
      }
    }
  },
  computed: {
    device() {
      return this.$store.state.app.device
    },
    fields() {
      return this.config?.customModel?.fields || []
    }
  },
  created() {
    this.getConfig()
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-card__header {

}
.container {
  padding: 20px;
}
.form-container {
}
@media (max-width: 768px) {
  .container {
    padding: 10px;
  }
}
</style>
