/**
 * 通用组件共同的使用的基础组件，原先放在 adapter/form 内部，限制了使用范围，这里提取出来，方便其他地方使用
 * 可用于 vben-form、vben-modal、vben-drawer 等组件使用,
 */

import type { UploadFile } from 'element-plus';

import type { Component } from 'vue';

import type { BaseFormComponentType } from '@vben/common-ui';
import type { Recordable } from '@vben/types';

import { defineComponent, getCurrentInstance, h, ref, watch } from 'vue';

import { ApiComponent, globalShareState, IconPicker } from '@vben/common-ui';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElCheckbox,
  ElCheckboxButton,
  ElCheckboxGroup,
  ElDatePicker,
  ElDivider,
  ElImageViewer,
  ElInput,
  ElInputNumber,
  ElInputTag,
  ElNotification,
  ElRadio,
  ElRadioButton,
  ElRadioGroup,
  ElSelectV2,
  ElSpace,
  ElSwitch,
  ElTimePicker,
  ElTreeSelect,
  ElUpload,
} from 'element-plus';

import { Tinymce as RichTextarea } from '#/components/tinymce';

const withPreviewUpload = () => {
  return defineComponent({
    name: 'UploadWithPreview',
    emits: ['update:modelValue'],
    setup: (
      props: any,
      { attrs, slots, emit }: { attrs: any; emit: any; slots: any },
    ) => {
      const previewVisible = ref<boolean>(false);
      const previewImageUrl = ref<string>('');
      const fileList = ref<UploadFile[]>(
        attrs?.fileList || attrs?.['file-list'] || [],
      );

      const handleBeforeUpload = (file: UploadFile) => {
        if (attrs.maxSize && (file.size || 0) / 1024 / 1024 > attrs.maxSize) {
          ElNotification({
            title: $t('ui.formRules.sizeLimitTitle'),
            message: $t('ui.formRules.sizeLimit', [attrs.maxSize]),
            type: 'error',
          });
          return false;
        }
        return attrs.beforeUpload?.(file) ?? true;
      };

      const handleChange = (
        uploadFile: UploadFile,
        uploadFiles: UploadFile[],
      ) => {
        fileList.value = uploadFiles.filter(
          (file) => file.status !== 'removed',
        );
        emit(
          'update:modelValue',
          fileList.value.length > 0 ? fileList.value : undefined,
        );
      };

      const handlePreview = (file: UploadFile) => {
        // 阻止默认行为，避免新页面打开
        event?.preventDefault();
        event?.stopPropagation();

        // 检查是否为图片文件
        const isImageFile = (file: UploadFile): boolean => {
          const imageExtensions = new Set([
            'bmp',
            'gif',
            'jpeg',
            'jpg',
            'png',
            'webp',
          ]);

          // 优先检查 file.type，对于 blob URL 来说，file.type 会包含正确的 MIME 类型
          if (file.type && file.type.startsWith('image/')) {
            return true;
          }

          // 检查 file.name 的扩展名
          if (file.name) {
            const ext = file.name.split('.').pop()?.toLowerCase();
            if (ext && imageExtensions.has(ext)) {
              return true;
            }
          }

          // 最后检查 file.url 的扩展名（非 blob URL）
          if (file.url && !file.url.startsWith('blob:')) {
            const ext = file.url.split('.').pop()?.toLowerCase();
            if (ext && imageExtensions.has(ext)) {
              return true;
            }
          }

          return false;
        };

        // 如果是图片文件，使用 ElImageViewer 预览
        if (isImageFile(file)) {
          previewImageUrl.value = file.url || file.preview || '';
          previewVisible.value = true;
        } else {
          // 非图片文件直接在新窗口打开
          if (file.url) {
            window.open(file.url, '_blank');
          } else if (file.preview) {
            window.open(file.preview, '_blank');
          } else {
            ElNotification({
              title: $t('ui.formRules.previewWarningTitle'),
              message: $t('ui.formRules.previewWarning'),
              type: 'warning',
            });
          }
        }
      };

      // 监听表单 API 设置的值
      watch(
        () => attrs.modelValue,
        (res) => {
          fileList.value = res || [];
        },
      );

      return () => {
        const uploadProps = {
          ...props,
          ...attrs,
          fileList: fileList.value,
          beforeUpload: handleBeforeUpload,
          onChange: handleChange,
          onPreview: handlePreview,
        };

        return h('div', {}, [
          h(ElUpload, uploadProps, slots),
          previewVisible.value &&
            h(ElImageViewer, {
              urlList: [previewImageUrl.value],
              showProgress: true,
              onClose: () => {
                previewVisible.value = false;
              },
            }),
        ]);
      };
    },
  });
};

