import config from '@/config'
import { getToken } from '@/utils/auth'
import { listCheckApprovalCcDetails, listCheckPendingTasks } from "@/api/myToDoList/myToDoList.js"
import { listData } from "@/api/system/dict/data.js"
/**
* 显示消息提示框
* @param content 提示的标题
*/
export function toast(content) {
  uni.showToast({
    icon: 'none',
    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 = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    var part = encodeURIComponent(propName) + "="
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']'
            var subPart = encodeURIComponent(params) + "="
            result += subPart + encodeURIComponent(value[key]) + "&"
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&"
      }
    }
  }
  return result
}

export function getDate(date, AddDayCount = 0) {
  if (!date) {
    date = new Date()
  }
  if (typeof date !== 'object') {
    date = date.replace(/-/g, '/')
  }
  const dd = new Date(date)

  dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期

  const y = dd.getFullYear()
  const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期，不足10补0
  const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
  return {
    fullDate: y + '-' + m + '-' + d,
    year: y,
    month: m,
    date: d,
    day: dd.getDay()
  }
}

export function serializeData(obj) {
  let str = '?'
  Object.keys(obj).forEach(function (key) {
    str += key + "=" + obj[key] + '&'
  });

  let reg = /&$/gi;
  str = str.replace(reg, ""); //清除最后一个&符号
  return str
}


export function buildTeamOptions(tree = [], includeFullData = false) {
  const result = [];

  function dfs(node, path = []) {
    const currentPath = [...path, node.label];
    // 如果是 TEAMS 叶子节点
    if (node.deptType === 'TEAMS') {
      if (includeFullData) {
        // 包含完整节点数据
        result.push({
          ...node,
          text: currentPath.join(' / '),
          value: node.id,
          path: currentPath,
          children: null
        });
      } else {
        // 只包含text和value
        result.push({
          text: currentPath.join(' / '),
          value: node.id
        });
      }
    }
    // 继续递归子节点
    if (node.children && Array.isArray(node.children)) {
      node.children.forEach(child => dfs(child, currentPath));
    }
  }

  tree.forEach(root => dfs(root));
  return result;
}

/**
 * 找出deptType为DEPARTMENT的节点
 * @param {Array} tree - 树形结构数据
 * @param {boolean} includeFullData - 是否包含节点的完整数据，默认false
 * @returns {Array} 包含所有DEPARTMENT节点的数组
 */
export function buildDepartmentOptions(tree = [], includeFullData = false) {
  const result = [];

  function dfs(node, path = []) {
    const currentPath = [...path, node.label];
    // 如果是 DEPARTMENT 节点
    if (node.deptType === 'DEPARTMENT') {
      if (includeFullData) {
        // 包含完整节点数据
        result.push({
          ...node,
          text: currentPath.join(' / '),
          value: node.id,
          path: currentPath,
          children: null
        });
      } else {
        // 只包含text和value
        result.push({
          text: currentPath.join(' / '),
          value: node.id
        });
      }
    }
    // 继续递归子节点
    if (node.children && Array.isArray(node.children)) {
      node.children.forEach(child => dfs(child, currentPath));
    }
  }

  tree.forEach(root => dfs(root));
  return result;
}

/**
 *
/**
 * 找出deptType为BRIGADE的节点
 * @param {Array} tree - 树形结构数据
 * @param {boolean} includeFullData - 是否包含节点的完整数据，默认false
 * @returns {Array} 包含所有BRIGADE节点的数组
 */
export function buildBrigadeOptions(tree = [], includeFullData = false) {
  const result = [];

  function dfs(node, path = []) {
    const currentPath = [...path, node.label];
    // 如果是 DEPARTMENT 节点
    if (node.deptType === 'BRIGADE') {
      if (includeFullData) {
        // 包含完整节点数据
        result.push({
          ...node,
          text: currentPath.join(' / '),
          value: node.id,
          path: currentPath,
          children: null
        });
      } else {
        // 只包含text和value
        result.push({
          text: currentPath.join(' / '),
          value: node.id
        });
      }
    }
    // 继续递归子节点
    if (node.children && Array.isArray(node.children)) {
      node.children.forEach(child => dfs(child, currentPath));
    }
  }

  tree.forEach(root => dfs(root));
  return result;
}

/**
 * 找出deptType为BRIGADE的节点
 * @param {Array} tree - 树形结构数据
 * @param {boolean} includeFullData - 是否包含节点的完整数据，默认false
 * @returns {Array} 包含所有BRIGADE节点的数组
 */
