import { MessageBox } from 'element-ui';
import WebSocketManager from './WebSocketManager';

/**
 * obj对象 key添加前缀 转化
 * obj = { a: 1，  b: 1， c: 1 }
 * str = 'deal'
 * 转化后 ==》
 * obj = { 'deal.a': 1，  'deal.b': 1， 'deal.c': 1}
 */
export function objAddPrefix(obj, str) {
  for (const key in obj) {
    obj[`${str}.${key}`] = obj[key];
    delete obj[key];
  }
  return obj;
}

export const confirmAction = async function(tip, type, title = '操作', customClass = '', showCancelButton = true) { // 二次确认提示 确认框
  // tip: 提示文案  type: 弹框类型  success / info / warning / error
  return await MessageBox.confirm(tip, title, {
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: type || 'error',
    customClass: customClass,
    showCancelButton,
  })
    .then(() => {
      return true;
    })
    .catch(() => {
      return false;
    });
};

let wsManager = null;
export const appInit = async() => {
  // 创建 WebSocketManager 实例，初始化 WebSocket 连接
  wsManager = new WebSocketManager('/page-600161', (actionId) => {
    if (actionId === '消息提醒') {
      Eui.App.sendNotice({
        showType: 'all',
        level: 'success',
        title: '交易成功',
        content: '您发起的001产品市价交易成功！',
        attribute: {},
      });
    }
  });
  // console.log(11111111, Eui.server);
  // wsManager.init();
  // 监听消息提醒点击事件
  // Eui.Ipc.addSubscribes(
  //   {
  //     '消息提醒点击': (attribute) => {
  //       Eui.service.router.push(attribute.path);
  //     }
  //   },
  //   { scopeId: Eui.scopeId },
  // );

  // 存储cookie
  document.cookie = `user.loginId=${Eui.Share.get('loginId')}; path=/`;
  document.cookie = `user.bankId=${Eui.Share.get('bankId')}; path=/`;
  // 存储语言设置到cookie，适配xfunds的zh_CN和en_US
  let language = '';
  let lanFlag = '';
  if (window.localStorage.getItem('system:share:i18n')) {
    lanFlag = window.localStorage.getItem('system:share:i18n');
  } else {
    lanFlag = Eui.Share.get('language');
  }
  if (lanFlag === 'en_US') {
    language = 'en';
  }
  if (lanFlag === 'zh' || lanFlag === 'zh_CN') {
    language = 'zh-cn';
  }
  if (language === '') {
    language = Eui.Share.get('language');
  }
  document.cookie = `ecas_language=${language}; path=/`;
};

export function dateFormat(fmt, date) {
  let ret;
  const opt = {
    'Y+': date.getFullYear().toString(), // 年
    'M+': (date.getMonth() + 1).toString(), // 月
    'D+': date.getDate().toString(), // 日
    'H+': date.getHours().toString(), // 时
    'm+': date.getMinutes().toString(), // 分
    's+': date.getSeconds().toString(), // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (const k in opt) {
    ret = new RegExp('(' + k + ')').exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')));
    }
  }
  return fmt;
}

