import "choerodon-ui/pro/lib/form/style";
import _Form from "@hzero-front-ui/c7n-ui/lib/FormPro";
import "choerodon-ui/pro/lib/text-field/style";
import _TextField from "choerodon-ui/pro/lib/text-field";
import "choerodon-ui/pro/lib/icon/style";
import _Icon from "choerodon-ui/pro/lib/icon";
import "choerodon-ui/pro/lib/progress/style";
import _Progress from "@hzero-front-ui/c7n-ui/lib/ProgressPro";
import "choerodon-ui/pro/lib/select/style";
import _Select from "choerodon-ui/pro/lib/select";

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 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, { useState, useMemo, useEffect, useRef } from 'react';
import { observer } from 'mobx-react-lite';
import { map, some, debounce } from 'lodash';
import { axios, Choerodon } from '@choerodon/boot';
import { useExecuteContentStore } from "./stores";
import "./index.less";
var OptGroup = _Select.OptGroup,
    Option = _Select.Option;
export default observer(function () {
  var _useExecuteContentSto = useExecuteContentStore(),
      projectId = _useExecuteContentSto.AppState.currentMenuType.projectId,
      formatMessage = _useExecuteContentSto.intl.formatMessage,
      appServiceId = _useExecuteContentSto.appServiceId,
      selectDs = _useExecuteContentSto.selectDs,
      store = _useExecuteContentSto.store,
      modal = _useExecuteContentSto.modal,
      pipelineId = _useExecuteContentSto.pipelineId,
      prefixCls = _useExecuteContentSto.prefixCls,
      mainStore = _useExecuteContentSto.mainStore,
      refresh = _useExecuteContentSto.refresh,
      record = _useExecuteContentSto.record;

  var formRef = useRef();

  var _useState = useState(1),
      _useState2 = _slicedToArray(_useState, 2),
      branchPage = _useState2[0],
      setBranchPage = _useState2[1];

  var _useState3 = useState(1),
      _useState4 = _slicedToArray(_useState3, 2),
      tagPage = _useState4[0],
      setTagPage = _useState4[1];

  var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      moreTagLoading = _useState6[0],
      setMoreTagLoading = _useState6[1];

  var _useState7 = useState(false),
      _useState8 = _slicedToArray(_useState7, 2),
      moreBranchLoading = _useState8[0],
      setMoreBranchLoading = _useState8[1];

  var _useState9 = useState(''),
      _useState10 = _slicedToArray(_useState9, 2),
      searchValue = _useState10[0],
      setSearchValue = _useState10[1];

  var getBranchData = store.getBranchData,
      getTagData = store.getTagData,
      getHasMoreBranch = store.getHasMoreBranch,
      getHasMoreTag = store.getHasMoreTag;
  useEffect(function () {
    loadData('');
  }, []); // eslint-disable-next-line consistent-return

  modal.handleOk( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return selectDs.submit();

          case 3:
            _context.t0 = _context.sent;

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

            mainStore.setExpandedKeys([pipelineId]);
            mainStore.setSelectedMenu(record.toData());
            refresh();
            _context.next = 11;
            break;

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

          case 11:
            _context.next = 16;
            break;

          case 13:
            _context.prev = 13;
            _context.t1 = _context["catch"](0);
            throw new Error(_context.t1);

          case 16:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 13]]);
  })));

  function loadMore(_x, _x2) {
    return _loadMore.apply(this, arguments);
  }

  function _loadMore() {
    _loadMore = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(type, e) {
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              e.stopPropagation();

              if (!(type === 'branch')) {
                _context3.next = 9;
                break;
              }

              setMoreBranchLoading(true);
              _context3.next = 5;
              return store.loadBranchData({
                projectId: projectId,
                appServiceId: appServiceId,
                page: branchPage + 1,
                searchValue: searchValue
              });

            case 5:
              setMoreBranchLoading(false);
              setBranchPage(function (pre) {
                return pre + 1;
              });
              _context3.next = 14;
              break;

            case 9:
              setMoreTagLoading(true);
              _context3.next = 12;
              return store.loadTagData({
                projectId: projectId,
                appServiceId: appServiceId,
                page: tagPage + 1,
                searchValue: searchValue
              });

            case 12:
              setMoreTagLoading(false);
              setTagPage(function (pre) {
                return pre + 1;
              });

            case 14:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));
    return _loadMore.apply(this, arguments);
  }

  var loadData = useMemo(function () {
    return debounce( /*#__PURE__*/function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(text) {
        var selectCom, fields, _yield$axios$all, _yield$axios$all2, branchData, tagData, value;

        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                setBranchPage(1);
                setTagPage(1);

                if (formRef.current) {
                  fields = formRef.current.fields;

                  if (fields instanceof Array && fields.length) {
                    // eslint-disable-next-line prefer-destructuring
                    selectCom = fields[1];
                  }
                }

                if (selectCom && selectCom.options) {
                  selectCom.options.changeStatus('loading');
                }

                _context2.prev = 4;
                _context2.next = 7;
                return axios.all([store.loadBranchData({
                  projectId: projectId,
                  appServiceId: appServiceId,
                  page: 1,
                  searchValue: text
                }), store.loadTagData({
                  projectId: projectId,
                  appServiceId: appServiceId,
                  page: 1,
                  searchValue: text
                })]);

              case 7:
                _yield$axios$all = _context2.sent;
                _yield$axios$all2 = _slicedToArray(_yield$axios$all, 2);
                branchData = _yield$axios$all2[0];
                tagData = _yield$axios$all2[1];
                value = selectDs.current.get('branch');

                if (!(!branchData && !tagData)) {
                  _context2.next = 15;
                  break;
                }

                if (selectCom && selectCom.options) {
                  selectCom.options.changeStatus('ready');
                }

                return _context2.abrupt("return");

              case 15:
                if (!text && value && !(some(branchData.list, function (item) {
                  return item.branchName === value.slice(0, -7);
                }) || some(tagData.list, function (item) {
                  return item.release.tagName === value.slice(0, -7);
                }))) {
                  if (value.slice(-7) === '_type_b') {
                    store.setBranchData([].concat(_toConsumableArray(store.getBranchData), [{
                      branchName: value.slice(0, -7)
                    }]));
                  } else {
                    store.setTagData([].concat(_toConsumableArray(store.getTagData), [{
                      release: {
                        tagName: value.slice(0, -7)
                      }
                    }]));
                  }
                }

                if (selectCom && selectCom.options) {
                  selectCom.options.changeStatus('ready');
                }

                _context2.next = 23;
                break;

              case 19:
                _context2.prev = 19;
                _context2.t0 = _context2["catch"](4);

                if (selectCom && selectCom.options) {
                  selectCom.options.changeStatus('ready');
                }

                Choerodon.handleResponseError(_context2.t0);

              case 23:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, null, [[4, 19]]);
      }));

      return function (_x3) {
        return _ref2.apply(this, arguments);
      };
    }(), 700);
  }, [projectId, appServiceId, formRef]);

  function renderBranchOptionOrigin(args) {
    // eslint-disable-next-line no-shadow
    var record = args.record,
        text = args.text; // meaning是默认的textfiled 此处用于判断 是否是加载更多的按钮

    if (!record.get('meaning')) {
      // 根据value来判断是哪一个加载更多的按钮
      var progress = null;

      if (record.get('value') === 'tag') {
        progress = moreTagLoading ? /*#__PURE__*/React.createElement(_Progress, {
          type: "loading",
          size: "small"
        }) : null;
      } else {
        progress = moreBranchLoading ? /*#__PURE__*/React.createElement(_Progress, {
          type: "loading",
          size: "small"
        }) : null;
      }

      return /*#__PURE__*/React.createElement("div", {
        role: "none",
        onClick: loadMore.bind(this, record.get('value')),
        className: "".concat(prefixCls, "-popover")
      }, progress, /*#__PURE__*/React.createElement("span", {
        className: "".concat(prefixCls, "-popover-option-more")
      }, formatMessage({
        id: 'loadMore'
      })));
    }

    return renderOption(record.get('value'));
  } // 用于渲染分支来源


  var renderBranchOrigin = function renderBranchOrigin(args) {
    var text = args.text,
        value = args.value;
    return renderOption(value);
  };

  function renderOption(text) {
    if (!text) return null;
    return /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement(_Icon, {
      type: text.slice(-7) === '_type_t' ? 'local_offer' : 'branch',
      className: "".concat(prefixCls, "-popover-option-icon")
    }), text && text.slice(0, -7));
  }

  function searchMatcher() {
    return true;
  }

  function handleInput(_ref3) {
    var value = _ref3.target.value;
    setSearchValue(value);
    loadData(value);
  }

  function handleBlur(e) {
    if (getBranchData.length === 0 && getTagData.length === 0) {
      selectDs.current.set('branch', null);
    }

    setSearchValue('');
    loadData('');
  }

  return /*#__PURE__*/React.createElement(_Form, {
    dataSet: selectDs // style={{ width: 340 }}
    ,
    ref: formRef,
    columns: 3
  }, /*#__PURE__*/React.createElement(_TextField, {
    name: "appServiceName",
    disabled: true
  }), /*#__PURE__*/React.createElement(_Select, {
    name: "branch",
    searchable: true,
    searchMatcher: searchMatcher,
    onInput: handleInput,
    onBlur: handleBlur,
    clearButton: false,
    optionRenderer: renderBranchOptionOrigin,
    renderer: renderBranchOrigin,
    colSpan: 2
  }, /*#__PURE__*/React.createElement(OptGroup, {
    label: formatMessage({
      id: 'branch'
    }),
    key: "proGroup"
  }, map(getBranchData, function (_ref4) {
    var branchName = _ref4.branchName;
    return /*#__PURE__*/React.createElement(Option, {
      value: "".concat(branchName, "_type_b"),
      key: branchName,
      title: branchName
    }, branchName);
  }), getHasMoreBranch ? /*#__PURE__*/React.createElement(Option, {
    value: "branch"
  }) : null), /*#__PURE__*/React.createElement(OptGroup, {
    label: formatMessage({
      id: 'tag'
    }),
    key: "more"
  }, map(getTagData, function (_ref5) {
    var release = _ref5.release;
    return release ? /*#__PURE__*/React.createElement(Option, {
      value: "".concat(release.tagName, "_type_t"),
      key: release.tagName
    }, release.tagName) : null;
  }), getHasMoreTag ? /*#__PURE__*/React.createElement(Option, {
    value: "tag"
  }) : null)));
});