"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

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

var _react = _interopRequireWildcard(require("react"));

var _moment = _interopRequireDefault(require("moment"));

var _toast = _interopRequireDefault(require("../../components/toast"));

var _okrcaseLibrary = _interopRequireDefault(require("../../components/okrcase-library"));

var _pagination = _interopRequireDefault(require("../../components/pagination"));

var _dialog = _interopRequireDefault(require("../../components/dialog"));

var _okrExcel = _interopRequireDefault(require("../../components/okr-excel"));

var _errorBoundary = _interopRequireDefault(require("../../components/error-boundary"));

var _header = _interopRequireWildcard(require("./header"));

var _list = _interopRequireDefault(require("./list"));

var _loading = _interopRequireDefault(require("./loading"));

var _bsGlobal = require("../../utils/bs-global");

var _tools = require("../../utils/tools");

var _localStorage = require("../../utils/local-storage");

var _errorLevel = _interopRequireDefault(require("../../utils/error-level"));

var _requestApi = require("./request-api");

var _context = require("./context");

var _precls = require("./precls");

require("./index.css");

require("./theme.css");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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 _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 _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 _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 _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 _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 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; }

function getOkrExcelData(okrData) {
  var okrExcelData = [];
  okrData.forEach(function (okrInfo) {
    if (!okrInfo.Krs || !okrInfo.Krs.length) {
      okrExcelData.push(_objectSpread({}, okrInfo));
      return;
    }

    okrInfo.Krs.forEach(function (kr, i) {
      // 过滤目标下的其他执行（默认分组）
      if (kr.mileStoneId === 0) return;

      var data = _objectSpread(_objectSpread({}, i === 0 ? okrInfo : {}), {}, {
        feedId: okrInfo.feedId,
        Kr: _objectSpread(_objectSpread({}, kr), {}, {
          index: i
        })
      });

      if (i === 0) data.rowSpan = okrInfo.Krs.filter(function (kr) {
        return kr.mileStoneId;
      }).length;
      okrExcelData.push(data);
    });
  });
  return okrExcelData;
}