const commonMore = {
  /**
   * 导出请求参数处理
   * @authors shuixx
   * @createDate 2019/11/14 9:37
   * @param {String} moduleName
   * @param {String} dgId
   * @param {String} queryForm
   * @param {String} exportName
   * @param {Function?} paramsHandler
   * @return {Object}
   */
  dataHandler(exportParams) {
    const afterColumns = exportParams.columns.map(v => {
      return {
        width: v.width,
        align: v.align,
        title: v.label,
        field: v.name === 'action' ? 'operation' : v.name,
        fixed: v.fixed,
      };
    });
    const data = { ...exportParams, columns: afterColumns.filter(v => !v.fixed), frozenColumns: afterColumns.filter(v => v.fixed) };
    console.log(afterColumns, data, 'dddd');
    Array.isArray(data.columns) && data.columns.forEach(commonMore.setColWidth);
    Array.isArray(data.frozenColumns) && data.frozenColumns.forEach(commonMore.setColWidth);
    data.fileName = this.encodeUnicode(data.fileName);
    data.columns = this.encodeUnicode(JSON.stringify(this.handlerColumnsTitle(data.columns)));
    data.frozenColumns = this.encodeUnicode(JSON.stringify(this.handlerColumnsTitle(data.frozenColumns)));
    data.params = this.encodeUnicode(JSON.stringify(this.handleParams({ ...data.params,
      start: data.params.pageStart, limit: data.params.limit, pageNumber: data.params.pageStart, pageSize: data.params.pageLimit,
    })));
    const transformedParams = {};
    for (const key in data) {
      transformedParams[`queryParam.${key}`] = data[key];
    }

    return transformedParams;
  },
  handleParams(params) {
    const newObject = {};
    for (const key in params) {
      if (key.startsWith('queryParam.')) {
        const newKey = key.replace('queryParam.', '');
        newObject[newKey] = params[key];
      } else {
        newObject[key] = params[key];
      }
    }
    return newObject;
  },
  /**
   * 导出列宽设置
   * @authors shuixx
   * @createDate 2019/11/20 17:16
   * @param {Object} col
   */
  setColWidth(col) {
    if (isNaN(col.width)) {
      const number = parseFloat(col.width);
      if (isNaN(number)) {
        col.width = 20;
      } else {
        col.width = 2 * number;
      }
    } else {
      col.width /= 8;
    }
  },
  /**
   * 编码
   * @authors shuixx
   * @createDate 2019/8/29 11:03
   * @param {String} str
   * @return {String}
   */
  encodeUnicode(str) {
    var res = [];
    for (var i = 0; i < str.length; i++) {
      res[i] = ('00' + str.charCodeAt(i).toString(16)).slice(-4);
    }
    return '\\u' + res.join('\\u');
  },
  /**
   * 列标题处理
   * @authors shuixx
   * @createDate 2019/8/29 11:06
   * @param {Array} columns
   * @return {Array}
   */
  handlerColumnsTitle(columns) {
    for (let i = 0; i < columns.length; i++) {
      const column = columns[i];
      columns[i].title = $(`<span>${column.title}</span>`).text();
    }
    return columns;
  },
};
export { commonMore };

// 防抖
export function debounce(func, wait) {
  let timer;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
}

// 金额千分位格式化
// amount: 金额
// decimal: 小数位数，默认2位
export function formatMoney(amount, decimal = 2) {
  if (amount === undefined || amount === null || isNaN(amount)) {
    return (0).toFixed(decimal);
  }

  // 确保金额为数字类型
  amount = parseFloat(amount);

  // 保留小数位并分离整数和小数部分
  const [integerPart, decimalPart] = amount.toFixed(decimal).split('.');

  // 使用正则表达式为整数部分添加千分位逗号
  const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

  // 拼接整数部分和小数部分
  return `${formattedInteger}.${decimalPart}`;
}

export function setCurrency(data, columns) { // 设置本地货币和损益货币
  if (data.length > 0) {
    columns.map(v => {
      if (v.label.includes('(本地货币)') || v.label.includes('（本地货币）')) {
        v.label = v.label.replaceAll('本地货币', data[0].LocalCurrency || data[0]?.children[0]?.LocalCurrency || data[0]._G_localCurrency);
      }
      if (v.label.includes('(损益货币)') || v.label.includes('（损益货币）')) {
        v.label = v.label.replaceAll('损益货币', data[0].PNLCurrency || data[0]?.children[0]?.PNLCurrency || data[0]._G_plCurrency);
      }
      return v;
    });
  }
}

// 格式化日期
export function formateDate(date) {
  const date1 = date.toString()
  if (date1.length < 8) return date1
  const year = date1.substr(0, 4)
  const month = date1.substr(4, 2)   
  const day = date1.substr(6, 2)
  return `${year}-${month}-${day}`
}
