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/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 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, useEffect, useMemo, useCallback } from 'react';
import { withRouter } from 'react-router-dom';
import { observer } from 'mobx-react-lite';
import { Content, axios } from '@choerodon/boot';
import { injectIntl } from 'react-intl';
import _ from 'lodash';
import debounce from 'lodash/debounce';
import get from 'lodash/get';
import some from 'lodash/some';
import MouserOverWrapper from "../../../../../components/MouseOverWrapper";
import { useFormStore } from "./stores";
import { handlePromptError } from "../../../../../utils";
import IssueType from "../../../components/issue-type";
import "../../../../main.less";
import "./index.less";
import "../index.less";
var Option = _Select.Option,
    OptGroup = _Select.OptGroup;

function BranchCreate(props) {
  var _this = this;

  var _useFormStore = useFormStore(),
      modal = _useFormStore.modal,
      handleRefresh = _useFormStore.handleRefresh,
      contentStore = _useFormStore.contentStore,
      formDs = _useFormStore.formDs,
      projectId = _useFormStore.projectId,
      appServiceId = _useFormStore.appServiceId,
      formatMessage = _useFormStore.intl.formatMessage,
      projectOptionsDs = _useFormStore.projectOptionsDs,
      categories = _useFormStore.AppState.currentMenuType.categories;

  var _useState = useState(3),
      _useState2 = _slicedToArray(_useState, 2),
      branchPageSize = _useState2[0],
      setBranchPageSize = _useState2[1];

  var _useState3 = useState(3),
      _useState4 = _slicedToArray(_useState3, 2),
      tagPageSize = _useState4[0],
      setTagPageSize = _useState4[1];

  var _useState5 = useState(''),
      _useState6 = _slicedToArray(_useState5, 2),
      prefixData = _useState6[0],
      setPrefixeData = _useState6[1];

  var _useState7 = useState([]),
      _useState8 = _slicedToArray(_useState7, 2),
      branchOringData = _useState8[0],
      setBranchOringData = _useState8[1];

  var _useState9 = useState([]),
      _useState10 = _slicedToArray(_useState9, 2),
      branchTagData = _useState10[0],
      setBranchTagData = _useState10[1];

  var _useState11 = useState(false),
      _useState12 = _slicedToArray(_useState11, 2),
      loadMoreBranch = _useState12[0],
      setLoadMoreBranch = _useState12[1];

  var _useState13 = useState(false),
      _useState14 = _slicedToArray(_useState13, 2),
      loadMoreTag = _useState14[0],
      setLoadMoreTag = _useState14[1];

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

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

  var _useState19 = useState(null),
      _useState20 = _slicedToArray(_useState19, 2),
      selectCom = _useState20[0],
      setSelectCom = _useState20[1];

  var _useState21 = useState(false),
      _useState22 = _slicedToArray(_useState21, 2),
      isCallHandleInput = _useState22[0],
      setIsCallHandleInput = _useState22[1];

  var _useState23 = useState(false),
      _useState24 = _slicedToArray(_useState23, 2),
      isOPERATIONS = _useState24[0],
      setIsOPERATIONS = _useState24[1];

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

  useEffect(function () {
    setIsOPERATIONS(!some(categories || [], ['code', 'N_AGILE']));
  }, [categories]);
  useEffect(function () {
    loadBranchData(branchPageSize);
    loadTagData(tagPageSize);
  }, [appServiceId]);
  var searchData = useMemo(function () {
    return _.debounce(function (text) {
      if (selectCom && selectCom.options) {
        selectCom.options.changeStatus('loading');
      }

      axios.all([contentStore.loadBranchData(projectId, appServiceId, branchPageSize, text), contentStore.loadTagData(projectId, appServiceId, tagPageSize, text)]).then(axios.spread(function (branchs, tags) {
        if (selectCom && selectCom.options) {
          selectCom.options.changeStatus('ready');
        }

        if (handlePromptError(branchs) || handlePromptError(tags)) {
          setLoadMoreBranch(judgeShowMore(branchs));
          setLoadMoreTag(judgeShowMore(tags));
          var value = formDs.current.get('branchOrigin');

          if (!text && value && !(_.findIndex(branchs.list, function (item) {
            return item.branchName === value.slice(0, -7);
          }) !== -1 // eslint-disable-next-line max-len
          || _.findIndex(tags.list, function (item) {
            return item.release.tagName === value.slice(0, -7);
          }) !== -1)) {
            if (value.slice(-7) === '_type_b') {
              branchs.list.push({
                branchName: value.slice(0, -7)
              });
            } else {
              tags.list.push({
                release: {
                  tagName: value.slice(0, -7)
                }
              });
            }
          }

          setBranchOringData(branchs.list || []);
          setBranchTagData(tags.list || []);
        }
      }));
    }, 700);
  }, [selectCom, projectId, appServiceId, branchPageSize, tagPageSize]);
  /**
   * 加载分支数据
   * @param BranchPageSize
   */

  function loadBranchData(_x) {
    return _loadBranchData.apply(this, arguments);
  }
  /**
   * 加载标记数据
   * @param TagPageSize
   */


  function _loadBranchData() {
    _loadBranchData = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(BranchPageSize) {
      var data;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              setMoreBranchLoading(true);
              _context.next = 3;
              return contentStore.loadBranchData(projectId, appServiceId, BranchPageSize);

            case 3:
              data = _context.sent;
              setMoreBranchLoading(false);

              if (handlePromptError(data)) {
                setBranchOringData(data.list);
                setLoadMoreBranch(judgeShowMore(data));
              }

            case 6:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));
    return _loadBranchData.apply(this, arguments);
  }

  function loadTagData(_x2) {
    return _loadTagData.apply(this, arguments);
  }
  /**
   * 创建
   */


  function _loadTagData() {
    _loadTagData = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(TagPageSize) {
      var data;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              setMoreTagLoading(true);
              _context2.next = 3;
              return contentStore.loadTagData(projectId, appServiceId, TagPageSize);

            case 3:
              data = _context2.sent;
              setMoreTagLoading(false);

              if (handlePromptError(data)) {
                setBranchTagData(data.list);
                setLoadMoreTag(judgeShowMore(data));
              }

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

  function handleOk() {
    return _handleOk.apply(this, arguments);
  }

  function _handleOk() {
    _handleOk = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _context3.prev = 0;
              _context3.next = 3;
              return formDs.submit();

            case 3:
              _context3.t0 = _context3.sent;

              if (!(_context3.t0 !== false)) {
                _context3.next = 7;
                break;
              }

              handleRefresh();
              return _context3.abrupt("return", true);

            case 7:
              return _context3.abrupt("return", false);

            case 10:
              _context3.prev = 10;
              _context3.t1 = _context3["catch"](0);
              return _context3.abrupt("return", false);

            case 13:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, null, [[0, 10]]);
    }));
    return _handleOk.apply(this, arguments);
  }

  modal.handleOk(handleOk);
  /**
   * 切换issue
   * @param value
   */

  var changeIssue = function changeIssue(value) {
    var type;

    var _ref = value || {},
        typeCode = _ref.typeCode,
        issueNum = _ref.issueNum;

    formDs.current.set('branchName', issueNum);

    switch (typeCode) {
      case 'story':
        type = 'feature';
        break;

      case 'bug':
        type = 'bugfix';
        break;

      case 'issue_epic':
        type = 'custom';
        break;

      case 'sub_task':
        type = 'feature';
        break;

      case 'task':
        type = 'feature';
        break;

      default:
        type = 'custom';
    }

    formDs.current.set('branchType', type);
  };
  /**
   * 获取列表的icon
   * @param type 分支类型
   * @returns {*}
   */


  var getIcon = function getIcon(type) {
    var icon;

    switch (type) {
      case 'feature':
        icon = /*#__PURE__*/React.createElement("span", {
          className: "c7n-branch-icon icon-feature"
        }, "F");
        break;

      case 'bugfix':
        icon = /*#__PURE__*/React.createElement("span", {
          className: "c7n-branch-icon icon-develop"
        }, "B");
        break;

      case 'hotfix':
        icon = /*#__PURE__*/React.createElement("span", {
          className: "c7n-branch-icon icon-hotfix"
        }, "H");
        break;

      case 'master':
        icon = /*#__PURE__*/React.createElement("span", {
          className: "c7n-branch-icon icon-master"
        }, "M");
        break;

      case 'release':
        icon = /*#__PURE__*/React.createElement("span", {
          className: "c7n-branch-icon icon-release"
        }, "R");
        break;

      default:
        icon = /*#__PURE__*/React.createElement("span", {
          className: "c7n-branch-icon icon-custom"
        }, "C");
    }

    return icon;
  }; // 用于分支类型的渲染函数


  var renderBranchType = function renderBranchType(_ref2) {
    var text = _ref2.text;

    if (text !== 'custom') {
      setPrefixeData(text ? "".concat(text, "-") : '');
      contentStore.setBranchPrefix(text ? "".concat(text, "-") : '');
    } else {
      contentStore.setBranchPrefix(null);
      setPrefixeData(null);
    }

    return text ? /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", {
      style: {
        width: '100%'
      }
    }, getIcon(text), /*#__PURE__*/React.createElement("span", {
      className: "c7n-branch-text"
    }, text))) : null;
  }; // 用于分支类型的渲染函数


  var renderOptionsBranchType = function renderOptionsBranchType(_ref3) {
    var text = _ref3.text;
    return /*#__PURE__*/React.createElement("div", {
      style: {
        width: '100%'
      }
    }, getIcon(text), /*#__PURE__*/React.createElement("span", {
      className: "c7n-branch-text"
    }, text));
  }; // 用于问题名称的渲染函数


  var renderIssueName = function renderIssueName(_ref4) {
    var typeCode = _ref4.typeCode,
        issueNum = _ref4.issueNum,
        summary = _ref4.summary,
        issueTypeVO = _ref4.issueTypeVO;
    var mes = '';
    var icon = '';
    var color = '';

    switch (typeCode) {
      case 'story':
        mes = formatMessage({
          id: 'branch.issue.story'
        });
        icon = 'agile_story';
        color = '#00bfa5';
        break;

      case 'bug':
        mes = formatMessage({
          id: 'branch.issue.bug'
        });
        icon = 'agile_fault';
        color = '#f44336';
        break;

      case 'issue_epic':
        mes = formatMessage({
          id: 'branch.issue.epic'
        });
        icon = 'agile_epic';
        color = '#743be7';
        break;

      case 'sub_task':
        mes = formatMessage({
          id: 'branch.issue.subtask'
        });
        icon = 'agile_subtask';
        color = '#4d90fe';
        break;

      default:
        mes = formatMessage({
          id: 'branch.issue.task'
        });
        icon = 'agile_task';
        color = '#4d90fe';
    }

    return /*#__PURE__*/React.createElement(React.Fragment, null, issueTypeVO ? /*#__PURE__*/React.createElement(IssueType, {
      data: issueTypeVO
    }) : /*#__PURE__*/React.createElement("div", {
      style: {
        color: color
      },
      className: "branch-issue"
    }, /*#__PURE__*/React.createElement("i", {
      className: "icon icon-".concat(icon)
    })), /*#__PURE__*/React.createElement("span", {
      className: "branch-issue-content"
    }, /*#__PURE__*/React.createElement("span", {
      style: {
        color: 'rgb(0,0,0,0.65)'
      }
    }, issueNum), /*#__PURE__*/React.createElement(MouserOverWrapper, {
      style: {
        display: 'inline-block',
        verticalAlign: 'sub'
      },
      width: "350px",
      text: summary
    }, summary)));
  };

  var issueNameRender = function issueNameRender(_ref5) {
    var text = _ref5.text,
        value = _ref5.value;

    var _ref6 = value || {},
        typeCode = _ref6.typeCode,
        issueNum = _ref6.issueNum,
        summary = _ref6.summary,
        issueTypeVO = _ref6.issueTypeVO;

    return typeCode || issueTypeVO ? /*#__PURE__*/React.createElement("span", null, renderIssueName({
      typeCode: typeCode,
      issueNum: issueNum,
      summary: summary,
      issueTypeVO: issueTypeVO
    })) : null;
  };

  var issueNameOptionRender = function issueNameOptionRender(_ref7) {
    var record = _ref7.record;
    var typeCode = record.get('typeCode');
    var issueNum = record.get('issueNum');
    var summary = record.get('summary');
    var issueTypeVO = record.get('issueTypeVO');
    return /*#__PURE__*/React.createElement("span", null, renderIssueName({
      typeCode: typeCode,
      issueNum: issueNum,
      summary: summary,
      issueTypeVO: issueTypeVO
    }));
  };

  var loadMore = function loadMore(type, e) {
    e.stopPropagation();

    if (type === 'branch') {
      var pageSize = branchPageSize + 10;
      setBranchPageSize(pageSize);
      loadBranchData(pageSize);
    } else {
      var _pageSize = tagPageSize + 10;

      setTagPageSize(_pageSize);
      loadTagData(_pageSize);
    }
  };

  var rednerBranchOptionOrigin = function rednerBranchOptionOrigin(args) {
    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", {
        onClick: loadMore.bind(_this, record.get('value')),
        className: "c7n-option-popover",
        role: "none"
      }, progress, /*#__PURE__*/React.createElement("span", {
        className: "c7n-option-span"
      }, formatMessage({
        id: 'loadMore'
      })));
    }

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


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

    if (text || value) {
      return null;
    }

    return renderOption(value);
  };

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

  function searchMatcher() {
    return true;
  }

  function handleInput(_ref8) {
    var value = _ref8.target.value;
    if (!isCallHandleInput) setIsCallHandleInput(true);
    searchData(value);
  }

  function changeRef(obj) {
    if (obj) {
      var fields = obj.fields;

      if (fields instanceof Array && fields.length > 0) {
        var select = fields[1];

        if (select && !selectCom) {
          setSelectCom(select);
        }
      }
    }
  }

  function handleBlur(e) {
    if (branchOringData.length === 0 && branchTagData.length === 0) {
      formDs.current.set('branchOrigin', null);
    }

    searchData('');
  }

  var loadProjectData = useCallback(function () {
    projectOptionsDs.query();
  }, []);
  var handleProjectSearch = useCallback(function (e) {
    e.persist();
    searchProjectData(e.target.value);
  }, []);
  var searchProjectData = useMemo(function () {
    return debounce(function (value) {
      projectOptionsDs.setQueryParameter('params', value);
      setSearchValue(value);
      loadProjectData();
    }, 500);
  }, []);
  var handleProjectBlur = useCallback(function () {
    if (searchValue) {
      searchProjectData('');
    }
  }, [searchValue]);
  var renderProjectOption = useCallback(function (_ref9) {
    var text = _ref9.text,
        value = _ref9.value;

    if (String(value) === String(projectId)) {
      return "".concat(text, "\uFF08\u672C\u9879\u76EE\uFF09");
    }

    return text;
  }, []);
  var renderProject = useCallback(function (_ref10) {
    var value = _ref10.value;
    var currentValue = get(value, 'id');
    var text = get(value, 'name');
    return renderProjectOption({
      text: text,
      value: currentValue
    });
  }, []);
  return /*#__PURE__*/React.createElement("div", {
    className: "sidebar-content c7n-createBranch"
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      width: '75%'
    }
  }, /*#__PURE__*/React.createElement(_Form, {
    dataSet: formDs,
    columns: 5,
    ref: changeRef
  }, !isOPERATIONS && [/*#__PURE__*/React.createElement(_Select, {
    name: "project",
    colSpan: 5,
    searchable: true,
    searchMatcher: function searchMatcher() {
      return true;
    },
    onInput: handleProjectSearch,
    optionRenderer: renderProjectOption,
    renderer: renderProject,
    onBlur: handleProjectBlur,
    clearButton: false,
    pagingOptionContent: /*#__PURE__*/React.createElement("span", {
      className: "c7ncd-select-load-more-text"
    }, "\u52A0\u8F7D\u66F4\u591A")
  }), /*#__PURE__*/React.createElement(_Select, {
    name: "issue",
    colSpan: 5,
    onChange: changeIssue,
    optionRenderer: issueNameOptionRender,
    renderer: issueNameRender,
    searchable: true,
    searchMatcher: "content"
  })], /*#__PURE__*/React.createElement(_Select, {
    colSpan: 5,
    name: "branchOrigin",
    searchMatcher: searchMatcher,
    onInput: handleInput,
    onBlur: handleBlur,
    searchable: true,
    optionRenderer: rednerBranchOptionOrigin,
    renderer: renderBranchOrigin
  }, /*#__PURE__*/React.createElement(OptGroup, {
    label: formatMessage({
      id: 'branch.branch'
    }),
    key: "proGroup"
  }, branchOringData.map(function (s) {
    return /*#__PURE__*/React.createElement(Option, {
      value: "".concat(s.branchName, "_type_b"),
      key: s.branchName,
      title: s.branchName
    }, s.branchName);
  }), loadMoreBranch ? /*#__PURE__*/React.createElement(Option, {
    value: "branch"
  }) : null), /*#__PURE__*/React.createElement(OptGroup, {
    label: formatMessage({
      id: 'branch.tag'
    }),
    key: "more"
  }, branchTagData.map(function (s) {
    return s.release ? /*#__PURE__*/React.createElement(Option, {
      value: "".concat(s.release.tagName, "_type_t"),
      key: s.release.tagName
    }, s.release.tagName) : null;
  }), loadMoreTag ? /*#__PURE__*/React.createElement(Option, {
    value: "tag"
  }) : null)), /*#__PURE__*/React.createElement(_Select, {
    colSpan: 2,
    name: "branchType",
    renderer: renderBranchType,
    optionRenderer: renderOptionsBranchType
  }, ['feature', 'bugfix', 'release', 'hotfix', 'custom'].map(function (s) {
    return /*#__PURE__*/React.createElement(Option, {
      value: s,
      key: s,
      title: s
    }, s);
  })), /*#__PURE__*/React.createElement(_TextField, {
    colSpan: 3,
    name: "branchName",
    renderer: function renderer(_ref11) {
      var value = _ref11.value;
      return value ? "".concat(prefixData || '').concat(value) : value;
    }
  }))));
}

export default withRouter(injectIntl(observer(BranchCreate)));

function judgeShowMore(data) {
  return data.total > data.size && data.size > 0;
}