export function buildManagerOptions(tree = [], includeFullData = false) {
  const result = [];

  function dfs(node, path = []) {
    const currentPath = [...path, node.label];
    // 如果是 DEPARTMENT 节点
    if (node.deptType === 'MANAGER') {
      if (includeFullData) {
        // 包含完整节点数据
        result.push({
          ...node,
          text: currentPath.join(' / '),
          value: node.id,
          path: currentPath,
          children: null
        });
      } else {
        // 只包含text和value
        result.push({
          text: currentPath.join(' / '),
          value: node.id
        });
      }
    }
    // 继续递归子节点
    if (node.children && Array.isArray(node.children)) {
      node.children.forEach(child => dfs(child, currentPath));
    }
  }

  tree.forEach(root => dfs(root));
  return result;
}

//将数组格式的按照航站楼分成对象格式
export function getHandleAreaData(data, notkezhang) {
  let louObj = {};
  let areaArr = [];
  data.forEach(element => {

    let name = `${element.terminlName}-${element.terminlCode}`
    if (!louObj[name]) {
      louObj[name] = [];
    }
    louObj[name].push({
      ...element,
      label: notkezhang ? element.channelName : element.regionalName,
      code: notkezhang ? element.channelCode : element.regionalCode,
    });
  });

  Object.keys(louObj).forEach(key => {
    areaArr.push({
      label: key.split('-')[0],
      code: key.split('-')[1],
      children: louObj[key]
    });
  });

  return areaArr;
}


// 封装上传
export function uploadFile(event) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `${config.baseUrl}/common/upload`,
      filePath: event.tempFilePaths[0],
      name: 'file',
      header: { Authorization: 'Bearer ' + getToken() },
      success: (res) => resolve(JSON.parse(res.data)),
      fail: reject
    });
  });
}

// 为消息tab显示红点
export async function showMessageTabRedDot() {
  try {
    const query = {
      pageNum: 1,
      pageSize: 9999
    };

    let total = 0
    let response = await listCheckPendingTasks(query);
    total += response.total;
    let response1 = await listCheckApprovalCcDetails(query);
    total += response1.rows.filter(item => item.isRead == '0').length;
    if (total > 0) {
      // 消息tab在tabBar列表中的索引是1（从0开始）
      uni.showTabBarRedDot({
        index: 1,
        success: () => {
          // console.log('消息tab红点显示成功')
        },
        fail: (err) => {
          // console.log('消息tab红点显示失败:', err)
          // 如果使用自定义tabBar时原生API失败，可以在这里添加自定义处理逻辑
        }
      })
    } else {
      // 当total等于0时，取消消息tab上的红点显示
      uni.hideTabBarRedDot({
        index: 1,
        success: () => {
          console.log('消息tab红点隐藏成功')
        },
        fail: (err) => {
          console.log('消息tab红点隐藏失败:', err)
        }
      })
    }
  } catch (error) {
  }
}

/**
 * 文字截断函数，超过指定长度显示省略号
 * @param {string} text - 需要截断的文本
 * @param {number} maxLength - 最大长度，默认10
 * @param {string} suffix - 后缀，默认'...'
 * @returns {string} 截断后的文本
 */
export function truncateText(text, maxLength = 10, suffix = '...') {
  if (!text || typeof text !== 'string') {
    return '';
  }

  // 如果文本长度小于等于最大长度，直接返回原文本
  if (text.length <= maxLength) {
    return text;
  }

  // 截取文本并添加后缀
  return text.substring(0, maxLength) + suffix;
}

/**
 * 智能文字截断函数，考虑中英文混合情况
 * @param {string} text - 需要截断的文本
 * @param {number} maxLength - 最大长度（按字符数计算），默认10
 * @param {string} suffix - 后缀，默认'...'
 * @returns {string} 截断后的文本
 */
export function smartTruncateText(text, maxLength = 10, suffix = '...') {
  if (!text || typeof text !== 'string') {
    return '';
  }

  // 计算字符数（中文字符算1个，英文字符算0.5个）
  let charCount = 0;
  let result = '';

  for (let i = 0; i < text.length; i++) {
    const char = text[i];
    // 中文字符范围
    if (char.charCodeAt(0) > 127) {
      charCount += 1;
    } else {
      charCount += 0.5;
    }

    // 如果超过最大长度，添加后缀并返回
    if (charCount > maxLength) {
      return result + suffix;
    }

    result += char;
  }

  // 如果文本长度小于等于最大长度，直接返回原文本
  return text;
}

