import VillageInfoApi, { CommonInfoModel, VillageBulidingInfo } from "@/api/inhert/VillageInfoApi";
import { CollectableModulesIdMap, type GroupForm, type SingleForm } from "../forms";
import type { IDynamicFormItemCallback, IDynamicFormItemCallbackAdditionalProps } from "@/components/dynamic";
import type { PickerIdFieldProps } from "@/components/dynamic/wrappers/PickerIdField";
import type { FieldProps } from "@/components/form/Field.vue";
import type { UploaderInstance } from "@/components/form/Uploader.vue";
import type { UploaderFieldProps, UploaderFieldInstance } from "@/components/form/UploaderField.vue";
import { useAliOssUploadCo } from "@/common/components/upload/AliOssUploadCo";
import { villageCommonContent } from "./common";
import { goFormStatic } from "../composeable/TaskEntryForm";
import type { ButtonProp } from "@/components/basic/Button.vue";
import { useCollectStore } from "@/store/collect";

export function villageInfoFolkCultureForm(title: string) : SingleForm {
  return [VillageBulidingInfo, (m) => ({
    formItems: [
      {
        label: title + '名称',
        name: 'name',
        type: 'text',
        defaultValue: '',
        additionalProps: {
          placeholder: '请输入名称',
        },
        rules:  [{
          required: true,
          message: '请输入名称',
        }]
      }, 
      {
        label: '非遗项目', 
        name: 'ichId',
        type: 'select-id', 
        defaultValue: null,
        additionalProps: {
          loadData: {
            callback: (m, r, p, i) => async () => {
              return (await VillageInfoApi.getList(
                CollectableModulesIdMap['ich'],
                undefined, undefined,
                i.formGlobalParams.villageId,
                i.formGlobalParams.villageVolunteerId
              )).map((p) => ({
                value: p.id,
                text: p.title,
              }))
            }
          },
        } as IDynamicFormItemCallbackAdditionalProps<PickerIdFieldProps>,
        formProps: { showRightArrow: true } as FieldProps,
        rules: [],
      },
      ...villageCommonContent(m, {
        title: title,
        showTitle: false,
        contentKey: 'details'
      }).formItems
    ]
  }), { title: title, typeName: 'folkCultureType', }];
}

export const villageInfoCulture : GroupForm = {
  [1]: [CommonInfoModel, (m) => villageCommonContent(m, {
    title: '建村(社)历史',
    showTitle: true
  }), { title: '建村(社)历史', typeName: 'culturalType', }],
  [2]: [CommonInfoModel, (m) => villageCommonContent(m, {
    title: '历史事件',
    showTitle: true
  }), { title: '历史事件', typeName: 'culturalType', }],  
  [3]: [CommonInfoModel, (m) => ({
    formItems: [
      ...(villageCommonContent(m, {
        title: '历史文献',
        showTitle: true
      }).formItems.slice(0, 1)),
      {
        label: '扫描件或图片',
        name: 'images',
        type: 'uploader',
        defaultValue: '',
        additionalProps: {
          upload: useAliOssUploadCo('xiangyuan/cultural/scan'),
          maxFileSize: 1024 * 1024 * 20,
          maxUploadCount: 20,
        } as UploaderFieldProps,
        rules: [{
          required: true,
          message: '请上传扫描件或图片',
        }]
      },
    ],
  }), { title: '历史文献', typeName: 'culturalType', }],
  [4]: [CommonInfoModel, (m) => {
    const common = villageCommonContent(m, {
      title: '口述历史',
      showTitle: true,
      noCloseExtra: true,
    }).formItems;
    common.splice(1, 1);
    return {
      formItems: [
        ...common,
        {
          label: '口述人', 
          name: 'speakerId',
          type: 'select-id', 
          additionalProps: {
            loadData: { 
              callback(_, m, p, i) { 
                const collectStore = useCollectStore();
                return async () => (await VillageInfoApi.getList(
                  CollectableModulesIdMap['speaker'],
                  undefined, undefined,
                  i.formGlobalParams.villageId,
                  i.formGlobalParams.villageVolunteerId
                ))
                .map((p) => ({
                  value: p.id,
                  text: p.name,
                }))
              } 
            },
          } as IDynamicFormItemCallbackAdditionalProps<PickerIdFieldProps>,
          formProps: { showRightArrow: true } as FieldProps,
          rules: [{
            required: true,
            message: '请选择口述人',
          }],
        },
        {
          label: '口述人管理',
          type: 'button',
          name: 'manage',
          defaultValue: '',
          additionalProps: {
            text: '口述人管理',
            onClick: { callback(v, m, p, i) {
              return () => {
                const collectStore = useCollectStore();
                if (!collectStore.canCollect(CollectableModulesIdMap['speaker'])) {
                  uni.showToast({
                    title: '您暂无权限采编口述人，请联系管理员。',
                    icon: 'none',
                    duration: 3000
                  });
                  return;
                }
                goFormStatic(
                  i.formGlobalParams.villageId,
                  i.formGlobalParams.villageVolunteerId,
                  CollectableModulesIdMap['speaker'],
                  1,
                  undefined,
                  undefined,
                  '口述人管理'
                );
              }
            } } as IDynamicFormItemCallback<() => void>,
          } as IDynamicFormItemCallbackAdditionalProps<ButtonProp>,
          formProps: {
            inputAlign: 'right'
          } as FieldProps,
        },
        {
          label: '口述历史视频/录音',
          name: 'video',
          type: 'uploader',
          defaultValue: '',
          additionalProps: {
            upload: useAliOssUploadCo('xiangyuan/cultural/video'),
            chooseType: '',
            maxFileSize: 1024 * 1024 * 1000, // 1000MB
            single: true,
          } as UploaderFieldProps,
          formProps: {
            extraMessage: '您可以上传已经录制好的口述历史视频/录音，也可以点击下方按钮录制新的音频。但小程序中录音时长最长10分钟，如需更长时间，请使用系统相机或者录音机拍摄。',
          } as FieldProps,
        },
        {
          label: '',
          name: 'video1',
          type: 'recorder',
          defaultValue: '',
          additionalProps: {
            onRecordDone: (path: string) => {
              if (m.value.getValueByPath('video')) {
                (m.value.getFormItemControlRef<UploaderFieldInstance>('annex')?.getUploaderRef() as UploaderInstance).addItemAndUpload({
                  filePath: path,
                  state: 'notstart',
                });
              } else {
                (m.value.getFormItemControlRef<UploaderFieldInstance>('video')?.getUploaderRef() as UploaderInstance).addItemAndUpload({
                  filePath: path,
                  state: 'notstart',
                });
              }
            }
          },
        },
      ],
    }
  }, { title: '口述历史', typeName: 'culturalType', }],
}
