
// 动态数据接口定义

import CommonContent, { CommonContentApi, GetContentListParams } from "@/api/CommonContent";
import CalendarContent from "@/api/fusion/CalendarContent";
import ScenicSpotContent from "@/api/fusion/ScenicSpotContent";
import ActivityContent from "@/api/inheritor/ActivityContent";
import InheritorContent from "@/api/inheritor/InheritorContent";
import MoveableContent from "@/api/inheritor/MoveableContent";
import ProductsContent from "@/api/inheritor/ProductsContent";
import ProjectsContent from "@/api/inheritor/ProjectsContent";
import SeminarContent from "@/api/inheritor/SeminarContent";
import UnitContent from "@/api/inheritor/UnitContent";
import UnmoveableContent from "@/api/inheritor/UnmoveableContent";
import BulidingContent from "@/api/introduction/BulidingContent";
import CharacterContent from "@/api/introduction/CharacterContent";
import CustomContent from "@/api/introduction/CustomContent";
import FeatureContent from "@/api/introduction/FeatureContent";
import HistoryContent from "@/api/introduction/HistoryContent";
import IndexContent from "@/api/introduction/IndexContent";
import LanguageContent from "@/api/introduction/LanguageContent";
import PolicyContent from "@/api/introduction/PolicyContent";
import SeaContent from "@/api/introduction/SeaContent";
import VictualsContent from "@/api/introduction/VictualsContent";
import TeamsContent from "@/api/research/TeamsContent";
import type { IHomeCommonCategoryListTabListDropdownDefine } from "./CommonCategoryDefine";
import DiscussContent from "@/api/research/DiscussContent";
import ResultContent from "@/api/research/ResultContent";
import { CommonCategorDynamicDropDownValuesToParams } from "./data-defines/Dropdown";
import NewsIndexContent from "@/api/news/NewsIndexContent";
import VillageContent from "@/api/fusion/VillageContent";
import NotConfigue from "@/api/NotConfigue";
import { getDynamicScript } from "./CommonCategoryScript";

export * from './data-defines/Category';
export * from './data-defines/Dropdown';

//默认动态数据接口定义

/**
 * 默认列表动态数据接口定义 - 通用内容
 */
export interface IHomeCommonCategoryDynamicDataCommonContent {
  type: 'commonContent',
  params: {
    /**
     * 模型ID
     */
    modelId: number,
    /**
     * 栏目ID
     */
    mainBodyColumnId?: string|number|number[],
    /**
     * 分类类型id
     */
    typeId?: number,
  },
  /**
   * 其他参数
   */
  otherParams?: Record<string, any>,
}
/**
 * 默认列表动态数据接口定义 - 通用详情内容
 */
export interface IHomeCommonCategoryDynamicDataDetailContent {
  type: 'detailContent',
  params: {
    /**
     * 内容ID
     */
    id: number,
    /**
     * 模型ID
     */
    modelId: number,
  },
  /**
   * 其他参数
   */
  otherParams?: Record<string, any>,
}
/**
 * 默认列表动态数据接口定义 - 已序列化的预制接口
 */
export interface IHomeCommonCategoryDynamicDataSerializedApi {
  type: 'serializedApi',
  /**
   * 序列化接口名称
   */
  name: string,
  params?: {
    /**
     * 栏目ID
     */
    mainBodyColumnId?: string|number|number[],
  },
  /**
   * 其他参数
   */
  otherParams?: Record<string, any>,
}
/**
 * 默认列表动态数据接口定义 - 请求内容
 */
export interface IHomeCommonCategoryDynamicDataRequest {
  type: 'request',
  method: "OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE",
  url: string,
  /**
   * 请求参数
   */
  querys?: Record<string, any>,
  /**
   * 请求头
   */
  headers?: Record<string, string>,
  /**
   * 是否添加token
   */
  addToken?: boolean,
  /**
   * 自定义数据处理脚本
   */
  dataSolve?: string,
  /**
   * 其他参数
   */
  otherParams?: Record<string, any>,
}
/**
 * 默认列表动态数据接口定义 - 从父级指定键内容
 */
export interface IHomeCommonCategoryDynamicDataParentKey {
  type: 'parentKey',
  key: string,
}
/**
 * 默认列表动态数据接口定义 - 静态数据
 */
export interface IHomeCommonCategoryDynamicDataStaticData {
  type: 'staticData',
  data: Record<string, any>[],
}

export type IHomeCommonCategoryDynamicData = IHomeCommonCategoryDynamicDataCommonContent 
  | IHomeCommonCategoryDynamicDataSerializedApi 
  | IHomeCommonCategoryDynamicDataRequest
  | IHomeCommonCategoryDynamicDataParentKey
  | IHomeCommonCategoryDynamicDataDetailContent
  | IHomeCommonCategoryDynamicDataStaticData;

/**
 * 序列化接口映射表
 */
export const SerializedApiMap : Record<string, CommonContentApi> = {
  BulidingContent,
  ActivityContent,
  InheritorContent,
  MoveableContent,
  ProductsContent,
  ProjectsContent,
  SeminarContent,
  UnitContent,
  UnmoveableContent,
  CalendarContent,
  ScenicSpotContent,
  CharacterContent,
  FeatureContent,
  HistoryContent,
  IndexContent,
  LanguageContent,
  PolicyContent,
  SeaContent,
  VictualsContent,
  CustomContent,
  TeamsContent,
  DiscussContent,
  ResultContent,
  NewsIndexContent,
  VillageContent,
};

/**
 * 动态数据序列化接口
 */