var NewOkrList = function NewOkrList(props) {
  var OkrListCmp = props.OkrListCmp,
      OkrCommunicationPush = props.OkrCommunicationPush,
      Empty = props.Empty,
      SetCycleModal = props.SetCycleModal,
      OkrOperateRecordDrawer = props.OkrOperateRecordDrawer;
  var useLocalStorage = new _localStorage.LocalStorage();
  var formFieldValues = useLocalStorage.getItem('okr-filter-values') || {
    targetType: '',
    targetCategory: '',
    targetSort: '',
    okrType: '',
    okrClassify: '',
    orderType: 0
  };

  var filterCycle = function () {
    var routerData = (0, _tools.getQueryString)();
    var annualNum = routerData.annualNum,
        cycleType = routerData.cycleType,
        yqmNum = routerData.yqmNum;

    if (!!annualNum && !!cycleType && !!yqmNum) {
      return {
        annualNum: annualNum,
        cycleType: cycleType,
        yqmNum: yqmNum
      };
    }

    return useLocalStorage.getItem('okr-filter-cycle') || {
      annualNum: "".concat(new Date().getFullYear()),
      cycleType: '2',
      yqmNum: "".concat((0, _moment["default"])().quarter())
    };
  }();

  var showWorkExecution = (0, _bsGlobal.getBSGlobal)('OkrAdvancedSetting').KRSetting.ShowWorkExecution;

  var _useState = (0, _react.useState)(true),
      _useState2 = _slicedToArray(_useState, 2),
      loading = _useState2[0],
      setLoading = _useState2[1];

  var _useState3 = (0, _react.useState)([]),
      _useState4 = _slicedToArray(_useState3, 2),
      okrs = _useState4[0],
      setOkrs = _useState4[1];

  var _useState5 = (0, _react.useState)(0),
      _useState6 = _slicedToArray(_useState5, 2),
      total = _useState6[0],
      setTotal = _useState6[1];

  var _useState7 = (0, _react.useState)(1),
      _useState8 = _slicedToArray(_useState7, 2),
      pageNum = _useState8[0],
      setPageNum = _useState8[1];

  var _useState9 = (0, _react.useState)(10),
      _useState10 = _slicedToArray(_useState9, 2),
      pageSize = _useState10[0],
      setPageSize = _useState10[1];

  var _useState11 = (0, _react.useState)({
    okrType: formFieldValues.okrType,
    okrClassify: formFieldValues.okrClassify,
    orderType: formFieldValues.orderType,
    annualNum: filterCycle.annualNum,
    cycleType: filterCycle.cycleType,
    yqmNum: filterCycle.yqmNum,
    onlyThisDept: false,
    keyWords: ''
  }),
      _useState12 = _slicedToArray(_useState11, 2),
      query = _useState12[0],
      setQuery = _useState12[1];

  var okrsRef = (0, _react.useRef)(okrs);

  var _useState13 = (0, _react.useState)(false),
      _useState14 = _slicedToArray(_useState13, 2),
      isInit = _useState14[0],
      setIsInit = _useState14[1];

  var _useState15 = (0, _react.useState)(localStorage.getItem('cacheViewType') || _header.ViewType.Card),
      _useState16 = _slicedToArray(_useState15, 2),
      viewType = _useState16[0],
      setViewType = _useState16[1];

  var headerRef = (0, _react.useRef)();

  var _useState17 = (0, _react.useState)(false),
      _useState18 = _slicedToArray(_useState17, 2),
      casesVisible = _useState18[0],
      setCasesVisible = _useState18[1];

  var routerData = (0, _tools.getQueryString)();
  var departmentName = routerData.departmentName,
      departmentId = routerData.departmentId,
      locationRelation = routerData.relation,
      toUserId = routerData.toUserId;
  var relation;

  if (departmentId === undefined && toUserId === undefined && locationRelation === undefined) {
    relation = 1;
  } else {
    relation = locationRelation || 0;
  }

  (0, _react.useEffect)(function () {
    setPageNum(1);
  }, [relation, toUserId, departmentId, query]);

  var handleOnSearch = function handleOnSearch(params) {
    setQuery(_objectSpread(_objectSpread({}, query), params));
    setPageNum(1);
  };

  (0, _react.useEffect)(function () {
    if (isInit) {
      handleOnSearch({
        keyWords: ''
      });
    }
  }, [relation, toUserId, departmentId]);
  (0, _react.useEffect)(function () {
    setIsInit(true);
  }, []); // 记录访问者数据

  var recordVisitUser = function recordVisitUser() {
    if (toUserId) {
      (0, _requestApi.visitOkrCyclePag)(toUserId);
    }
  };

  var getOkrsRequest = function getOkrsRequest() {
    var params = _objectSpread(_objectSpread({
      relation: relation,
      toUserId: (0, _bsGlobal.getUserInfo)().Id,
      userIds: toUserId,
      searchKr: 0,
      status: 0,
      haveSubDept: false,
      departmentIds: departmentId
    }, query), {}, {
      pageNum: pageNum,
      pageSize: pageSize
    });

    if (showWorkExecution) {
      params.showOkrE = 1;
      params.Searchpage = 2;
    }

    if (departmentId !== 0 && departmentId !== '0') {
      params.keyWords = '';
    }

    recordVisitUser();
    (0, _requestApi.okrSearch)(params).then(function (res) {
      setOkrs(res && res.works || []);
      setTotal(res && res.total || 0);
      setLoading(false);
    });
  };

  var getOkrs = function getOkrs() {
    // 这个用于loading加载
    setLoading(true);
    getOkrsRequest();
  };

  var onRefreshOkrs = function onRefreshOkrs() {
    // 这个不要loading，推屏出来的时候用这个
    getOkrsRequest();
  };

  (0, _react.useEffect)(function () {
    okrsRef.current = okrs;
  }, [okrs]);

  var handlePageChange = function handlePageChange(nowPage, nowPageSize) {
    setPageNum(nowPage);
    setPageSize(nowPageSize);
  };

  var onFrontAddOKR = function onFrontAddOKR(data) {
    setOkrs([data].concat(_toConsumableArray(okrsRef.current || [])));
  };

  var isShowPrincple = (0, _react.useMemo)(function () {
    return !toUserId && Number(relation) !== 1;
  }, [toUserId, relation]);
  var isShowPeriod = (0, _react.useMemo)(function () {
    return Number(query.cycleType) === -1;
  }, [query]);
  var replaceOkr = (0, _react.useCallback)(function (data) {
    var index = okrsRef.current.findIndex(function (item) {
      return item.workId === data.workId;
    });
    okrsRef.current.splice(index, 1, data);
    setOkrs(_toConsumableArray(okrsRef.current));
  }, [okrs]);

  var openCreateModal = function openCreateModal() {
    if (headerRef.current) {
      headerRef.current.openCreateModal();
    }
  };

  var handleCaseChoosed = function handleCaseChoosed(data) {
    if (headerRef.current) {
      headerRef.current.openCreateModal();
      headerRef.current.setCase(data);
    }

    setCasesVisible(false);

    _toast["default"].Success('成功套用');
  };

  var onCasesCloseHandler = function onCasesCloseHandler() {
    return setCasesVisible(false);
  };

  (0, _react.useEffect)(function () {
    getOkrs();
  }, [pageNum, pageSize, query]);
  var onChangeViewTypeHandler = (0, _react.useCallback)(function (type) {
    localStorage.setItem('cacheViewType', type);
    setViewType(type);
  }, []);
  var okrExcelData = (0, _react.useMemo)(function () {
    return getOkrExcelData(okrs);
  }, [okrs]);
  return /*#__PURE__*/_react["default"].createElement(_context.Context.Provider, {
    value: _objectSpread({
      OkrCommunicationPush: OkrCommunicationPush,
      OkrOperateRecordDrawer: OkrOperateRecordDrawer,
      relation: relation,
      departmentName: departmentName,
      departmentId: departmentId,
      toUserId: toUserId
    }, query)
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: _precls.precls
  }, /*#__PURE__*/_react["default"].createElement(_header["default"], {
    onSearch: handleOnSearch,
    ref: headerRef,
    onFrontAddOKR: onFrontAddOKR,
    onChangeViewType: onChangeViewTypeHandler,
    viewType: viewType
  }), /*#__PURE__*/_react["default"].createElement(_loading["default"], {
    loading: loading
  }, okrs.length > 0 && viewType === _header.ViewType.Card && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_list["default"], {
    OkrListCmp: OkrListCmp,
    okrs: okrs,
    setOkrs: setOkrs,
    refreshList: function refreshList() {
      return setTimeout(getOkrs, 500);
    },
    replaceOkr: replaceOkr,
    isShowPrincple: isShowPrincple,
    isShowPeriod: isShowPeriod,
    isShowEasyCreate: relation !== '2' && relation !== '3',
    openCreateModal: openCreateModal
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(_precls.precls, "__pagination")
  }, /*#__PURE__*/_react["default"].createElement(_pagination["default"], {
    total: total,
    onChange: handlePageChange,
    pageSize: pageSize,
    current: pageNum,
    size: "sm"
  }))), okrs.length > 0 && viewType === _header.ViewType.Table && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_okrExcel["default"], {
    showCycle: query.cycleType === '-1',
    data: okrExcelData,
    onRefresh: onRefreshOkrs
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(_precls.precls, "__pagination")
  }, /*#__PURE__*/_react["default"].createElement(_pagination["default"], {
    total: total,
    onChange: handlePageChange,
    pageSize: pageSize,
    current: pageNum,
    size: "sm"
  }))), !loading && okrs.length === 0 && /*#__PURE__*/_react["default"].createElement(Empty, {
    openCreate: function openCreate() {
      return openCreateModal();
    },
    toUserId: toUserId || (0, _bsGlobal.getUserInfo)().Id,
    openCases: function openCases() {
      return setCasesVisible(true);
    },
    relation: relation,
    cycle: {
      annualNum: query.annualNum,
      cycleType: query.cycleType,
      yqmNum: query.yqmNum
    }
  })), /*#__PURE__*/_react["default"].createElement(_dialog["default"], {
    zIndex: 1200,
    noHeadLine: true,
    visible: casesVisible,
    onClose: onCasesCloseHandler,
    animation: "slide-fade-up",
    noFooter: true,
    noCloseIcon: true,
    destroyOnClose: true,
    style: {
      width: '100%',
      height: '100%'
    },
    maskClosable: true
  }, /*#__PURE__*/_react["default"].createElement(_okrcaseLibrary["default"], {
    onClose: function onClose() {
      return setCasesVisible(false);
    },
    onApplyTpl: handleCaseChoosed
  }))));
};

function ErrorBoundaryFun(props) {
  return /*#__PURE__*/_react["default"].createElement(_errorBoundary["default"], {
    errorLevel: _errorLevel["default"].P0
  }, /*#__PURE__*/_react["default"].createElement(NewOkrList, props));
}

var _default = ErrorBoundaryFun;
exports["default"] = _default;