"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useOkrColumns = exports.dic = exports["default"] = void 0;

var _react = require("react");

var _setting = require("./setting");

var _getLocale = require("../../utils/getLocale");

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

// 当需要强制更新客户端缓存的列配置时可以更改此版本号
var columnOptionVersion = '1.0.0';

var dic = function dic() {
  return {
    '目标': (0, _getLocale.getLocale)('Mod_Objective'),
    '关键成果': (0, _getLocale.getLocale)('Mod_KeyResults'),
    '目标（O）': "".concat((0, _getLocale.getLocale)('Mod_Objective'), "\uFF08O\uFF09"),
    '类型': (0, _getLocale.getLocale)('OKR_MyO_Pop_Type'),
    '负责人': (0, _getLocale.getLocale)('OKR_MyO_Pop_Owner'),
    '对齐目标负责人': (0, _getLocale.getLocale)('OKR_MyO_AlignOOwner'),
    '可见范围': (0, _getLocale.getLocale)('OKR_MyO_Pop_Title_Perm'),
    '目标完成度': "".concat((0, _getLocale.getLocale)('Mod_Objective')).concat((0, _getLocale.getLocale)('OKR_MyO_Pop_Upd_Progresss1')),
    '目标最新进展': "".concat((0, _getLocale.getLocale)('Mod_Objective')).concat((0, _getLocale.getLocale)('Pro_page_Plan_Latestpro')),
    '关键成果（KR）': "".concat((0, _getLocale.getLocale)('Mod_KeyResults'), "\uFF08KR\uFF09"),
    'KR 负责人': "KR ".concat((0, _getLocale.getLocale)('OKR_MyO_Pop_Owner')),
    '权重': (0, _getLocale.getLocale)('OKR_MyO_Text_Weights'),
    '信心指数': (0, _getLocale.getLocale)('OKR_MyO_KRP_Confidence'),
    'KR 完成度': "KR ".concat((0, _getLocale.getLocale)('OKR_MyO_Pop_Upd_Progresss1')),
    'KR 最新进展': "KR ".concat((0, _getLocale.getLocale)('Pro_page_Plan_Latestpro'))
  };
};

exports.dic = dic;

// 判断是否需要重置缓存，避免出现客户端缓存无法失效问题
function needCoverCache(optionDic, columns) {
  var cacheVersion = localStorage.getItem('columnOptionVersion'); // 如果版本号不一致

  if (cacheVersion !== columnOptionVersion) {
    localStorage.setItem('columnOptionVersion', columnOptionVersion);
    return true;
  } // 如果 columns 有新增的列时


  var newColumn = columns.find(function (item) {
    return !optionDic[item.field];
  }); // 这里这么写方便后续扩展

  if (newColumn) return true;
  return false;
}

function createDefaultOptions(cacheOptionDic, columns) {
  var optionDic = {};
  columns.forEach(function (item, idx) {
    optionDic[item.field] = {
      key: item.field,
      hide: item.hide || false,
      width: item.width,
      idx: idx
    }; // 如果存在缓存，则复用现有的显示状态，避免在重置缓存后让用户以为是BUG

    if (cacheOptionDic[item.field]) {
      optionDic[item.field].hide = cacheOptionDic[item.field].hide;
    }
  });
  return optionDic;
}

function getCacheColumnOptions(columns) {
  var optionStr = localStorage.getItem('cacheOkrColumnOptions') || '{}';
  var optionDic = JSON.parse(optionStr);
  if (optionStr === '{}' || needCoverCache(optionDic, columns)) optionDic = createDefaultOptions(optionDic, columns);
  return optionDic;
}

function setCacheColumnOptions(option) {
  localStorage.setItem('cacheOkrColumnOptions', JSON.stringify(option));
}
/** 判断是否开启了高级功能，如果没有开启，则将 hide 设置为 false */


function getHide(field, currentHide) {
  var dicData = dic();

  switch (field) {
    case dicData['类型']:
      if (!_setting.showKrClassify) return true;
      return currentHide;

    case dicData['信心指数']:
      if (!_setting.showKrConfidence) return true;
      return currentHide;

    case dicData['权重']:
      if (!_setting.showKrWeight) return true;
      return currentHide;

    case dicData['KR 最新进展']:
      if (!_setting.showKrProgress) return true;
      return currentHide;

    default:
      return currentHide;
  }
}

function formatColumnsByOption(optionDic, columns) {
  var formatColumn = new Array(columns.length);

  try {
    columns.forEach(function (item) {
      var option = optionDic[item.field];
      formatColumn[option.idx] = _objectSpread(_objectSpread({}, item), {}, {
        hide: getHide(item.field, option.hide),
        width: option.width
      });
    });
  } catch (error) {
    // 避免解析过程中发生错误导致列无法展示
    setCacheColumnOptions(createDefaultOptions(optionDic, columns));
    return columns;
  }

  return formatColumn;
}

