import "choerodon-ui/pro/lib/form/style";
import _Form from "@hzero-front-ui/c7n-ui/lib/FormPro";
import "choerodon-ui/pro/lib/button/style";
import _Button from "choerodon-ui/pro/lib/button";
import "choerodon-ui/pro/lib/select/style";
import _Select from "choerodon-ui/pro/lib/select";
import "choerodon-ui/pro/lib/tooltip/style";
import _Tooltip from "choerodon-ui/pro/lib/tooltip";

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, { useCallback, useMemo, useState } from 'react';
import { injectIntl } from 'react-intl';
import { observer } from 'mobx-react-lite';
import debounce from 'lodash/debounce';
import get from 'lodash/get';
import MouserOverWrapper from "../../../../../components/MouseOverWrapper";
import IssueType from "../../../components/issue-type";
import { useSelectStore } from "./stores";

function BranchEdit() {
  var _useSelectStore = useSelectStore(),
      formatMessage = _useSelectStore.formatMessage,
      modal = _useSelectStore.modal,
      handleRefresh = _useSelectStore.handleRefresh,
      selectDs = _useSelectStore.selectDs,
      projectOptionsDs = _useSelectStore.projectOptionsDs,
      projectId = _useSelectStore.AppState.currentMenuType.projectId;

  var _useState = useState(''),
      _useState2 = _slicedToArray(_useState, 2),
      searchValue = _useState2[0],
      setSearchValue = _useState2[1];
  /**
   * 创建
   */


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

  function _handleOk() {
    _handleOk = _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 = 7;
                break;
              }

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

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

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

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

  modal.handleOk(function () {
    return handleOk();
  });
  var loadData = useCallback(function () {
    projectOptionsDs.query();
  }, []);
  var handleSearch = useCallback(function (e) {
    e.persist();
    searchData(e.target.value);
  }, []);
  var searchData = useMemo(function () {
    return debounce(function (value) {
      projectOptionsDs.setQueryParameter('params', value);
      setSearchValue(value);
      loadData();
    }, 500);
  }, []);
  var handleBlur = useCallback(function () {
    if (searchValue) {
      searchData('');
    }
  }, [searchValue]);
  var renderProjectOption = useCallback(function (_ref) {
    var text = _ref.text,
        value = _ref.value;

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

    return text;
  }, []);
  var renderProject = useCallback(function (_ref2) {
    var value = _ref2.value;
    var currentValue = get(value, 'id');
    var text = get(value, 'name');
    return renderProjectOption({
      text: text,
      value: currentValue
    });
  }, []); // 用于问题名称的渲染函数

  var renderIssueName = function renderIssueName(_ref3) {
    var typeCode = _ref3.typeCode,
        issueNum = _ref3.issueNum,
        summary = _ref3.summary,
        issueTypeVO = _ref3.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(_Tooltip, {
      title: summary
    }, summary)));
  };

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

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

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

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

  var handleDeleteRecord = useCallback(function (record) {
    selectDs.remove(record);
  }, [selectDs]);
  var handleAddRecord = useCallback(function () {
    selectDs.create();
  }, [selectDs]);
  var handleIssueFilter = useCallback(function (record) {
    var issueId = record.get('issueId');
    var selectedIssueIds = selectDs.map(function (selectedRecord) {
      var _selectedRecord$get;

      return (_selectedRecord$get = selectedRecord.get('issue')) === null || _selectedRecord$get === void 0 ? void 0 : _selectedRecord$get.issueId;
    }) || [];
    return selectedIssueIds.indexOf(issueId) === -1;
  });
  return /*#__PURE__*/React.createElement("div", null, selectDs.map(function (record) {
    return /*#__PURE__*/React.createElement(_Form, {
      record: record,
      columns: 11
    }, /*#__PURE__*/React.createElement(_Select, {
      name: "project",
      searchable: true,
      searchMatcher: function searchMatcher() {
        return true;
      },
      onInput: handleSearch,
      optionRenderer: renderProjectOption,
      renderer: renderProject,
      onBlur: handleBlur,
      clearButton: false,
      pagingOptionContent: /*#__PURE__*/React.createElement("span", {
        className: "c7ncd-select-load-more-text"
      }, "\u52A0\u8F7D\u66F4\u591A"),
      colSpan: 5
    }), /*#__PURE__*/React.createElement(_Select, {
      name: "issue",
      optionRenderer: issueNameOptionRender,
      renderer: issueNameRender,
      searchable: true,
      searchMatcher: "content",
      colSpan: 5,
      optionsFilter: handleIssueFilter
    }), /*#__PURE__*/React.createElement(_Button, {
      icon: "delete",
      funcType: "flat",
      onClick: function onClick() {
        return handleDeleteRecord(record);
      },
      className: "c7ncd-form-record-delete-btn"
    }));
  }), /*#__PURE__*/React.createElement(_Button, {
    icon: "add",
    funcType: "flat",
    onClick: handleAddRecord
  }, "\u6DFB\u52A0\u5173\u8054\u95EE\u9898"));
}

export default injectIntl(observer(BranchEdit));