import "choerodon-ui/pro/lib/data-set/style";
import _DataSet from "choerodon-ui/pro/lib/data-set";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { 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; }

import React, { createContext, useContext, useEffect, useMemo } from 'react';
import { inject } from 'mobx-react';
import { injectIntl } from 'react-intl';
import { withRouter } from 'react-router-dom';
import { isEmpty, includes, filter } from 'lodash';
import useStore from "./useStore";
import AppServiceDs from "./AppServiceDataSet";
import SelectAppDataSet from "./SelectAppDataSet";
import handleMapStore from "../main-view/store/handleMapStore";
var Store = /*#__PURE__*/createContext();
export function useCodeManagerStore() {
  return useContext(Store);
}
export var StoreProvider = withRouter(injectIntl(inject('AppState')(function (props) {
  var children = props.children,
      projectId = props.AppState.currentMenuType.id,
      _props$location = props.location,
      state = _props$location.state,
      search = _props$location.search;
  var searchParams = new URLSearchParams(search);
  var urlAppServiceId = searchParams.get('appServiceId');

  var checkHasApp = function checkHasApp(value, recentApp) {
    return recentApp.some(function (e) {
      return (e === null || e === void 0 ? void 0 : e.id) === value;
    });
  };

  function localSet(name, data) {
    if (typeof data !== 'string') {
      // eslint-disable-next-line no-param-reassign
      data = JSON.stringify(data);
    }

    localStorage.setItem(name, data);
  }

  var localGet = function localGet(name) {
    return localStorage.getItem(name) ? JSON.parse(localStorage.getItem(name)) : null;
  };

  var unshiftPop = function unshiftPop(value, recentApp, recentAppList) {
    // 有数据的话又再一次访问这个appservice则把他放到数组第一位
    var deIndex = recentApp.findIndex(function (e) {
      return (e === null || e === void 0 ? void 0 : e.id) === value[0].id;
    });

    if (deIndex > -1) {
      recentApp.splice(deIndex, 1); // 如果数据组存在该元素，则把该元素删除
    }

    recentApp.unshift(value[0]); // eslint-disable-next-line no-param-reassign

    recentAppList[projectId] = recentApp;
    localSet('recent-app', JSON.stringify(recentAppList));
  };

  var setLocalStorage = function setLocalStorage(value) {
    var recentAppList = localGet('recent-app');
    var temp = appServiceDs.toData().filter(function (e) {
      return (e === null || e === void 0 ? void 0 : e.id) === value;
    });
    var objTemp = {};

    if (isEmpty(temp)) {
      return;
    }

    if (recentAppList !== null && recentAppList[projectId]) {
      var recentApp = recentAppList[projectId];

      if (!checkHasApp(value, recentApp)) {
        // 先校验localstorage里面有没有这个数据
        !isEmpty(temp) && recentApp.unshift(temp[0]);

        if (recentApp.length > 5) {
          recentApp.splice(-1, 1);
        }

        recentAppList[projectId] = recentApp;
        localSet('recent-app', JSON.stringify(recentAppList));
      } else {
        unshiftPop(temp, recentApp, recentAppList);
      }
    } else if (recentAppList === null) {
      if (!isEmpty(temp)) {
        objTemp[projectId] = [temp[0]];
      }

      localSet('recent-app', JSON.stringify(objTemp));
    } else {
      if (!isEmpty(temp)) {
        recentAppList[projectId] = [temp[0]];
      }

      localSet('recent-app', JSON.stringify(recentAppList));
    }
  };

  var handleDataSetChange = function handleDataSetChange(_ref) {
    var dataSet = _ref.dataSet,
        record = _ref.record,
        value = _ref.value,
        oldValue = _ref.oldValue;
    if (!value) return;
    var option = {
      props: {
        children: record.get('name'),
        value: record.get('id')
      }
    };
    setLocalStorage(value);
    localSet('selectAppId', value);
    Object.keys(handleMapStore).forEach(function (key) {
      if (key.indexOf('Code') !== -1) {
        handleMapStore[key] && handleMapStore[key].select && handleMapStore[key].select(value, option);
      }
    });
  };

  var updateLocalAppService = function updateLocalAppService(appServiceList) {
    var recentAppList = localGet('recent-app');

    if (recentAppList && recentAppList[projectId]) {
      var recentApp = recentAppList[projectId] || [];
      var codeArr = [];
      recentApp.forEach(function (item) {
        if (item && item.id && item.code) {
          codeArr.push(item.code);
        }
      });
      var newData = filter(appServiceList, function (item) {
        return includes(codeArr, item.code);
      });

      if (newData && newData.length) {
        recentAppList[projectId] = newData.slice(0, 5);
        localSet('recent-app', JSON.stringify(recentAppList));
      }
    }
  };

  var appServiceDs = useMemo(function () {
    return new _DataSet(AppServiceDs({
      projectId: projectId
    }));
  }, []);
  var codeManagerStore = useStore();
  var selectAppDs = useMemo(function () {
    return new _DataSet(SelectAppDataSet({
      handleDataSetChange: handleDataSetChange,
      codeManagerStore: codeManagerStore
    }));
  }, []);
  var permissions = useMemo(function () {
    return ['choerodon.code.project.develop.code-management.ps.default'];
  }, []);
  useEffect(function () {
    codeManagerStore.checkHasApp(projectId);
  }, []);
  useEffect(function () {
    appServiceDs.transport.read = function () {
      return {
        url: "/devops/v1/projects/".concat(projectId, "/app_service/list_by_active"),
        method: 'get'
      };
    };

    appServiceDs.query().then(function (res) {
      if (state && state.appServiceId) {
        selectAppDs.current && selectAppDs.current.set('appServiceId', state.appServiceId);
        return;
      }

      if (res && res.length && res.length > 0) {
        updateLocalAppService(res);
        var recentAppList = localGet('recent-app');
        var newAppServiceId;

        if (urlAppServiceId) {
          codeManagerStore.handleEncrept(urlAppServiceId, function (encodeId) {
            selectAppDs.current.set('appServiceId', encodeId);
          });
          return;
        }

        if (recentAppList !== null && !isEmpty(recentAppList[projectId])) {
          var _recentAppList$projec;

          var cacheId = recentAppList[projectId].find(function (i) {
            return String(i.id) === String(localStorage.getItem('selectAppId'));
          });
          newAppServiceId = cacheId && localStorage.getItem('selectAppId') || ((_recentAppList$projec = recentAppList[projectId][0]) === null || _recentAppList$projec === void 0 ? void 0 : _recentAppList$projec.id);
        } else {
          var _res$;

          var _cacheId = res.find(function (i) {
            return String(i.id) === String(localStorage.getItem('selectAppId'));
          });

          newAppServiceId = _cacheId && localStorage.getItem('selectAppId') || ((_res$ = res[0]) === null || _res$ === void 0 ? void 0 : _res$.id);
        }

        selectAppDs.current.set('appServiceId', newAppServiceId);
      }
    });
  }, [projectId]);

  var value = _objectSpread(_objectSpread({}, props), {}, {
    prefixCls: 'c7ncd-code-manager',
    intlPrefix: 'c7ncd.code-manager',
    itemType: {
      CIPHER_ITEM: 'secrets',
      CUSTOM_ITEM: 'customResources'
    },
    codeManagerStore: codeManagerStore,
    permissions: permissions,
    appServiceDs: appServiceDs,
    selectAppDs: selectAppDs,
    projectId: projectId
  });

  return /*#__PURE__*/React.createElement(Store.Provider, {
    value: value
  }, children);
})));