<template>
  <BasicModal ref="modalRef" destroyOnClose wrapClassName="j-cgform-tab-modal" v-bind="$attrs" @register="registerModal" :width="800" @ok="handleSubmit">
  <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
     <!--主表区域 -->
     <a-tab-pane tab="showlist" :key="refKeys[0]" :forceRender="true" :style="tabsStyle">
       <BasicForm @register="registerForm" ref="formRef"/>
     </a-tab-pane>
  <!--子表单区域 -->
      <a-tab-pane tab="概览" key="okkiOverview" :forceRender="true" :style="tabsStyle">
        <OkkiOverviewForm ref="okkiOverviewForm" :disabled="formDisabled"></OkkiOverviewForm>
      </a-tab-pane>

      <a-tab-pane tab="产品" key="okkiProductList" :forceRender="true" :style="tabsStyle">
        <OkkiProductListForm ref="okkiProductListForm" :disabled="formDisabled"></OkkiProductListForm>
      </a-tab-pane>

      <a-tab-pane tab="亮点" key="okkiHighlight" :forceRender="true" :style="tabsStyle">
        <OkkiHighlightForm ref="okkiHighlightForm" :disabled="formDisabled"></OkkiHighlightForm>
      </a-tab-pane>

      <a-tab-pane tab="优势" key="okkiAdvantage" :forceRender="true" :style="tabsStyle">
        <JVxeTable
          keep-source
          resizable
          ref="okkiAdvantage"
          :loading="okkiAdvantageTable.loading"
          :columns="okkiAdvantageTable.columns"
          :dataSource="okkiAdvantageTable.dataSource"
          :height="340"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          />
      </a-tab-pane>
      <a-tab-pane tab="推荐商品列表" key="okkiRecommendedProducts" :forceRender="true" :style="tabsStyle">
        <OkkiRecommendedProductsForm ref="okkiRecommendedProductsForm" :disabled="formDisabled"></OkkiRecommendedProductsForm>
      </a-tab-pane>

      <a-tab-pane tab="关键词" key="okkiKeywords" :forceRender="true" :style="tabsStyle">
        <OkkiKeywordsForm ref="okkiKeywordsForm" :disabled="formDisabled"></OkkiKeywordsForm>
      </a-tab-pane>

      <a-tab-pane tab="关键词系列" key="okkiKeywordsSeries" :forceRender="true" :style="tabsStyle">
        <OkkiKeywordsSeriesForm ref="okkiKeywordsSeriesForm" :disabled="formDisabled"></OkkiKeywordsSeriesForm>
      </a-tab-pane>

      <a-tab-pane tab="评价" key="okkiReview" :forceRender="true" :style="tabsStyle">
        <OkkiReviewForm ref="okkiReviewForm" :disabled="formDisabled"></OkkiReviewForm>
      </a-tab-pane>

      <a-tab-pane tab="常见问题" key="okkiFaq" :forceRender="true" :style="tabsStyle">
        <OkkiFaqForm ref="okkiFaqForm" :disabled="formDisabled"></OkkiFaqForm>
      </a-tab-pane>

      <a-tab-pane tab="博客" key="okkiShowlistBlog" :forceRender="true" :style="tabsStyle">
        <OkkiShowlistBlogForm ref="okkiShowlistBlogForm" :disabled="formDisabled"></OkkiShowlistBlogForm>
      </a-tab-pane>

    </a-tabs>
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref,reactive} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import { JVxeTable } from '/@/components/jeecg/JVxeTable'
    import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts'
    import OkkiOverviewForm from './OkkiOverviewForm.vue'
    import OkkiProductListForm from './OkkiProductListForm.vue'
    import OkkiHighlightForm from './OkkiHighlightForm.vue'
    import OkkiRecommendedProductsForm from './OkkiRecommendedProductsForm.vue'
    import OkkiKeywordsForm from './OkkiKeywordsForm.vue'
    import OkkiKeywordsSeriesForm from './OkkiKeywordsSeriesForm.vue'
    import OkkiReviewForm from './OkkiReviewForm.vue'
    import OkkiFaqForm from './OkkiFaqForm.vue'
    import OkkiShowlistBlogForm from './OkkiShowlistBlogForm.vue'
    import {formSchema,okkiAdvantageColumns} from '../OkkiShowlist.data';
    import {saveOrUpdate,okkiOverviewList,okkiProductListList,okkiHighlightList,okkiAdvantageList,okkiRecommendedProductsList,okkiKeywordsList,okkiKeywordsSeriesList,okkiReviewList,okkiFaqList,okkiShowlistBlogList} from '../OkkiShowlist.api';
    import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils'
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const formDisabled = ref(false);
    const modalRef = ref();
    const refKeys = ref(['okkiShowlist','okkiOverview', 'okkiProductList', 'okkiHighlight', 'okkiAdvantage', 'okkiRecommendedProducts', 'okkiKeywords', 'okkiKeywordsSeries', 'okkiReview', 'okkiFaq', 'okkiShowlistBlog', ]);
    const activeKey = ref('okkiShowlist');
    const okkiOverviewForm = ref();
    const okkiProductListForm = ref();
    const okkiHighlightForm = ref();
    const okkiAdvantage = ref();
    const okkiRecommendedProductsForm = ref();
    const okkiKeywordsForm = ref();
    const okkiKeywordsSeriesForm = ref();
    const okkiReviewForm = ref();
    const okkiFaqForm = ref();
    const okkiShowlistBlogForm = ref();
    const tableRefs = {okkiAdvantage, };
    const okkiAdvantageTable = reactive({
          loading: false,
          dataSource: [],
          columns:okkiAdvantageColumns
    })
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
     //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await reset();
        setModalProps({confirmLoading: false,showCancelBtn:data?.showFooter,showOkBtn:data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        formDisabled.value = !data?.showFooter;
        if (unref(isUpdate)) {
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
             okkiOverviewForm.value.initFormData(okkiOverviewList,data?.record?.id)
             okkiProductListForm.value.initFormData(okkiProductListList,data?.record?.id)
             okkiHighlightForm.value.initFormData(okkiHighlightList,data?.record?.id)
             okkiRecommendedProductsForm.value.initFormData(okkiRecommendedProductsList,data?.record?.id)
             okkiKeywordsForm.value.initFormData(okkiKeywordsList,data?.record?.id)
             okkiKeywordsSeriesForm.value.initFormData(okkiKeywordsSeriesList,data?.record?.id)
             okkiReviewForm.value.initFormData(okkiReviewList,data?.record?.id)
             okkiFaqForm.value.initFormData(okkiFaqList,data?.record?.id)
             okkiShowlistBlogForm.value.initFormData(okkiShowlistBlogList,data?.record?.id)
             requestSubTableData(okkiAdvantageList, {id:data?.record?.id}, okkiAdvantageTable)
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //方法配置
    const [handleChangeTabs,handleSubmit,requestSubTableData,formRef] = useJvxeMethod(requestAddOrEdit,classifyIntoFormData,tableRefs,activeKey,refKeys,validateSubForm);
    // 弹窗tabs滚动区域的高度
    const tabsStyle = computed(() => {
      let height: Nullable<string> = null
      let minHeight = '100px'
      let maxHeight: Nullable<string> = '500px'
      // 弹窗wrapper
      let modalWrapperRef = modalRef.value?.modalWrapperRef
      if (modalWrapperRef) {
        if (modalWrapperRef.fullScreen) {
          height = 'calc(' + modalWrapperRef.spinStyle.height + ' - 50px)';
          maxHeight = null
        }
      }
      let overflow = 'auto';
      return {height, minHeight, maxHeight, overflow};
    })

    async function reset(){
      await resetFields();
      activeKey.value = 'okkiShowlist';
      okkiOverviewForm.value.resetFields();
      okkiProductListForm.value.resetFields();
      okkiHighlightForm.value.resetFields();
      okkiAdvantageTable.dataSource = [];
      okkiRecommendedProductsForm.value.resetFields();
      okkiKeywordsForm.value.resetFields();
      okkiKeywordsSeriesForm.value.resetFields();
      okkiReviewForm.value.resetFields();
      okkiFaqForm.value.resetFields();
      okkiShowlistBlogForm.value.resetFields();
    }
    function classifyIntoFormData(allValues) {
         let main = Object.assign({}, allValues.formValue)
         return {
           ...main, // 展开
           okkiOverviewList: okkiOverviewForm.value.getFormData(),
           okkiProductListList: okkiProductListForm.value.getFormData(),
           okkiHighlightList: okkiHighlightForm.value.getFormData(),
           okkiAdvantageList: allValues.tablesValue[0].tableData,
           okkiRecommendedProductsList: okkiRecommendedProductsForm.value.getFormData(),
           okkiKeywordsList: okkiKeywordsForm.value.getFormData(),
           okkiKeywordsSeriesList: okkiKeywordsSeriesForm.value.getFormData(),
           okkiReviewList: okkiReviewForm.value.getFormData(),
           okkiFaqList: okkiFaqForm.value.getFormData(),
           okkiShowlistBlogList: okkiShowlistBlogForm.value.getFormData(),
         }
       }
     //校验所有一对一子表表单
     function validateSubForm(allValues){
         return new Promise((resolve,reject)=>{
             Promise.all([
                  okkiOverviewForm.value.validateForm(1),
                  okkiProductListForm.value.validateForm(2),
                  okkiHighlightForm.value.validateForm(3),
                  okkiRecommendedProductsForm.value.validateForm(5),
                  okkiKeywordsForm.value.validateForm(6),
                  okkiKeywordsSeriesForm.value.validateForm(7),
                  okkiReviewForm.value.validateForm(8),
                  okkiFaqForm.value.validateForm(9),
                  okkiShowlistBlogForm.value.validateForm(10),
             ]).then(() => {
                 resolve(allValues)
             }).catch(e => {
                 if (e.error === VALIDATE_FAILED) {
                     // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                     activeKey.value = e.index == null ? unref(activeKey) : refKeys.value[e.index]
                 } else {
                     console.error(e)
                 }
             })
         })
     }
    //表单提交事件
    async function requestAddOrEdit(values) {
        try {
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(values, isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
    :deep(.ant-input-number){
        width: 100%
    }

    :deep(.ant-calendar-picker){
        width: 100%
    }
</style>

<style lang="less">
// Online表单Tab风格专属样式
.j-cgform-tab-modal {
  .ant-modal-header {
    padding-top: 8px;
    padding-bottom: 8px;
    border-bottom: none !important;
  }

  .ant-modal .ant-modal-body > .scrollbar,
  .ant-tabs-nav .ant-tabs-tab {
    padding-top: 0;
  }

  .ant-tabs-top-bar {
    width: calc(100% - 55px);
    position: relative;
    left: -14px;
  }

  .ant-tabs .ant-tabs-top-content > .ant-tabs-tabpane {
    overflow: hidden auto;
  }
}
</style>