import "choerodon-ui/pro/lib/text-field/style";
import _TextField from "choerodon-ui/pro/lib/text-field";
import "choerodon-ui/pro/lib/form/style";
import _Form from "@hzero-front-ui/c7n-ui/lib/FormPro";
import "choerodon-ui/pro/lib/select-box/style";
import _SelectBox from "choerodon-ui/pro/lib/select-box";
import "choerodon-ui/pro/lib/tooltip/style";
import _Tooltip from "choerodon-ui/pro/lib/tooltip";
import "choerodon-ui/pro/lib/select/style";
import _Select from "choerodon-ui/pro/lib/select";

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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

import React, { Fragment, useState, useEffect, useMemo } from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
import { observer } from 'mobx-react-lite';
import { Choerodon } from '@choerodon/boot';
import keys from 'lodash/keys';
import countBy from 'lodash/countBy';
import pickBy from 'lodash/pickBy';
import isEmpty from 'lodash/isEmpty';
import map from 'lodash/map';
import PlatForm from "./Platform";
import Tips from "../../../../../components/new-tips";
import { useImportAppServiceStore } from "./stores";
import "./index.less";
var Option = _Select.Option;
var ImportForm = injectIntl(observer(function (props) {
  var _useImportAppServiceS = useImportAppServiceStore(),
      projectId = _useImportAppServiceS.AppState.currentMenuType.projectId,
      formatMessage = _useImportAppServiceS.intl.formatMessage,
      intlPrefix = _useImportAppServiceS.intlPrefix,
      prefixCls = _useImportAppServiceS.prefixCls,
      IMPORT_METHOD = _useImportAppServiceS.IMPORT_METHOD,
      refresh = _useImportAppServiceS.refresh,
      modal = _useImportAppServiceS.modal,
      importDs = _useImportAppServiceS.importDs,
      selectedDs = _useImportAppServiceS.selectedDs,
      marketSelectedDs = _useImportAppServiceS.marketSelectedDs,
      importStore = _useImportAppServiceS.importStore,
      hasMarket = _useImportAppServiceS.hasMarket;

  var record = useMemo(function () {
    return importDs.current || importDs.records[0];
  }, [importDs.current]);

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      hasFailed = _useState2[0],
      setHasFailed = _useState2[1];

  useEffect(function () {
    setHasFailed(false);
  }, [record.get('platformType')]);
  modal.handleOk( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
    var ds, result;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (!(record.get('platformType') === 'share' || record.get('platformType') === 'market')) {
              _context.next = 14;
              break;
            }

            ds = record.get('platformType') === 'market' ? marketSelectedDs : selectedDs;

            if (ds.length) {
              _context.next = 4;
              break;
            }

            return _context.abrupt("return", true);

          case 4:
            _context.next = 6;
            return validateDs();

          case 6:
            _context.t0 = _context.sent;

            if (!(_context.t0 === false)) {
              _context.next = 9;
              break;
            }

            return _context.abrupt("return", false);

          case 9:
            _context.next = 11;
            return checkData();

          case 11:
            result = _context.sent;

            if (result) {
              _context.next = 14;
              break;
            }

            return _context.abrupt("return", false);

          case 14:
            _context.prev = 14;
            _context.next = 17;
            return importDs.submit();

          case 17:
            _context.t1 = _context.sent;

            if (!(_context.t1 !== false)) {
              _context.next = 21;
              break;
            }

            refresh();
            return _context.abrupt("return", true);

          case 21:
            return _context.abrupt("return", false);

          case 24:
            _context.prev = 24;
            _context.t2 = _context["catch"](14);
            Choerodon.handleResponseError(_context.t2);
            return _context.abrupt("return", false);

          case 28:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[14, 24]]);
  })));

  function validateDs() {
    return _validateDs.apply(this, arguments);
  }

  function _validateDs() {
    _validateDs = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var validateResult, results;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              validateResult = false; // 因为市场服务应用通过ds.loadData方法添加，调用ds.validate不会触发每条record的校验

              if (!(record.get('platformType') === 'market')) {
                _context2.next = 8;
                break;
              }

              _context2.next = 4;
              return Promise.all(marketSelectedDs.map(function (eachRecord) {
                return eachRecord.validate(true);
              }));

            case 4:
              results = _context2.sent;
              validateResult = results.every(function (result) {
                return result;
              });
              _context2.next = 12;
              break;

            case 8:
              _context2.next = 10;
              return selectedDs.validate();

            case 10:
              validateResult = _context2.sent;
              importStore.setSkipCheck(false);

            case 12:
              return _context2.abrupt("return", validateResult);

            case 13:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));
    return _validateDs.apply(this, arguments);
  }

  function checkData() {
    return _checkData.apply(this, arguments);
  }

  function _checkData() {
    _checkData = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var ds, lists, _getRepeatData, listCode, listName, repeatName, repeatCode, res;

      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              ds = record.get('platformType') === 'market' ? marketSelectedDs : selectedDs;
              lists = ds.toData();
              _getRepeatData = getRepeatData(lists), listCode = _getRepeatData.listCode, listName = _getRepeatData.listName, repeatName = _getRepeatData.repeatName, repeatCode = _getRepeatData.repeatCode;
              _context3.prev = 3;
              importStore.setSkipCheck(true);
              _context3.next = 7;
              return importStore.batchCheck(projectId, listCode, listName);

            case 7:
              res = _context3.sent;
              validateDs();

              if (!(res && isEmpty(repeatName) && isEmpty(repeatCode) && isEmpty(res.listCode) && isEmpty(res.listName))) {
                _context3.next = 12;
                break;
              }

              setHasFailed(false);
              return _context3.abrupt("return", true);

            case 12:
              setHasFailed(true);
              return _context3.abrupt("return", false);

            case 16:
              _context3.prev = 16;
              _context3.t0 = _context3["catch"](3);
              Choerodon.handleResponseError(_context3.t0);
              return _context3.abrupt("return", false);

            case 20:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, null, [[3, 16]]);
    }));
    return _checkData.apply(this, arguments);
  }

  function getRepeatData(lists) {
    var nameData = countBy(lists, 'name');
    var codeData = countBy(lists, 'code');
    var listName = keys(nameData);
    var listCode = keys(codeData);
    var repeatName = keys(pickBy(nameData, function (value, key) {
      return key && value > 1;
    }) || {});
    var repeatCode = keys(pickBy(codeData, function (value, key) {
      return key && value > 1;
    }) || {});
    return {
      listCode: listCode,
      listName: listName,
      repeatName: repeatName,
      repeatCode: repeatCode
    };
  }

  function handleOptionProps(_ref2) {
    var optionRecord = _ref2.record;
    return {
      disabled: optionRecord.get('value') === 'market' && !hasMarket
    };
  }

  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-import-wrap")
  }, /*#__PURE__*/React.createElement(_Form, {
    record: record
  }, /*#__PURE__*/React.createElement(_SelectBox, {
    className: "".concat(prefixCls, "-import-wrap-select"),
    name: "platformType",
    onOption: handleOptionProps
  }, map(IMPORT_METHOD, function (item) {
    return /*#__PURE__*/React.createElement(Option, {
      value: item,
      key: item
    }, /*#__PURE__*/React.createElement(_Tooltip, {
      title: hasMarket || item !== 'market' ? '' : '未安装【应用市场】插件，无法使用此功能'
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-import-wrap-radio")
    }, /*#__PURE__*/React.createElement(Tips, {
      helpText: formatMessage({
        id: "".concat(intlPrefix, ".").concat(item, ".tips")
      }),
      title: formatMessage({
        id: "".concat(intlPrefix, ".import.type.").concat(item)
      })
    }))));
  }))), record.get('platformType') === 'share' || record.get('platformType') === 'market' ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(PlatForm, {
    checkData: checkData
  }), hasFailed && /*#__PURE__*/React.createElement("span", {
    className: "".concat(prefixCls, "-import-wrap-failed")
  }, formatMessage({
    id: "".concat(intlPrefix, ".platform.failed")
  }))) : /*#__PURE__*/React.createElement(_Form, {
    record: record,
    style: {
      width: '3.6rem'
    }
  }, record.get('platformType') === 'github' && /*#__PURE__*/React.createElement(_SelectBox, {
    name: "isTemplate"
  }, /*#__PURE__*/React.createElement(Option, {
    value: true
  }, formatMessage({
    id: "".concat(intlPrefix, ".github.system")
  })), /*#__PURE__*/React.createElement(Option, {
    value: false
  }, formatMessage({
    id: "".concat(intlPrefix, ".github.custom")
  }))), record.get('platformType') === 'github' && record.get('isTemplate') && /*#__PURE__*/React.createElement(_Select, {
    name: "githubTemplate",
    searchable: true
  }), /*#__PURE__*/React.createElement(_TextField, {
    name: "repositoryUrl",
    disabled: record.get('platformType') === 'github' && record.get('isTemplate'),
    addonAfter: record.get('platformType') === 'github' && record.get('isTemplate') ? null : /*#__PURE__*/React.createElement(Tips, {
      helpText: formatMessage({
        id: "".concat(intlPrefix, ".address.").concat(record.get('platformType'), ".tips")
      })
    })
  }), record.get('platformType') === 'gitlab' && /*#__PURE__*/React.createElement(_TextField, {
    name: "accessToken"
  }), /*#__PURE__*/React.createElement(_Select, {
    name: "type",
    clearButton: false
  }), /*#__PURE__*/React.createElement(_TextField, {
    name: "name"
  }), /*#__PURE__*/React.createElement(_TextField, {
    name: "code"
  })));
}));
export default ImportForm;