<template>
  <container>
    <!-- 如果不想使用锚点,删除a-row->a-col,只留内部的template层即可 -->
    <a-row :gutter="16" type="flex">
      <a-col flex="1">
        <br />
        <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
                :frame="frame"
                :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-col flex="240px">
        <a-anchor
          :get-container="()=> $el.parentNode"
          :offset-top="24"
          :target-offset="48"
          :wrapper-style="{ backgroundColor: 'transparent' }"
          @click.prevent
        >
          <a-anchor-link
            :href="`#form-${index}-${id}`"
            :key="index"
            :title="part.title"
            v-for="(part, index) in parts"
          />
        </a-anchor>
      </a-col>
    </a-row>
  </container>
</template>

<script>
export default {
  props: ['id', 'param', 'frame'],

  data() {
    return {
      parts: [
        {
          title: '巡查基本情况',
          component: () => import('./base'),
        },
        {
          title: '房屋检查',
          component: () => import('./inspection'),
        },
        {
          title: '等级划分',
          component: () => import('./grade'),
        },
        {
          title: '处理情况',
          component: () => import('./handling'),
        },
        {
          title: '本期巡查结果',
          component: () => import('./result'),
        },
      ],
    };
  },
  methods: {
    /**
     * 循环子组件中的onGetData
     */
    onGetData() {
      return new Promise(async (resolve, reject) => {
        let formData = {},
          flag = true;
        for (let i = 0; i < this.$refs.forms.length; i++) {
          const form = this.$refs.forms[i];
          try {
            const data = await form.onGetData();
            formData = this.$_.defaultsDeep(formData, data);
          } catch (e) {
            flag = false;
            reject(e);
          }
        }
        if (flag) {
          resolve(formData);
        }
      });
    },
  },
};
</script>