import { CommonInfoModel } from "@/api/inhert/VillageInfoApi";
import type { IDynamicFormOptions, IDynamicFormRef } from "@/components/dynamic";
import type { FieldProps } from "@/components/form/Field.vue";
import type { NewDataModel } from "@imengyu/js-request-transform";
import type { Ref } from "vue";
import { villageCommonContent } from "./data/common";
import { villageInfoBuildingForm, villageInfoDistributionForm } from "./data/building";
import { villageInfoCulture, villageInfoFolkCultureForm } from "./data/cultural";
import { villageInfoFoodProductsForm } from "./data/food";
import { villageInfoOverviewForm } from "./data/overview";
import { villageInfoEnvironmentForm } from "./data/environment";
import { villageInfoRelicForm } from "./data/relic";
import { vilElementForm } from "./data/element";
import { villageInfoFigureFormItems, villageInfoStoryFormItems } from "./data/history";
import { villageInfoRouteForm, villageInfoTravelGuideForm } from "./data/travel";
import { villageInfoSpeakerForm } from "./data/specker";
import { ichFormItems } from "./data/ich";
import type { PickerIdFieldProps } from "@/components/dynamic/wrappers/PickerIdField";
import { villageInfoSpotsFormItems } from "./data/spots";
import { villageInfoGloryFormItems } from "./data/glory";

export type SingleForm = [NewDataModel, (formRef: Ref<IDynamicFormRef>) => IDynamicFormOptions, {
  title: string,
  typeName: string,
  mergeSubs?: boolean,
  order?: number,
  id?: number,
}]
export type GroupForm = Record<number, SingleForm>;

export const CollectableModulesIdMap : Record<string, number> = {
  'overview': 11,
  'cultural': 2,
  'story': 14,
  'spots': 13,
  'speaker': 17,
  'figure': 7,
  'element': 5,
  'environment': 6,
  'building': 16,
  'distribution': 4,
  'relic': 3,
  'folk_culture': 8,
  'food_product': 9,
  'route': 12,
  'travel_guide': 15,
  'ich': 10,
  'collect': 18,
  'glory': 23,
};

/**
 * 采集模块ID到表单定义的映射
 */
const villageInfoForm : Record<number, GroupForm> = {
  11: villageInfoOverviewForm,//村落概况
  2: villageInfoCulture,//历史文化
  14: {//掌故轶事
    [0]: villageInfoStoryFormItems
  },
  13: {//风景名胜
    [0]: villageInfoSpotsFormItems,
  },
  17: {//口述者
    [1]: villageInfoSpeakerForm,
  },
  7: {//历史人物
    [0]: villageInfoFigureFormItems,
  },
  5: {//环境要素
    [0]: vilElementForm,
  },
  6: {//环境格局
    [0]: villageInfoEnvironmentForm
  },
  16: {//传统建筑
    [1]: villageInfoBuildingForm('文物建筑'),
    [2]: villageInfoBuildingForm('历史建筑'),
    [3]: villageInfoBuildingForm('重要传统建筑'),
  },
  4: { [0]: villageInfoDistributionForm },//建筑分布
  3: { [0]: villageInfoRelicForm },//文物古迹
  8: {//民俗文化
    [1]: villageInfoFolkCultureForm('节庆活动'),
    [2]: villageInfoFolkCultureForm('祭祀崇礼'),
    [3]: villageInfoFolkCultureForm('婚丧嫁娶'),
    [4]: villageInfoFolkCultureForm('地方方言'),
    [5]: villageInfoFolkCultureForm('特色文化'),
  },
  10: { [0]: ichFormItems },//非遗
  15: { [0]: villageInfoTravelGuideForm },//旅游导览
  12: { [0]: villageInfoRouteForm },//旅游路线
  9: {//美食物产
    [1]: villageInfoFoodProductsForm('农副产品'),
    [2]: villageInfoFoodProductsForm('食品产品'),
    [3]: villageInfoFoodProductsForm('特色美食'),
    [4]: villageInfoFoodProductsForm('商业集市'),
    [5]: villageInfoFoodProductsForm('服装服饰'),
    [6]: villageInfoFoodProductsForm('运输工具'),
  },
  18: {//随手记
    [1]: [CommonInfoModel, (r) => ({
      formItems: [
        {
          label: '标题',
          name: 'name',
          type: 'text',
          defaultValue: '',
          additionalProps: {
            placeholder: '请输入标题',
          } as FieldProps,
          rules: [{
            required: true,
            message: '请输入标题',
          }]
        },
        {
          label: '描述',
          name: 'desc',
          type: 'textarea',
          defaultValue: '',
          additionalProps: {
            placeholder: '请输入描述',
            maxLength: 200,
            showWordLimit: true,
          } as FieldProps,
          rules: []
        },
        ...villageCommonContent(r, {
          title: '记录',
          showTitle: false,
        }).formItems
      ]
    }), { title: '随手记', typeName: '', }]
  },
  23: {//乡源荣光
    [1]: villageInfoGloryFormItems,
  },
}

export function getVillageInfoForm(collectModuleId: number, subId: number) {
  const group = villageInfoForm[collectModuleId];
  if (!group)
    throw new Error('未定义的表单类型: ' + collectModuleId);
  if (subId === -1 || !group[subId]) 
    return mergeFormItems(group);
  return group[subId];
}
export function getVillageInfoFormIds(collectModuleId: number) {
  return Object.keys(villageInfoForm[collectModuleId]).map((k) => Number(k));
}

export function mergeFormItems(group: GroupForm) {
  const groupArray = Object.keys(group)
    .map((k) => {
      const id = Number(k);
      const it = group[id];
      it[2].id = id;
      return it;
    })
    .sort((a, b) => 
      (a[2].order || 0) - (b[2].order || 0)
    );
  const [model, firstForm, info] = groupArray[0];
  const isOverview = group === villageInfoOverviewForm;
  const needType = !isOverview && info.typeName;
  const result : SingleForm = [model, (formRef: Ref<IDynamicFormRef>) => {
    const options : IDynamicFormOptions = {
      formItems: [],
    };
    if (needType) {
      options.formItems.push({
        label: '类型',
        name: info.typeName, 
        type: 'select-id', 
        additionalProps: {
          disabled: groupArray.length <= 1,
          loadData: async () => groupArray.map((it) => ({
            value: it[2].id,
            text: it[2].title,
          })),
        } as PickerIdFieldProps,
        defaultValue: groupArray[0][2].id,
        formProps: { showRightArrow: true } as FieldProps,
        rules: [{
          required: true,
          type: 'number',
          message: '请选择类型',
        }],
      });
    }
    if (needType || isOverview) {
      let i = 0;
      for (const it of groupArray) {
        const op = it[1](formRef);
        const ex = it[2];
        options.formItems.push({
          label: ex.title, 
          name: 'group' + i, 
          type: 'flat-group', 
          childrenColProps: { span: 24 },
          children: op.formItems, 
          show: isOverview ? undefined : { callback: (_, m) => m[info.typeName] == ex.id }
        });
        i++;
      }
    } else {
      options.formItems.push(...firstForm(formRef).formItems)
    }
    return options;
  }, info ?? { title: '合并', typeName: '' }]

  return result;
}