const withDefaultPlaceholder = <T extends Component>(
  component: T,
  type: 'input' | 'select',
) => {
  return defineComponent({
    inheritAttrs: false,
    name: component.name,
    setup: (props: any, { attrs, expose, slots }) => {
      const placeholder =
        props?.placeholder ||
        attrs?.placeholder ||
        $t(`ui.placeholder.${type}`);
      // 透传组件暴露的方法
      const innerRef = ref();
      const publicApi: Recordable<any> = {};
      expose(publicApi);
      const instance = getCurrentInstance();
      instance?.proxy?.$nextTick(() => {
        for (const key in innerRef.value) {
          if (typeof innerRef.value[key] === 'function') {
            publicApi[key] = innerRef.value[key];
          }
        }
      });
      return () =>
        h(component, { ...props, ...attrs, placeholder, ref: innerRef }, slots);
    },
  });
};

// 这里需要自行根据业务组件库进行适配，需要用到的组件都需要在这里类型说明
export type ComponentType =
  | 'ApiSelect'
  | 'ApiTreeSelect'
  | 'Checkbox'
  | 'CheckboxGroup'
  | 'DatePicker'
  | 'Divider'
  | 'IconPicker'
  | 'Input'
  | 'InputNumber'
  | 'InputTag'
  | 'RadioGroup'
  | 'RichTextarea'
  | 'SectionTitle'
  | 'Select'
  | 'Space'
  | 'Switch'
  | 'TimePicker'
  | 'TreeSelect'
  | 'Upload'
  | BaseFormComponentType;

