/*
 * @Author: 赵伟
 * @Date: 2024-04-19 14:42:51
 * @Description: UI 公共方法
 */
import { PageEnum } from '@/enums/pagesEnums';
import { removeAllPageCacheState } from '@/hooks/pageCacheState';
import themes from '@/styles/theme.less';
import { type ClientInfo } from '@/types';
import { history } from '@umijs/max';
import { Modal, Upload, message, type ModalFuncProps, type UploadFile } from 'antd';
import { closeAllModals } from './modal';
import SessionStorage from './sessionStorage';

type ModalConfirmProps = ModalFuncProps & {
  isDelete?: boolean;
};

// 自定义删除 Confirm 弹框
export function modalConfirm({
  title,
  content,
  okText = '确认',
  cancelText = '取消',
  isDelete = true,
  onOk,
  ...rest
}: ModalConfirmProps) {
  Modal.confirm({
    ...rest,
    width: 600,
    centered: true,
    title: (
      <div>
        <img
          src={
            isDelete
              ? require('@/assets/img/delete-icon.png')
              : require('@/assets/img/comfirm-icon.png')
          }
          style={{ width: '120px', marginBottom: '24px' }}
          draggable={false}
          alt=""
        />
        <div style={{ color: themes.textColor, fontSize: '16px', fontWeight: 500 }}>{title}</div>
      </div>
    ),
    content: content && <div style={{ color: themes.textColor, fontSize: '15px' }}>{content}</div>,
    okText: okText,
    cancelText: cancelText,
    onOk: onOk,
  });
}

/**
 * 跳转到登录页
 * @param toHome 是否跳转到首页
 */
export const gotoLoginPage = (toHome: boolean = true) => {
  const { pathname, search } = location;
  const urlParams = new URLSearchParams();
  urlParams.append('redirect', pathname + search);
  const newSearch = toHome || pathname === '/' ? '' : urlParams.toString();
  if (pathname !== PageEnum.LOGIN) {
    closeAllModals();
    removeAllPageCacheState();
    history.replace({
      pathname: PageEnum.LOGIN,
      search: newSearch,
    });
  }
};

export const gotoOAuth2 = () => {
  const clientInfo = SessionStorage.getItem(SessionStorage.clientInfoKey, true) as ClientInfo;
  if (clientInfo) {
    const { clientId, userAuthorizationUri } = clientInfo;
    const url = `${userAuthorizationUri}?client_id=${clientId}&response_type=code&grant_type=authorization_code`;
    location.replace(url);
  }
};

// 从事件中获取上传文件列表，用于 Upload + Form 中
export const getFileListFromEvent = (e: any) => {
  const fileList: UploadFile[] = (Array.isArray(e) ? e : e?.fileList) || [];
  return fileList.map((item) => {
    if (item.status === 'done') {
      const { response } = item;
      if (response?.code !== 200) {
        return {
          ...item,
          status: 'error',
        };
      }
    }
    return item;
  });
};

/**
 * 验证文件上传
 *
 * @param {UploadFile[]} files - The array of uploaded files.
 * @param {boolean} [required=true] - Flag indicating if files are required.
 * @return {boolean} Returns true if all files are valid, false otherwise.
 */
export const validateUploadFiles = (files: UploadFile[], required: boolean = true): boolean => {
  if (required && files.length === 0) {
    message.error('请上传文件');
    return false;
  }

  const hasError = files.some((file) => {
    if (file.status === 'uploading') {
      message.error('请等待文件上传完成');
      return true;
    }
    if (file.status === 'error') {
      message.error('存在上传失败的文件，请删除后重新上传');
      return true;
    }
    if (!file.response || file.response.code !== 200 || !file.response.data) {
      message.error('存在上传失败的文件，请删除后重新上传');
      return true;
    }
    return false;
  });
  return !hasError;
};

// 限制上传文件类型
export const limitUploadFileType = (type: string) => {
  return (file: UploadFile): boolean | string => {
    const acceptTypes = type.split(',').map((item) => item.trim());
    const fileType = file.name.split('.').pop()?.trim();
    if (!(fileType && acceptTypes.includes(fileType))) {
      message.error(`文件类型不正确，只支持 "${acceptTypes.join('、')}" 类型的文件`);
      file.status = 'error';
      return Upload.LIST_IGNORE;
    }
    return true;
  };
};

/**
 * 滚动到底部
 *
 * @param {boolean} smooth - Determines if the scroll should be smooth
 */
export const scrollToBottom = (element: HTMLElement | null, smooth: boolean = true) => {
  if (element) {
    const optons: ScrollToOptions = {
      top: element.scrollHeight,
      behavior: smooth ? 'smooth' : 'instant',
    };
    element.scrollTo(optons);
  }
};
