<template>
  <!-- 
    整页表单的页签外框架
    v 1.0
    2021-05-12
    Lufthafen
  -->
  <div class="yo-form-page">
    <!-- 表单主体 -->
    <!-- 如果不想使用固钉,删除a-row->a-col,只留内部的template层即可 -->
    <container>
      <a-row :gutter="16" type="flex">
        <a-col flex="1">
          <br />
          <div class="yo-form">
            <div class="yo-form-group">
              <yo-form-link content="对片区信息进行管理" title="片区管理" />
              <yo-form-link content="对项目信息进行管理" title="项目管理" />
            </div>
          </div>
          <a-card class="yo-form-page--body">
            <template v-for="(part, index) in parts">
              <section :id="`form-${index}-${id}`" :key="index">
                <h5 v-if="part.title">{{part.title}}</h5>
                <component
                  :is="part.component"
                  :key="index"
                  :param="param"
                  ref="forms"
                  v-if="part.component"
                />
              </section>
              <a-divider :key="`divider-${index}`" v-if="index < parts.length - 1" />
            </template>
          </a-card>
        </a-col>
      </a-row>
    </container>

    <!-- 底部工具栏 -->
    <div class="yo-form-page--bar">
      <container>
        <div class="yo-form-page--bar-inner">
          <span>
            <!-- 可以在工具栏中增加其他控件(只能在一行内) -->
            <!-- ... -->
          </span>
          <span>
            <a-button @click="closeContentWindow()">取消</a-button>
            <a-button :loading="saving" @click="onSubmit" type="primary">保存</a-button>
          </span>
        </div>
      </container>
    </div>
  </div>
</template>
<script>
export default {
  props: ['id', 'param'],

  data() {
    return {
      parts: [
        /**
         * {
         *    title: '标题',
         *    component: () => import('...'),
         * }
         */
        {
          component: () => import('./part'),
        },
      ],

      saving: false,
    };
  },

  methods: {
    async onSubmit() {
      let formData = {};
      for (let i = 0; i < this.$refs.forms.length; i++) {
        const form = this.$refs.forms[i];
        try {
          const data = await form.onGetData();
          formData = {
            ...formData,
            ...data,
          };
        } catch {
          return;
        }
      }

      /**
       * 对表单提交进行处理
       */
      this.saving = true;
      this.$api
        .houseCodeAdd(formData)
        .then(({ success }) => {
          if (success) {
            this.$message.success('保存成功');
            this.$confirm({
              content: '已添加成功，是否继续添加？',
              onOk: () => {
                this.$refs.forms[0].onProjectChange();
              },
              onCancel: () => {
                this.closeContentWindow();
              },
            });
          }
        })
        .finally(() => {
          this.saving = false;
        });
    },
  },
};
</script>