import dayjs from 'dayjs';
import isToday from 'dayjs/plugin/isToday';
import isYesterday from 'dayjs/plugin/isYesterday';

const OSS_URL = import.meta.env.VITE_OSS_HOST;
const defaultAvatar = `${OSS_URL}/urm/default_avatar.png`;

dayjs.extend(isToday);
dayjs.extend(isYesterday);
// store统一设置
export const setCache = (key: string, value: any) => {
  if (!key) throw new Error('key is required');
  uni.setStorageSync(`QY_${key?.toUpperCase()}`, value);
};
export const getCache = (key: string) => {
  if (!key) throw new Error('key is required');
  return uni.getStorageSync(`QY_${key?.toUpperCase()}`);
};
export const removeCache = (key: string) => {
  if (!key) throw new Error('key is required');
  uni.removeStorageSync(`QY_${key?.toUpperCase()}`);
};

// 随机ID
export const genId = (prefix?: number | string) =>
  `${prefix || ''}${Math.random().toString(16).slice(2)}`;

// 将数组映射为对象
export const ArrToObj = (
  arr: anyObj[],
  key = 'code',
  value = 'value',
): { [key: string]: string } => {
  const obj: anyObj = {};
  let i = 0;
  for (i; i < arr.length; i++) {
    obj[arr[i][key]] = arr[i][value];
  }
  return obj;
};

// 延迟运行
export const $sleep = (time: number) => {
  return new Promise(res => {
    const timeout = setTimeout(() => {
      res(0);
      clearTimeout(timeout);
    }, time);
  });
};

export function formCheck(rules: anyObj[], data: anyObj) {
  let res = true;
  for (const i of rules) {
    if (i instanceof Array) {
      for (const j of i) {
        if (j.required && !data[j.prop]) {
          res = false;
          uni.showToast({
            title: j.message,
            icon: 'none',
          });
          break;
        }
        if (j.validator) {
          j.validator(data, data[j.prop], (result: any) => {
            if (result instanceof Error) {
              res = false;
              uni.showToast({
                title: j.message,
                icon: 'none',
              });
            }
          });
        }
      }
    } else {
      if (i.required && !data[i.prop]) {
        res = false;
        uni.showToast({
          title: i.message,
          icon: 'none',
        });
        break;
      }
    }
  }
  return res;
}

// // uniApi转换成同步
// function general(config: anyObj, method?: string) {
//     return new Promise((resolve, reject) => {
//         if (method) {
//             (uni as any)[method]({
//                 ...config,
//                 success(res: any) {
//                     resolve(res);
//                 },
//                 fail(err: any) {
//                     reject(err);
//                 },
//             });
//         }
//     });
// }
// export const uniSync = {
//     general,
//     chooseMedia: (...args: any[]) => general(args),
// };
/**
 * 文件上传
 * @param
 * @returns
 */
export const uploadFile = path =>
  new Promise((resolve, reject) => {
    uni.uploadFile({
      // url: `${import.meta.env.VITE_HOST}/api/main/sysFileInfo/tenUploadAll`,
      url: '/api/main/sysFileInfo/tenUploadAll',
      filePath: path,
      name: 'file',
      header: {
        Authorization: `Bearer ${getCache('token')}`,
      },
      success: uploadFileRes => {
        const data = JSON.parse(uploadFileRes.data);
        if (uploadFileRes.statusCode === 200) {
          resolve(data.data);
        } else {
          reject(data.message);
        }
      },
      fail: error => {
        reject(error);
      },
    });
  });

/**
 * 分钟转小时与分钟
 */
export const minToHour = (min: number) => {
  const h = Math.floor(min / 60);
  const m = min % 60;
  return [h, m];
};

export const formatDate = (time: string) => {
  const timestamp = new Date(time).getTime();
  const date = dayjs(timestamp);
  if (date.isToday()) return date.format('HH:mm');
  if (date.isYesterday()) return `昨天 ${date.format('HH:mm')}`;
  if (date.isSame(dayjs(), 'week') && (date.day() !== 0 || dayjs().day() === 0)) {
    const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    return `${daysOfWeek[date.day()]} ${date.format('HH:mm')}`;
  }
  return date.format('YYYY年M月D日 HH:mm');
};

export const getAvatarUrl = (url: string) => {
  if (url && url.includes('http')) {
    return url;
  }
  return defaultAvatar;
};
