import {
  Request
} from '@/service/request/index.js'

//格式化日期
//data: 日期对象或时间戳
//format: 格式化字符串，默认"YYYY-MM-DD hh:mm:ss"
export function formatDate(
  data,
  format = "YYYY-MM-DD hh:mm:ss"
) {
  if (data === null || data === undefined) {
    return ""
  }
  let date = data
  if (typeof data === 'object' && !(data instanceof Date)) {
    if (data.date) {
      date = data.date
    } else if (data.timestamp) {
      date = data.timestamp * 1000
    } else if (Object.keys(data).length === 0) {
      // empty object
      return ""
    }
    // If object but no date/timestamp property found, and not a Date object, 
    // it might be intended as 'date' if it was structured differently, 
    // but based on previous code, it only looked for date/timestamp.
    // However, if we want to support direct values, we assume 'date' holds the value 
    // extracted above. 
    // But wait, if data is { other: 1 }, date becomes { other: 1 }. new Date({other:1}) is Invalid Date usually.
  }

  if (!date) {
    return ""
  }

  const d = new Date(date);
  if (isNaN(d.getTime())) {
    return ""
  }

  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  const hour = String(d.getHours()).padStart(2, "0");
  const minute = String(d.getMinutes()).padStart(2, "0");
  const second = String(d.getSeconds()).padStart(2, "0");
  return format
    .replace("YYYY", year)
    .replace("MM", month)
    .replace("DD", day)
    .replace("hh", hour)
    .replace("mm", minute)
    .replace("ss", second);
}

//获取唯一id
export function getUid(len = 16) {
  const ts = Date.now().toString(36);
  const rand = Math.random().toString(36).slice(2);
  return (ts + rand).slice(0, len);
}


/**
 * 生成唯一的ID
 * @method guid
 * @grammar Base.guid() => String
 * @grammar Base.guid( prefix ) => String
 */
export const guid = (() => {
  let counter = 0;
  return (prefix) => {
    let id = (+new Date()).toString(32);
    for (let i = 0; i < 5; i++) {
      id += Math.floor(Math.random() * 65535).toString(32);
    }
    return (prefix || 'cw_') + id + (counter++).toString(32);
  };
})();

//判断是否有某个功能权限
export function hasFunction(key) {
  return new Promise((resolve, reject) => {
    Request(
      {
        url: "/v1/api/basic/home/menu?type=3",
        method: 'GET',
      }
    ).then((res) => {
      if (res?.data?.permissions) {
        const permissions = res.data.permissions || []
        if (Array.isArray(key)) {
          resolve(key.map(item => permissions.includes(item)))
        } else {
          resolve(permissions.includes(key))
        }
      } else {
        reject(res)
      }
    }).catch(err => {
      reject(err)
    })
  })
}

//
/**
 * 分页获取本地数据
 * @param {Object} params
 * @param {number} params.page 当前页码
 * @param {number} params.size 每页条数
 * @param {Array} params.initData 原始数据源
 * @param {Array} params.data 当前已加载数据
 * @returns {Object} { page, data }
 */
export function getPaginatedList({ page = 0, size = 10, initData = [], data = [] }) {
  if (!data) data = [];
  if (
    data.length >= initData.length
  ) {
    return {};
  }
  const _page = (page || 0) + 1;
  const start = (_page - 1) * size;
  const end = Math.min(
    start + size,
    initData?.length || 0
  );
  data = [
    ...data,
    ...(initData?.slice(start, end) || []),
  ];
  return {
    page: _page,
    data
  }
}