<template>
  <FlexCol>
    <FlexCol v-if="errorMessage" :padding="30" :gap="30" center height="100%">
      <Result status="error" :description="errorMessage" />
      <Button type="primary" @click="loadPageConfig">重新加载</Button>
    </FlexCol>
    <LoadingPage v-else-if="!loadState" />
    <CommonListPage
      v-else-if="currentCommonCategoryDefine && loadState"
      :startTabIndex="pageStartTab"
      v-bind="currentCommonCategoryDefine.content.props as any || undefined"
      :title="currentCommonCategoryDefine.title || undefined"
      :load="loadData"
      :tabs="tabs"
      :dropDownNames="dropdownNames"
      :showListTabIds="showListTabIds"
      :detailsPage="detailsPage"
    >
      <template #list="{ tabId }">
        <CommonCategoryBlocks
          v-if="tabRenderDefines[tabId]?.type === 'nestCategory'" 
          :categoryDefine="tabRenderDefines[tabId].categoryDefine"
        />
        <CommonCategoryBlocks
          v-else-if="tabRenderDefines[tabId]?.type === 'list' && tabRenderDefines[tabId].preInsertCategorys?.length" 
          :categoryDefine="tabRenderDefines[tabId].categoryDefine"
        />
      </template>
    </CommonListPage>

    <Footer text="我也是有底线的~" />
  </FlexCol>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { injectCommonCategory } from './CommonCategoryGlobalLoader';
import { navTo } from '@/components/utils/PageAction';
import { doLoadDynamicCategoryDataMergeTypeGetColumns, doLoadDynamicDropdownData, doLoadDynamicListData } from './CommonCategoryDynamicData';
import { CommonCategoryListTabNestCategoryDataToContent, type IHomeCommonCategoryDefine, type IHomeCommonCategoryListDefine, type IHomeCommonCategoryListTabDefine, type IHomeCommonCategoryListTabNestCategoryItemDefine } from './CommonCategoryDefine';
import { resolveCommonContentSolveProps } from '../common/CommonContent';
import { waitTimeOut } from '@imengyu/imengyu-utils';
import { formatError } from '@/common/composeabe/ErrorDisplay';
import type { SimpleDropDownPickerItem } from '@/common/components/SimpleDropDownPicker.vue';
import type { CommonListPageProps, DropDownNames } from '../common/CommonListPage.vue';
import type { CategoryDefine } from './CommonCategoryBlocks';
import CommonListPage from '../common/CommonListPage.vue';
import Result from '@/components/feedback/Result.vue';
import CommonCategoryBlocks from './CommonCategoryBlocks.vue';
import Footer from '@/components/display/Footer.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import LoadingPage from '@/components/display/loading/LoadingPage.vue';
import Button from '@/components/basic/Button.vue';

/**
 * 动态通用内容 - 通用列表页
 */

const loadState = ref(false);
const errorMessage = ref('');
const currentCommonCategoryDefine = ref<IHomeCommonCategoryDefine['page'][0]>();
const currentCommonCategoryContentDefine = ref<IHomeCommonCategoryListDefine>();
const commonCategory = injectCommonCategory();

const props = defineProps({
  pageConfigName: {
    type: String,
    default: '',
  },
  pageStartTab: {
    type: Number,
    default: 0,
  },
  pageQuerys: {
    type: Object as () => Record<string, string|number|number[]|undefined>,
    default: () => ({}),
  },
});

async function loadPageConfig() {
  if (!props.pageConfigName) {
    errorMessage.value = '配置有误';
    return;
  }
  currentCommonCategoryDefine.value = commonCategory.value.page
    .find((item) => item.name === props.pageConfigName);
  if (!currentCommonCategoryDefine.value) {
    errorMessage.value = '未找到指定的分类配置：' + props.pageConfigName;
    return;
  }
  if (currentCommonCategoryDefine.value.content.type !== 'CommonList') {
    errorMessage.value = '分类配置：' + props.pageConfigName + ' 不是列表类型';
    return;
  }
  currentCommonCategoryContentDefine.value = 
    currentCommonCategoryDefine.value.content as IHomeCommonCategoryListDefine;
  uni.setNavigationBarTitle({
    title: currentCommonCategoryDefine.value?.title || '',
  })

  await waitTimeOut(100);
  
  try {
    //特殊处理
    let hasNestCategory = false;
    for (const [_, tab] of Object.entries(tabDefines.value)) {
      if (tab.type === 'nestCategory') {
        tab.categorys = await doLoadDynamicCategoryDataMergeTypeGetColumns(tab.categorys)
        hasNestCategory = true;
      } else if (tab.type === 'list') {
        tab.preInsertCategorys = await doLoadDynamicCategoryDataMergeTypeGetColumns(tab.preInsertCategorys || [])
        hasNestCategory = true;
      }
    }

    if (hasNestCategory)
      await waitTimeOut(100);

    //加载下拉列表
    const result = [] as DropDownNames[];
    for (const [key, tab] of Object.entries(tabRenderDefines.value)) {
      if (tab.type !== 'list')
        continue;
      if (tab.dropdownDefines) {
        for (const dropdown of tab.dropdownDefines) {    
          const data : SimpleDropDownPickerItem[] = (dropdown.addAll ? [{
            id: 0, 
            name: dropdown.addAll
          }] : []);
          if (dropdown.data) {
            data.push(...(await doLoadDynamicDropdownData(dropdown.data)).map((item) => ({
              id: item[dropdown.data.idKey || 'id'],
              name: item[dropdown.data.nameKey || 'title'],
            })))
          }
          result.push({
            options: data,
            activeTab: [Number(key)],
            defaultSelectedValue: dropdown.formQueryKey ? (
              props.pageQuerys[dropdown.formQueryKey] as number || 0
            ) : dropdown.defaultValue || 0,
          })
        }
      }
    }
    loadState.value = true;
    dropdownNames.value = result;
  } catch (error) {
    console.error(error);
    loadState.value = false;
    errorMessage.value = formatError(error);
  }
}