export function CommonCategoryDynamicDataSerializedApi(item: IHomeCommonCategoryDynamicDataSerializedApi) {
  const api = SerializedApiMap[item.name as keyof typeof SerializedApiMap];
  if (!api) {
    throw new Error(`未实现的序列化接口 ${item.name}`);
  }
  return api;
}
//加载接口
export async function doLoadDynamicListData(
  item: IHomeCommonCategoryDynamicData,
  page: number,
  pageSize: number,
  keywords: string,
  dropdownDefines: IHomeCommonCategoryListTabListDropdownDefine[],
  dropDownValues: (number|string|boolean)[],
  parentData?: any,
) {
  switch (item.type) {
    default:
      throw new Error(`未实现的动态数据接口`);
    case 'commonContent':
      return await CommonContent.getContentList(new GetContentListParams()
        .setModelId(item.params.modelId)
        .setMainBodyColumnId(item.params.mainBodyColumnId)
        .setKeywords(keywords)
        .setSelfValues({
          ...item.otherParams,
          ...CommonCategorDynamicDropDownValuesToParams(dropDownValues, dropdownDefines || []),
        }) 
      , page, pageSize);
    case 'detailContent': {
      const res = await CommonContent.getContentDetail(item.params.id, undefined, item.params.modelId || undefined, item.otherParams);
      return {
        list: page === 1 ? [res] : [],
        total: 1,
      };
    }
    case 'parentKey': {
      if (!parentData)
        throw new Error(`此处不允许加载父级数据`);
      const arr = page === 1 ? parentData?.[item.key] || [] : [];
      return {
        list: arr,
        total: arr.length,
      };
    }
    case 'serializedApi': {
      const params = new GetContentListParams();
      if (item.params?.mainBodyColumnId)
        params.setMainBodyColumnId(item.params.mainBodyColumnId);
      return (await CommonCategoryDynamicDataSerializedApi(item).getContentList(
        params
        .setKeywords(keywords)
        .setSelfValues({
          ...item.otherParams,
          ...CommonCategorDynamicDropDownValuesToParams(dropDownValues, dropdownDefines || []),
        }) 
      , page, pageSize));
    }
    case 'staticData': {
      return item.data;
    }
    case 'request': {
      let data = (await (item.addToken ? CommonContent : NotConfigue).request<any>(
        item.url, 
        { ...item.querys, page, pageSize }, 
        {
          method: item.method, 
          headers: item.headers,
          data: {
            ...item.otherParams,
            ...CommonCategorDynamicDropDownValuesToParams(dropDownValues, dropdownDefines || [])
          },
        },
        '',
        undefined,
      )).data;
      if (item.dataSolve) {
        data = getDynamicScript().execute(item.dataSolve, {
          main: data,
        }) as any;
      }
      return data;
    }
  }
}
export async function doLoadDynamicDetailData(
  item: IHomeCommonCategoryDynamicData,
  id?: number,
  modelId?: number,
  parentData?: any,
) {
  switch (item.type) {
    default:
      throw new Error(`未实现的动态数据接口`);
    case 'commonContent':
      return await CommonContent.getContentDetail(id || 0, undefined, modelId || undefined, item.otherParams);
    case 'detailContent': {
      return await CommonContent.getContentDetail(item.params.id, undefined, item.params.modelId || undefined, item.otherParams);
    }
    case 'staticData': {
      return item.data;
    }
    case 'parentKey': {
      if (!parentData)
        throw new Error(`此处不允许加载父级数据`);
      return parentData?.[item.key];
    }
    case 'serializedApi': {
      return (await CommonCategoryDynamicDataSerializedApi(item).getContentDetail(id || 0, undefined, modelId || undefined, item.otherParams));
    }
    case 'request':
      return (await CommonContent.request(
        item.url, 
        { 
          id, 
          modelId,
          ...item.querys, 
        }, 
        {
          method: item.method, 
          data: {
            id,
            modelId,
            ...item.otherParams,
          },
        },
        '',
        undefined,
      )).data;
  }
}
export function doGetDynamicListDataParams(data: IHomeCommonCategoryDynamicData) {
  let modelId = 0;
  let mainBodyColumnId : string|number|number[]|undefined = undefined;
  switch (data.type) {
    case 'commonContent':
      modelId = data.params.modelId;
      mainBodyColumnId = data.params.mainBodyColumnId;
      break;
    case 'serializedApi': {
      const content = CommonCategoryDynamicDataSerializedApi(data);
      modelId = content.modelId;
      mainBodyColumnId = data.params?.mainBodyColumnId || content.mainBodyColumnId;
      break;
    }
    case 'detailContent':
    case 'parentKey':
    case 'request':
      break;
  }  
  return {
    modelId,
    mainBodyColumnId,
  };
}

export function doSerializeInternalVar(string: string) {
  let result = {
    prased: false,
    value: undefined as any,
  } 
  switch (string) {
    case 'TYPE_ARTICLE': result.value = GetContentListParams.TYPE_ARTICLE; result.prased = true; break;
    case 'TYPE_ARCHIVE': result.value = GetContentListParams.TYPE_ARCHIVE; result.prased = true; break;
    case 'TYPE_AUDIO': result.value = GetContentListParams.TYPE_AUDIO; result.prased = true; break;
    case 'TYPE_IMAGE': result.value = GetContentListParams.TYPE_IMAGE; result.prased = true; break;
    case 'TYPE_VIDEO': result.value = GetContentListParams.TYPE_VIDEO; result.prased = true; break; 
    default: {
      if (string.includes('.')) {
        const arr = string.split('.');
        const obj = arr[0];
        const type = arr[1] || '';
        const key = arr[2] || '';
        switch (type) {
          case 'serializedApi': 
            result.value = (CommonCategoryDynamicDataSerializedApi({
              type: 'serializedApi',
              name: obj,
            }) as unknown as Record<string, any>)?.[key];
            result.prased = true;
            break;
          default: break;
        }
      }
      break;
    }
  }
  return result;
}