import style from '../ReportsManage.less';
import extraComponents from '../extra/extraComponents';
import moment from 'moment';
import { Tag } from 'antd';
import { hasMoney, isNumber, returnHandledNumber } from './utils';
import { tagColors, tagBackgroundColors } from './constant';

/**
 * @params: config下的数值的configRule结构如下，[{最大值: 10,最小值: 0,颜色:'#AAAAAA'}];
 * @business: configRule有值，则按照configRule设置；没有，按照color设置； 有最大值，无最小值；['', 1]
 *            有最大值，有最小值；[2,
 *
 *        10]
 *            有最小值，无最大值；[11,'']
 */
// 链接 功能 弹窗功能待提出需求
// 函数名、属性、...
const clickLink = (config) => {
  return window.open(config.configItems, '_blank');
};
const handleUrl = (allWidgets, config) => {};
const handleConfigUrl = (config, record) => {
  let _configs = config.configItems.split('|');
  // type = 替换|跳转；
  let _type = '';
  //url=project/pandawork/contractDetails/index?ageSize=100&accountName=软件订单台账|contractCode=${订单编号}|company=${分公司}
  let _url = '';
  let _params = {};
  _configs.forEach((item) => {
    if (item.includes('type=')) _type = item.replace('type=', '');
    if (item.includes('url=')) {
      let _tempUrl = item.replace('url=', '');
      let _urlArray = _tempUrl.split('?');
      if (_urlArray[1]) {
        _urlArray[1].split('&').forEach((param) => {
          let _paramArr = param.split('=');
          if (_paramArr[1] && _paramArr[1].includes('${') && _paramArr[1].includes('}')) {
            let _key = _paramArr[1].replace(/\$\{|\}/g, '');
            _params[_paramArr[0]] = record[_key];
          } else {
            _params[_paramArr[0]] = _paramArr[1];
          }
        });
      }
      _url = _urlArray[0];
    }
  });
  return { url: _url, type: _type, params: _params };
};
const clickWidget = (config, text, record, showComponents, setDetailsConfig) => {
  // 功能跳转接口
  // type=替换|url=product/ReportsManage/ReportsSetting?accountName=${ID}&pageSize=100&title=${name}
  if (!config.configItems) return message.error('未配置跳转信息');
  // setDetailsComponentVisible(true);
  showComponents(true);
  let urlConfig = handleConfigUrl(config, record);
  // setDetailConfig(urlConfig);
  setDetailsConfig(urlConfig);
};
const clickModal = (config, showModal, setExtra) => {
  let _splitArr = config.configItems.split('&');
  let _fn = _splitArr[0] || 'default';
  _splitArr.splice(0, 1);
  let _data = {};
  _splitArr.forEach((item) => {
    let _item = item.split('=');
    _data[_item[0]] = _item[1];
  });
  // setExtraModal(true);
  showModal(true);
  return setExtra(extraComponents[_fn](_data));
};
const returnOpacity = (rgba) => {
  if (!rgba) rgba = 'rgba(0,0,0,.65)';
  let _str = rgba.replace('rgba(', '').replace(')', '');
  let _splitStr = _str.split(',');
  return `rgba(${_splitStr[0]},${_splitStr[1]},${_splitStr[2]},.25)`;
};
export const handleNumber = (config, number) => {
  let _color = '';
  let _number;
  if (number || number === 0) _number = Number(number); // 当设置精度后，会被转成字符串
  if (config.type === '数值' && config.numericalConfigs && config.numericalConfigs.length) {
    config.numericalConfigs.forEach((item) => {
      // 接口对于数值类型的返回为null
      if (!_color) {
        let _max = isNumber(item.maxValue) ? item.maxValue : '';
        let _min = isNumber(item.minValue) ? item.minValue : '';
        if (_max !== '' && _min === '') {
          _color = _number <= Number(_max) ? item.color : '';
        } else if (_min !== '' && _max === '') {
          _color = _number > Number(_min) ? item.color : '';
        } else {
          _color = _number > Number(_min) && _number <= Number(_max) ? item.color : '';
        }
      }
    });
  } else if (config.type === '数值标签' && config.labelConfigs && config.labelConfigs.length) {
    console.log('数值标签');
    _color = 'red';
  } else if (config.color) {
    _color = config.color;
  }
  return ![null, undefined, ''].includes(number) ? <span>
    <span className={style.prefixOrSuffix} style={{
      color: _color,
    }}>{config.prefix || ''}</span>
    <span style={{
      color: _color,
      margin: '0 5px',
    }}>{returnHandledNumber(config.configItems, number)}</span>
    <span className={style.prefixOrSuffix} style={{ color: _color }}>{config.suffix || ''}</span>
  </span> : '-';
};
export const handleNumberTag = (config, number) => {
  let _color = '';
  let _map = {};
  // 标签需要设置分隔符 2022年7月13日 ChenLong
  let _configItems = config.configItems.split('|');
  let _configMap = {};
  _configItems.forEach((item) => {
    let _arr = item.split('=');
    _configMap[_arr[0]] = _arr[1];
  });
  // 处理label的颜色
  if (config.labelConfigs && config.labelConfigs.length) {
    config.labelConfigs.forEach((item) => {
      _map[item.labelValue] = item.color;
    });
  }
  _color = config.color || 'rgba(0,0,0,.85)';
  // String(text)为了解决可能存在数值类型的数据需要设置成标签的需求
  // return String(text).split(_configMap['分隔符']).map(item => <Tag color={_map[item]}>{item}</Tag>);
  // let a = 'abc' a.split(undefined); a = ['abc']
  let _number = returnHandledNumber(config.configItems, number);
  return ![null, undefined, ''].includes(number) ? <Tag style={{
    background: mapTag(_map, number) || '',
    border: mapTag(_map, number) ? `1px solid ${mapTag(_map, number)}` : '',
    borderRadius: 2,
    color: mapTag(_map, number) ? tagColors[tagBackgroundColors.findIndex(c => c === mapTag(_map, number))] : `rgba(0, 0, 0, .65)`,
  }}>{(config.prefix || '') + _number + (config.suffix || '')}</Tag> : '-';
};
/** @params: 标签形态的configRule，[{标签值:'字符串',颜色: '#AAAAAA'}]; */
/* 支持正则配置 RegExp */
export const handleTag = (config, text) => {
  let _color = '';
  let _map = {};
  // 标签需要设置分隔符 2022年7月13日 ChenLong
  let _configItems = config.configItems.split('|');
  let _configMap = {};
  _configItems.forEach((item) => {
    let _arr = item.split('=');
    _configMap[_arr[0]] = _arr[1];
  });
  // 处理label的颜色
  if (config.labelConfigs && config.labelConfigs.length) {
    config.labelConfigs.forEach((item) => {
      _map[item.labelValue] = item.color;
    });
  }
  _color = config.color || 'rgba(0,0,0,.85)';
  // String(text)为了解决可能存在数值类型的数据需要设置成标签的需求
  // return String(text).split(_configMap['分隔符']).map(item => <Tag color={_map[item]}>{item}</Tag>);
  // let a = 'abc' a.split(undefined); a = ['abc']
  return String(text).split(_configMap['分隔符']).map(item => <Tag style={{
    background: mapTag(_map, item) || _color,
    border: `1px solid ${mapTag(_map, item) || _color}`,
    borderRadius: 2,
    color: mapTag(_map, item) ? tagColors[tagBackgroundColors.findIndex(c => c === mapTag(_map, item))] : `rgba(0, 0, 0, .65)`,
  }}>{item}</Tag>);
};
const mapTag = (map, key) => {
  if (map[key]) {
    return map[key];
  } else {
    let _keys = Object.keys(map);
    return _keys.reduce((final, _key) => {
      let isRegExp = _key.includes('RegExp=');
      let reg = new RegExp(_key.replace('RegExp=', ''));
      if (isRegExp && reg.test(key)) {
        final = map[_key];
      }
      return final;
    }, '');
  }
};
export const handleText = (config, text) => {
  const { labelConfigs } = config;
  let _config = null;
  if (labelConfigs && labelConfigs.length) {
    _config = labelConfigs.find(item => item.labelValue === text);
  }
  return <span style={{ color: _config?.color || config.color || 'rgba(0,0,0,.85)' }}>{text}</span>;
};
export const handleLink = (config, text) => {
  return <span className={style.link} style={{
    color: config.color || 'rgba(0,0,0,.85)',
  }} onClick={() => clickLink(config)}>{text}</span>;
};
export const handleWidget = (config, text, record, showComponents, setDetailsConfig) => {
  return <span style={{ color: config.color }} className={style.link}
               onClick={() => clickWidget(config, text, record, showComponents, setDetailsConfig)}>{text}</span>;
};
export const handleModal = (config, text, showModal, setExtra) => {
  return <span className={style.link} style={{ color: config.color || 'rgba(0,0,0,.85)' }}
               onClick={() => clickModal(config, showModal, setExtra)}>{text}</span>;
};
// 日期
export const handleDateString = (config, text) => {
  return text ? moment(text).format('YYYY-MM-DD') : '-';
};
// 时刻
export const handleDateTimeString = (config, text) => {
  return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '-';
};
// 处理pageSize
export const handlePageSize = (numStr) => {
  return numStr && isNumber(Number(numStr)) ? Number(numStr) : false;
};
// 处理默认排序
export const handleSortFields = (sortFields) => {
  return (sortFields && sortFields.split(',')) || [];
};