async function initComponentAdapter() {
  const components: Partial<Record<ComponentType, Component>> = {
    // 如果你的组件体积比较大，可以使用异步加载
    // Button: () =>
    // import('xxx').then((res) => res.Button),
    ApiSelect: (props, { attrs, slots }) => {
      return h(
        ApiComponent,
        {
          placeholder: $t('ui.placeholder.select'),
          ...props,
          ...attrs,
          component: ElSelectV2,
          loadingSlot: 'loading',
          visibleEvent: 'onVisibleChange',
        },
        slots,
      );
    },
    ApiTreeSelect: (props, { attrs, slots }) => {
      return h(
        ApiComponent,
        {
          placeholder: $t('ui.placeholder.select'),
          ...props,
          ...attrs,
          component: ElTreeSelect,
          props: { label: 'label', children: 'children' },
          nodeKey: 'value',
          loadingSlot: 'loading',
          optionsPropName: 'data',
          visibleEvent: 'onVisibleChange',
        },
        slots,
      );
    },
    Checkbox: ElCheckbox,
    CheckboxGroup: (props, { attrs, slots }) => {
      let defaultSlot;
      if (Reflect.has(slots, 'default')) {
        defaultSlot = slots.default;
      } else {
        const { options, isButton } = attrs;
        if (Array.isArray(options)) {
          defaultSlot = () =>
            options.map((option) =>
              h(isButton ? ElCheckboxButton : ElCheckbox, option),
            );
        }
      }
      return h(
        ElCheckboxGroup,
        { ...props, ...attrs },
        { ...slots, default: defaultSlot },
      );
    },
    // 自定义默认按钮
    DefaultButton: (props, { attrs, slots }) => {
      return h(ElButton, { ...props, attrs, type: 'info' }, slots);
    },
    // 自定义主要按钮
    PrimaryButton: (props, { attrs, slots }) => {
      return h(ElButton, { ...props, attrs, type: 'primary' }, slots);
    },
    Divider: ElDivider,
    IconPicker: (props, { attrs, slots }) => {
      return h(
        IconPicker,
        {
          iconSlot: 'append',
          modelValueProp: 'model-value',
          inputComponent: ElInput,
          ...props,
          ...attrs,
        },
        slots,
      );
    },
    Input: withDefaultPlaceholder(ElInput, 'input'),
    InputNumber: withDefaultPlaceholder(ElInputNumber, 'input'),
    InputTag: withDefaultPlaceholder(ElInputTag, 'input'),
    RadioGroup: (props, { attrs, slots }) => {
      let defaultSlot;
      if (Reflect.has(slots, 'default')) {
        defaultSlot = slots.default;
      } else {
        // 合并props和attrs以确保能正确获取options和isButton
        const mergedAttrs = { ...props, ...attrs };
        const { options, isButton } = mergedAttrs;
        if (Array.isArray(options)) {
          defaultSlot = () =>
            options.map((option, index) => {
              // 确保每个选项都有正确的value和label属性
              const optionProps = {
                label:
                  option.value === undefined
                    ? (option.label === undefined
                      ? option
                      : option.label)
                    : option.value,
                value:
                  option.value === undefined
                    ? (option.label === undefined
                      ? option
                      : option.label)
                    : option.value,
                ...option,
              };
              return h(isButton ? ElRadioButton : ElRadio, optionProps);
            });
        }
      }
      // 确保将所有属性正确传递给ElRadioGroup
      return h(
        ElRadioGroup,
        { ...props, ...attrs },
        { ...slots, default: defaultSlot },
      );
    },
    Select: (props, { attrs, slots }) => {
      return h(ElSelectV2, { ...props, attrs }, slots);
    },
    Space: ElSpace,
    Switch: ElSwitch,
    TimePicker: (props, { attrs, slots }) => {
      const { name, id, isRange } = props;
      const extraProps: Recordable<any> = {};
      if (isRange) {
        if (name && !Array.isArray(name)) {
          extraProps.name = [name, `${name}_end`];
        }
        if (id && !Array.isArray(id)) {
          extraProps.id = [id, `${id}_end`];
        }
      }
      return h(
        ElTimePicker,
        {
          ...props,
          ...attrs,
          ...extraProps,
        },
        slots,
      );
    },
    DatePicker: (props, { attrs, slots }) => {
      const { name, id, type } = props;
      const extraProps: Recordable<any> = {};
      if (type && type.includes('range')) {
        if (name && !Array.isArray(name)) {
          extraProps.name = [name, `${name}_end`];
        }
        if (id && !Array.isArray(id)) {
          extraProps.id = [id, `${id}_end`];
        }
      }
      return h(
        ElDatePicker,
        {
          ...props,
          ...attrs,
          ...extraProps,
        },
        slots,
      );
    },
    TreeSelect: withDefaultPlaceholder(ElTreeSelect, 'select'),
    Upload: withPreviewUpload(),
    RichTextarea,
    SectionTitle: (props, { attrs, slots }) => {
      // 获取标题文本，优先使用props.title，其次使用attrs.title，最后使用默认值
      const title = props.title || attrs.title || '标题';

      // 获取竖条颜色，优先使用props.barColor，其次使用attrs.barColor，最后使用默认值
      const barColor = props.barColor || attrs.barColor || '#215acd';

      // 获取标题文字大小，优先使用props.fontSize，其次使用attrs.fontSize，最后使用默认值
      const fontSize = props.fontSize || attrs.fontSize || '14px';

      // 根据文字大小动态计算竖条高度（约为文字大小的0.85倍）
      // 从fontSize中提取数字部分，例如从'14px'中提取14
      const fontSizeNum = Number.parseFloat(fontSize);
      // 计算竖条高度，默认12px对应14px字体，比例约为0.85
      const barHeight = `${fontSizeNum * 0.85}px`;

      return h(
        'div',
        {
          class: 'py-4', // 添加适当的上下内边距
          ...props,
          ...attrs,
        },
        h(
          'div',
          {
            class: 'flex items-center gap-4',
          },
          [
            h('div', {
              style: {
                width: '4px',
                height: barHeight,
                backgroundColor: barColor,
              },
            }),
            h(
              'span',
              {
                class: 'font-bold text-gray-800',
                style: {
                  fontSize,
                  fontWeight: '600',
                },
              },
              title,
            ),
          ],
        ),
      );
    },
  };

  // 将组件注册到全局共享状态中
  globalShareState.setComponents(components);

  // 定义全局共享状态中的消息提示
  globalShareState.defineMessage({
    // 复制成功消息提示
    copyPreferencesSuccess: (title, content) => {
      ElNotification({
        title,
        message: content,
        position: 'bottom-right',
        duration: 0,
        type: 'success',
      });
    },
  });
}

export { initComponentAdapter };