/**
 * 按单词截断文本（适用于英文文本）
 * @param {string} text - 需要截断的文本
 * @param {number} maxWords - 最大单词数，默认5
 * @param {string} suffix - 后缀，默认'...'
 * @returns {string} 截断后的文本
 */
export function truncateByWords(text, maxWords = 5, suffix = '...') {
  if (!text || typeof text !== 'string') {
    return '';
  }

  const words = text.trim().split(/\s+/);

  if (words.length <= maxWords) {
    return text;
  }

  return words.slice(0, maxWords).join(' ') + suffix;
}

/**
 * 根据字典值获取对应的字典文字
 * @param {string} dictType - 字典类型
 * @param {string|number} dictValue - 字典值
 * @param {string} defaultValue - 默认返回值，当找不到对应字典文字时返回
 * @returns {Promise<string>} 字典文字
 */
export async function getDictLabelByValue(dictType, dictValue, defaultValue = '') {
  if (!dictType || dictValue === undefined || dictValue === null) {
    return defaultValue;
  }

  try {
    // 调用listData接口获取字典数据
    const response = await listData({
      dictType: dictType,
      dictValue: dictValue.toString()
    });

    // 如果接口返回成功且有数据
    if (response.code === 200 && response.rows && response.rows.length > 0) {


      return response.rows.find(item => item.dictValue === dictValue.toString())?.dictLabel || defaultValue;
    }

    return defaultValue;
  } catch (error) {
    console.error('获取字典文字失败:', error);
    return defaultValue;
  }
}

/**
 * 检查角色是否有访问特定路径的权限
 * @param {string} role - 角色名称
 * @param {string} path - 访问路径
 * @returns {boolean} 是否有权限
 */
export function checkRolePermission(role, path) {
  // 角色权限配置对象
  const rolePermissions = {
    //安检员
    SecurityCheck: [
      '/pages/attendance/index',
      `/pages/seizedReported/index?params=${encodeURIComponent(JSON.stringify({ type: 'add' }))}`,
      '/pages/daily-exam/task-list/index',
      '/pages/eikonStatistics/index',
      '/pages/seizureRecord/index',
      '/pages/seizeStatistics/index',
      '/pages/voiceSubmissionDraft/index'
    ],
    //班组长
    banzuzhang: [
      '/pages/attendance/index',
      `/pages/seizedReported/index?params=${encodeURIComponent(JSON.stringify({ type: 'add' }))}`,
      '/pages/daily-exam/task-list/index',
      '/pages/inspectionChecklist/index',
      '/pages/eikonStatistics/index',
      '/pages/seizureRecord/index',
      '/pages/seizeStatistics/index',
      '/pages/inspectionStatistics/index',
      '/pages/questionStatistics/index',
      '/pages/voiceSubmissionDraft/index'
    ],
    //站长
    kezhang: [
      '/pages/attendance/index',
      '/pages/attendanceStatistics/index',
      '/pages/inspectionChecklist/index',
      '/pages/questionStatistics/index',
      '/pages/inspectionStatistics/index',
      '/pages/seizureRecord/index',
      '/pages/seizeStatistics/index',
      '/pages/eikonStatistics/index',
      '/pages/workProfile/index',
      '/pages/voiceSubmissionDraft/index'
    ],
    //站长
    test: [
      '/pages/attendanceStatistics/index',
      '/pages/inspectionChecklist/index',
      '/pages/questionStatistics/index',
      '/pages/inspectionStatistics/index',
      '/pages/seizureRecord/index',
      '/pages/seizeStatistics/index',
      '/pages/eikonStatistics/index',
      '/pages/workProfile/index',
      '/pages/voiceSubmissionDraft/index'
    ],
    zhijianke: [
      '/pages/attendanceStatistics/index',
      '/pages/inspectionChecklist/index',
      '/pages/questionStatistics/index',
      '/pages/inspectionStatistics/index',
      '/pages/seizureRecord/index',
      '/pages/seizeStatistics/index',
      '/pages/eikonStatistics/index',
      '/pages/workProfile/index',
      '/pages/voiceSubmissionDraft/index'
    ],
  };

  // 检查角色是否存在配置
  if (!rolePermissions[role]) {
    console.warn(`未找到角色 ${role} 的权限配置`);
    return false;
  }

  // 检查路径是否在角色的权限列表中
  return rolePermissions[role].includes(path);
}