watch(() => props.pageConfigName, loadPageConfig);
onMounted(loadPageConfig);

type RenderTabDefine = IHomeCommonCategoryListTabDefine & {
  categoryDefine?: CategoryDefine[];  
};

const tabDefines = computed(() => currentCommonCategoryContentDefine.value?.props.tabs || []);
const tabRenderDefines = computed(() => {
  const result = {} as Record<number, RenderTabDefine>;
  try {
    tabDefines.value.forEach((item, i) => {
      const renderItem : RenderTabDefine = {
        ...item,
      };
      function loadNestCategoryData(items: IHomeCommonCategoryListTabNestCategoryItemDefine[]) {
        return items
          .filter((item) => item.visible !== false)
          .map((item) => {
            return {
              ...item,
              showTitle: item.showTitle !== false,
              title: item.text,
              content: CommonCategoryListTabNestCategoryDataToContent(
                item.data, item
              ),
              type: item.type as CategoryDefine['type'],
            }
          });
      }
      switch (item.type) {
        default:
        case 'list':
          renderItem.categoryDefine = loadNestCategoryData(item.preInsertCategorys || []);
          break;
        case 'jump':
          break;
        case 'nestCategory':
          renderItem.categoryDefine = loadNestCategoryData(item.categorys);
          break;
      }
      result[i] = renderItem;
    });
  } catch (error) {
    errorMessage.value = formatError(error);
  }
  return result;
});
const showListTabIds = computed(() => {
  const define = tabDefines.value;
  if (define.length === 0)
    return undefined;
  return define
    .map((item, i) => ({ type: item.type, id: i }))
    .filter((item) => item.type === 'list')
    .map((item) => item.id);
})
const tabs = computed<CommonListPageProps['tabs']>(() => {
  const define = tabDefines.value;
  return define.map((item, i) => {
    switch (item.type) {
      default:
      case 'list':
        return {
          id: i,
          text: item.text,
          width: item.width,
        };
      case 'jump':
        return {
          id: i,
          text: item.text,
          onlyJump: true,
          jump: () => navTo(item.url, item.params),
          width: item.width,
        };
      case 'nestCategory':
        return {
          id: i,
          text: item.text,
          width: item.width,
        };
    }
  });
});
const dropdownNames = ref<DropDownNames[]>([]);
const detailsPage = computed(() => {
  if (tabDefines.value.find((item) => item.detailsPage)) {
    const result = {} as Record<number, string>;
    tabDefines.value.forEach((item, i) => {
      result[i] = item.detailsPage || '';
    });
    return result;
  }
  return currentCommonCategoryContentDefine.value?.props.detailsPage || undefined;
});

async function loadData(
  page: number, 
  pageSize: number,
  searchText: string,
  dropDownValues: number[],
  tabSelect: number
) {
  const tab = tabRenderDefines.value[tabSelect];
  if (!tab) 
    throw new Error(`配置有误 tab:${tabSelect}`);
  if (tab.type !== 'list')
    return { list: [], total: 0 };
  if (!tab.data) 
    throw new Error(`配置有误 tab:${tabSelect} 没有配置列表数据`);
  const res = await doLoadDynamicListData(
    tab.data, 
    page, 
    pageSize, 
    searchText, 
    tab.dropdownDefines || [],
    dropDownValues,
  );
  if (res && tab.dataSolve)
    res.list = resolveCommonContentSolveProps(res.list, tab.dataSolve);
  return res;
}
</script>