var defaultColumnCtlData = function defaultColumnCtlData() {
  var dicData = dic();
  return [{
    label: dicData['目标'],
    value: 'O',
    type: 'group',
    children: [{
      label: dicData['目标（O）'],
      value: '0,0',
      disable: true
    }, {
      label: dicData['类型'],
      value: '0,1',
      visible: _setting.showKrClassify
    }, {
      label: dicData['负责人'],
      value: '0,2'
    }, {
      label: dicData['对齐目标负责人'],
      value: '0,3'
    }, {
      label: dicData['可见范围'],
      value: '0,4'
    }, {
      label: dicData['目标完成度'],
      value: '0,5'
    }, {
      label: dicData['目标最新进展'],
      value: '0,6'
    }]
  }, {
    label: dicData['关键成果'],
    value: 'KR',
    type: 'group',
    children: [{
      label: dicData['关键成果（KR）'],
      value: '1,0'
    }, {
      label: dicData['KR 负责人'],
      value: '1,1'
    }, {
      label: dicData['信心指数'],
      value: '1,2',
      visible: _setting.showKrConfidence
    }, {
      label: dicData['权重'],
      value: '1,3',
      visible: _setting.showKrWeight
    }, {
      label: dicData['KR 完成度'],
      value: '1,4'
    }, {
      label: dicData['KR 最新进展'],
      value: '1,5',
      visible: _setting.showKrProgress
    }]
  }];
}; // 标记展示的列


function formatColumnCtlData(optionDic, columnCtlData) {
  columnCtlData.map(function (item) {
    return item.children || [];
  }).reduce(function (pre, cur) {
    return [].concat(_toConsumableArray(pre), _toConsumableArray(cur));
  }).forEach(function (item) {
    if (optionDic[item.label]) {
      item.checked = !optionDic[item.label].hide;
    } else {
      item.checked = false;
    }
  });
  return columnCtlData;
}

var useOkrColumns = function useOkrColumns(columns) {
  var _useState = (0, _react.useState)(getCacheColumnOptions(columns)),
      _useState2 = _slicedToArray(_useState, 2),
      optionDic = _useState2[0],
      setOptionDic = _useState2[1];

  var _useState3 = (0, _react.useState)(formatColumnsByOption(optionDic, columns)),
      _useState4 = _slicedToArray(_useState3, 2),
      columnDefs = _useState4[0],
      setColumnDefs = _useState4[1];

  (0, _react.useEffect)(function () {
    setColumnDefs(formatColumnsByOption(optionDic, columns));
  }, [columns]); // 右上角控制列是否展示的数据

  var _useState5 = (0, _react.useState)(formatColumnCtlData(optionDic, defaultColumnCtlData())),
      _useState6 = _slicedToArray(_useState5, 2),
      columnCtlData = _useState6[0],
      setColumnCtlData = _useState6[1]; // 用于处理列的移动事件，在用户下次访问时保持该顺序


  var onColumnMoved = (0, _react.useCallback)(function (moveField, toIndex) {
    var oldIdx = optionDic[moveField].idx;
    var success = 0;
    Object.values(optionDic).find(function (option) {
      if (success === 2) return true;

      if (option.idx === toIndex) {
        option.idx = oldIdx;
        success++;
        return success === 2;
      }

      if (option.idx === oldIdx) {
        option.idx = toIndex;
        success++;
        return success === 2;
      }
    });
    setOptionDic(_objectSpread({}, optionDic));
    setCacheColumnOptions(optionDic);
  }, [optionDic]);
  var onColumnResized = (0, _react.useCallback)(function (moveField, width) {
    optionDic[moveField].width = width;
    setOptionDic(_objectSpread({}, optionDic));
    setCacheColumnOptions(optionDic);
  }, [optionDic]);
  var onColumnsHideOrShow = (0, _react.useCallback)(function (value, item) {
    var _columnCtlData$level;

    var _ref = value.split(','),
        _ref2 = _slicedToArray(_ref, 2),
        level1Idx = _ref2[0],
        level2Idx = _ref2[1];

    var fieldName = item.label; // @ts-ignore

    var itemChecked = (_columnCtlData$level = columnCtlData[level1Idx]) === null || _columnCtlData$level === void 0 ? void 0 : _columnCtlData$level.children[level2Idx].checked;
    var checked = !itemChecked; // @ts-ignore

    columnCtlData[level1Idx].children[level2Idx].checked = checked;
    setColumnCtlData(_toConsumableArray(columnCtlData));

    if (optionDic[fieldName]) {
      optionDic[fieldName].hide = !checked;
      setOptionDic(_objectSpread({}, optionDic));
      setColumnDefs(formatColumnsByOption(optionDic, columns));
      setCacheColumnOptions(optionDic);
    }
  }, [columnCtlData, columns]);
  return {
    columnDefs: columnDefs,
    onColumnMoved: onColumnMoved,
    onColumnResized: onColumnResized,
    columnCtlData: columnCtlData,
    onColumnsHideOrShow: onColumnsHideOrShow
  };
};

exports.useOkrColumns = useOkrColumns;
var _default = useOkrColumns;
exports["default"] = _default;