import cacheManager from "./cacheManager.js"
import {nextTick} from "vue";

/**
* 显示消息提示框
* @param content 提示的标题
*/
export function toast(content) {
  uni.showToast({
    icon: 'none',
	duration:3000,
    title: content
  })
}

/**
* 显示模态弹窗
* @param content 提示的标题
*/
export function showConfirm(content) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title: '提示',
      content: content,
      cancelText: '取消',
      confirmText: '确定',
      success: function(res) {
        resolve(res)
      }
    })
  })
}

/**
* 参数处理
* @param params 参数
*/
export function tansParams(params) {
  let result = ''
  // FIXME   拼接参数 
  return result
}

/**
 * @summary 获取请求异常与正常返回
 * @param {Object} promise
 */
export function catchError(promise) {
	return new Promise((resolve,reject) => {
		promise.then(data => {
			resolve([undefined, data.data]) 
		}).catch(err => {
			reject([err]) 
		})
	})
}

// 是否是会员
export function getUserIdentity() {
	const auth = cacheManager.get('auth');
	if (auth) {
		if ((auth.levelIdList || []).some(item => item == auth.levelId)) {
			// 购买此levelId
			return 'VIP'
		}
		// 无购买此levelId
		return 'Not-Vip';
	} else {
		// 游客
		return 'Visitor';
	}
}

export function hasUserIdentity() {
	const auth = cacheManager.get('auth');
	if (auth) {
		if (auth.cardList.length) {
			// VIP
			return 'VIP'
		}
		// 非VIP
		return 'Not-Vip';
	} else {
		// 游客
		return 'Visitor';
	}
}

export function debounce(func, wait) {
  let timeout;

  return function(...args) {
    // 清除之前的定时器
    clearTimeout(timeout);

    // 设置新的定时器
    timeout = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
}


export function findRootNode(tree, targetId, idKey = 'id') {
	const path = [];
	
	function traverse(node) {
	  if (node[idKey] === targetId) return true;
	  if (node.children) {
	    for (const child of node.children) {
	      if (traverse(child)) {
	        path.unshift(node);
	        return true;
	      }
	    }
	  }
	  return false;
	}
	
	for (const root of tree) {
	  if (traverse(root)) {
	    return path.length > 0 ? path[0] : root;
	  }
	}
	return null;
}


export function findTreeNode(tree, targetId, childrenKey = 'children', idKey = 'id') {
	for (const node of tree) {
		if (node[idKey] === targetId) return node;
		if (node[childrenKey]?.length) {
			const found = findTreeNode(node[childrenKey], targetId, childrenKey, idKey);
			if (found) return found;
		}
	}
	return null;
}


export function convertTimeToSeconds(timeStr) {
    // 分割时间字符串为小时和分钟部分
    const parts = timeStr.split(':');
    // 解析小时和分钟为整数
    const hours = parseInt(parts[0], 10);
    const minutes = parseInt(parts[1], 10);
    // 计算总秒数：小时 × 3600 + 分钟 × 60
    const totalSeconds = hours * 60 + minutes;
    return totalSeconds.toString();
}

// 当前用户是否是非游客
export function getUserIsYouke() {
	const auth = cacheManager.get('auth');
	console.log('user', auth)
	if (!auth) {
		throw new Error('数据异常，未发现用户信息');
	}

	if (!auth.userName) {
		throw new Error('数据异常，无法判定用户身份')
	}

	return auth.userName.startsWith('youke');
}

export function getFullTimer() {
	const now = new Date();
	const year = now.getFullYear();
	const month = now.getMonth() + 1;
	const day = now.getDate();
    // 格式：2026-01-29
	return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
}


export function useSelectDateForUpdate(code) {
	function getDate() {
		return cacheManager.get(code);
	}
	
	function updateDate() {
		cacheManager.set(code, getFullTimer())
	}
	
	function isNowDate() {
		const nowDate = getDate();
		if (!nowDate) {
			updateDate();
			return false
		}
		if (nowDate != getFullTimer()) {
			updateDate();
		}
		
		return nowDate == getFullTimer();
	}
	
	function resetDate() {
		cacheManager.remove(code)
	}
	
	return {
		isNowDate,
		resetDate
	}
}

export function getDataFromStr(strdata) {
	if (!strdata) {
		return []
	}
	return strdata.toString().split(',')
}

export function isTargetInSameGroup(arr, currentElement, targetDanyuanId) {
  // 1. 参数校验
  if (!Array.isArray(arr) || arr.length === 0) return false;
  if (!currentElement || !targetDanyuanId) return false;

  // 2. 将数组拆分为4个一组的二维数组
  const chunkSize = 4;
  const groupedArray = [];
  for (let i = 0; i < arr.length; i += chunkSize) {
    groupedArray.push(arr.slice(i, i + chunkSize));
  }

  // 3. 查找包含当前元素的子数组
  const currentGroup = groupedArray.find(group => 
    group.some(item => item.danyuanId === currentElement.danyuanId)
  );

  // 4. 判断目标jieId是否在该子数组中
  if (!currentGroup) return false;
  return currentGroup.some(item => item.danyuanId === targetDanyuanId);
}

export function useActiveDomIntoView(classNameParent, classNameActive) {
	nextTick(() => {
		const container = document.querySelector(classNameParent);
		const highlightItem = document.querySelector(classNameActive);

		// 1. 检查元素是否已在可视区
		const containerRect = container.getBoundingClientRect();
		const activeRect = highlightItem.getBoundingClientRect();
		const isVisible = activeRect.left >= containerRect.left &&
			activeRect.right <= containerRect.right;
		if (isVisible) return;

		// 2. 优先使用 scrollIntoView
		const supportsSmoothScroll = 'scrollBehavior' in document.documentElement.style;
		if (supportsSmoothScroll) {
			highlightItem.scrollIntoView({
				behavior: 'smooth',
				inline: 'center',
				block: 'nearest'
			});
		} else {
			// 3. 降级方案：瞬时滚动 + 手动动画
			const targetPos = highlightItem.offsetLeft - container.offsetLeft;
			container.scrollTo({ left: targetPos });
		}
	});
}