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";

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 CollectableModulesNameMapping : Record<string, string> = {
  'overview': '村落概况',
  'distribution': '建筑分布',
  'building': '传统建筑',
  'folk_culture': '民俗文化',
  'food_product': '美食物产',
  'route': '旅游路线',
  'travel_guide': '旅游导览',
  'element': '环境要素',
  'environment': '环境格局',
  'relic': '文物古迹',
  'cultural': '历史文化',
  'figure': '历史人物',
  'ich': '非遗',
  'story': '掌故轶事',
  'spots': '风景名胜',
  'speaker': '口述者',
  'collect': '随手记',
}

const villageInfoForm : Record<string, GroupForm> = {
  'overview': villageInfoOverviewForm,
  'cultural': villageInfoCulture,
  'story': {
    [0]: villageInfoStoryFormItems
  },
  'spots': {
    [0]: villageInfoSpotsFormItems,
  },
  'speaker': {
    [1]: villageInfoSpeakerForm,
  },
  'figure': {
    [0]: villageInfoFigureFormItems,
  },
  'element': {
    [0]: vilElementForm,
  },
  'environment': {
    [0]: villageInfoEnvironmentForm
  },
  'building': {
    [1]: villageInfoBuildingForm('文物建筑'),
    [2]: villageInfoBuildingForm('历史建筑'),
    [3]: villageInfoBuildingForm('重要传统建筑'),
  },
  'distribution': { [0]: villageInfoDistributionForm },
  'relic': { [0]: villageInfoRelicForm },
  'folk_culture': {
    [1]: villageInfoFolkCultureForm('节庆活动'),
    [2]: villageInfoFolkCultureForm('祭祀崇礼'),
    [3]: villageInfoFolkCultureForm('婚丧嫁娶'),
    [4]: villageInfoFolkCultureForm('地方方言'),
    [5]: villageInfoFolkCultureForm('特色文化'),
  },
  'ich': { [0]: ichFormItems },
  'travel_guide': { [0]: villageInfoTravelGuideForm },
  'route': { [0]: villageInfoRouteForm },
  'food_product': {
    [1]: villageInfoFoodProductsForm('农副产品'),
    [2]: villageInfoFoodProductsForm('食品产品'),
    [3]: villageInfoFoodProductsForm('特色美食'),
    [4]: villageInfoFoodProductsForm('商业集市'),
    [5]: villageInfoFoodProductsForm('服装服饰'),
    [6]: villageInfoFoodProductsForm('运输工具'),
  },
  'collect': {
    [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: '', }]
  },
}

export function getVillageInfoForm(subType: string, subId: number) {
  const group = villageInfoForm[subType];
  if (!group)
    throw new Error('未定义的表单类型: ' + subType);
  if (subId === -1) 
    return mergeFormItems(group);
  return group[subId];
}
export function getVillageInfoFormIds(subType: string) {
  return Object.keys(villageInfoForm[subType]).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;
}
