<template>
  <!-- 
    整页表单的页签外框架
    v 1.1
    2021-05-17
    Lufthafen
  -->
  <div class="yo-form-page">
    <!-- 底部工具栏(需放在前面) -->
    <div class="yo-form-page--bar yo-form-page--bar--with-tab">
      <container>
        <div class="yo-form-page--bar-inner">
          <span>
            <!-- 可以在工具栏中增加其他控件(只能在一行内) -->
            <!-- ... -->
          </span>
          <span>
            <a-button @click="closeContentWindow()">取消</a-button>
            <a-button @click="onSubmit" type="primary">保存</a-button>
          </span>
        </div>
      </container>
    </div>

    <!-- 表单主体 -->
    <!-- 
      挂载了一个content到tab后面
      如果直接使用antd-vue的tab,将会莫名其妙地做各种多余的渲染,导致卡顿
      现在只使用其tab卡片,重写了一个tab内容
    -->
    <div class="yo-tab-external-mount">
      <a-tabs @change="onTabChange" type="card">
        <template v-for="(tab, index) in tabs">
          <a-tab-pane :force-render="true" :key="index" :tab="tab.title"></a-tab-pane>
        </template>
      </a-tabs>
      <div class="yo-tab-external-mount-content">
        <template v-for="(tab, index) in tabs">
          <div
            :class="tab.active ? 'yo-tab-external-tabpane-active' : 'yo-tab-external-tabpane-inactive'"
            :key="index"
            class="yo-tab-external-tabpane"
          >
            <component
              :frame="self"
              :id="id"
              :is="tab.component"
              :param="param"
              ref="forms"
              v-if="tab.component"
            />
          </div>
        </template>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  props: ['id', 'param'],

  data() {
    return {
      tabs: [
        /**
         * {
         *    title: '标题',
         *    component: () => import('...'),
         *    active: false,
         * }
         */
      ],
    };
  },

  methods: {
    async onSubmit() {
      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 = {
            ...formData,
            ...data,
          };
        } catch {
          flag = false;
        }
      }

      if (!flag) {
        return;
      }

      /**
       * 对表单提交进行处理
       */
    },

    onTabChange(key) {
      this.tabs.forEach((p, i) => {
        p.active = i === key;
      });
    },
  },
};
</script>