import "choerodon-ui/lib/radio/style";
import _Radio from "choerodon-ui/lib/radio";
import "choerodon-ui/lib/tooltip/style";
import _Tooltip from "choerodon-ui/lib/tooltip";
import "choerodon-ui/lib/icon/style";
import _Icon from "choerodon-ui/lib/icon";
import "choerodon-ui/pro/lib/button/style";
import _Button from "choerodon-ui/pro/lib/button";
import "choerodon-ui/pro/lib/table/style";
import _Table from "@hzero-front-ui/c7n-ui/lib/TablePro";
import "choerodon-ui/pro/lib/tabs/style";
import _Tabs from "choerodon-ui/pro/lib/tabs";

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

/* eslint-disable */
import React, { useEffect, Fragment, useMemo } from 'react';
import { withRouter } from 'react-router-dom';
import { observer } from 'mobx-react-lite';
import classNames from 'classnames';
import { Page, Permission } from '@choerodon/boot';
import map from 'lodash/map';
import { useRequestStore } from "./stores";
import Loading from "../../../../components/loading";
import MouseOverWrapper from "../../../../components/MouseOverWrapper";
import ClickText from "../../../../components/click-text";
import TimePopover from "../../../../components/timePopover";
import UserInfo from "../../../../components/userInfo";
import handleMapStore from "../../main-view/store/handleMapStore";
import { useCodeManagerStore } from "../../stores";
import EmptyPage from "../../components/empty-page";
import "./index.less";
import "../../../main.less";
import "./theme4.less";
var TabPane = _Tabs.TabPane;
var Column = _Table.Column;
var RequestPanel = withRouter(observer(function (props) {
  var _useRequestStore = useRequestStore(),
      _useRequestStore$AppS = _useRequestStore.AppState.currentMenuType,
      projectId = _useRequestStore$AppS.id,
      id = _useRequestStore$AppS.id,
      formatMessage = _useRequestStore.intl.formatMessage,
      openTableDS = _useRequestStore.openTableDS,
      mergedRequestStore = _useRequestStore.mergedRequestStore;

  var styles = props.styles;

  var _useCodeManagerStore = useCodeManagerStore(),
      appServiceDs = _useCodeManagerStore.appServiceDs,
      selectAppDs = _useCodeManagerStore.selectAppDs;

  var _mergedRequestStore$g = mergedRequestStore.getCount,
      closeCount = _mergedRequestStore$g.closeCount,
      mergeCount = _mergedRequestStore$g.mergeCount,
      openCount = _mergedRequestStore$g.openCount,
      totalCount = _mergedRequestStore$g.totalCount,
      auditCount = _mergedRequestStore$g.auditCount,
      getTabKey = mergedRequestStore.getTabKey,
      setTabKey = mergedRequestStore.setTabKey;
  var appId = selectAppDs.current && selectAppDs.current.get('appServiceId');
  var tabPaneList = useMemo(function () {
    return [{
      key: 'opened',
      count: openCount || 0
    }, {
      key: 'merged',
      count: mergeCount || 0
    }, {
      key: 'closed',
      count: closeCount || 0
    }, {
      key: 'all',
      count: totalCount || 0
    }];
  }, [closeCount, mergeCount, openCount, totalCount]);
  handleMapStore.setCodeManagerMergeRequest({
    refresh: reload,
    select: handleChange,
    getSelfToolBar: getSelfToolBar,
    getSelfToolBarObj: getSelfToolBarObj
  });
  useEffect(function () {
    mergedRequestStore.loadUser();
  }, []);

  function tabChange(e) {
    var key = e.target.value;
    setTabKey(key);
    openTableDS.query();
  }

  function reload() {
    appId && openTableDS.query();
  }

  function handleChange() {
    appId && openTableDS.query();
  }

  function getSelfToolBarObj() {
    return {
      name: formatMessage({
        id: 'merge.createMerge'
      }),
      icon: 'playlist_add',
      display: true,
      disabled: !mergedRequestStore.getUrl,
      permission: ['choerodon.code.project.develop.code-management.ps.default'],
      handler: linkToNewMerge
    };
  }

  function getSelfToolBar() {
    return /*#__PURE__*/React.createElement(Permission, {
      service: ['choerodon.code.project.develop.code-management.ps.default']
    }, /*#__PURE__*/React.createElement(_Button, {
      funcType: "flat",
      onClick: linkToNewMerge,
      disabled: !mergedRequestStore.getUrl,
      icon: "playlist_add"
    }, formatMessage({
      id: 'merge.createMerge'
    })));
  }

  function linkToNewMerge() {
    return _linkToNewMerge.apply(this, arguments);
  }

  function _linkToNewMerge() {
    _linkToNewMerge = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var res, url;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return mergedRequestStore.checkMerge(projectId, appId);

            case 3:
              res = _context.sent;

              if (res) {
                url = "".concat(mergedRequestStore.getUrl, "/merge_requests/new");
                window.open(url);
              }

              _context.next = 9;
              break;

            case 7:
              _context.prev = 7;
              _context.t0 = _context["catch"](0);

            case 9:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[0, 7]]);
    }));
    return _linkToNewMerge.apply(this, arguments);
  }

  function linkToMerge(iid) {
    var url = "".concat(mergedRequestStore.getUrl, "/merge_requests/").concat(iid);
    window.open(url);
  }

  function renderTitle(_ref) {
    var value = _ref.value,
        record = _ref.record;
    return /*#__PURE__*/React.createElement(MouseOverWrapper, {
      text: value,
      width: 0.25
    }, /*#__PURE__*/React.createElement(ClickText, {
      value: value,
      clickAble: true,
      onClick: linkToMerge,
      record: record.get('iid')
    }));
  }

  function renderIid(_ref2) {
    var value = _ref2.value;
    return /*#__PURE__*/React.createElement("span", null, "!", value);
  }

  function renderTargetBranch(_ref3) {
    var value = _ref3.value,
        record = _ref3.record;
    return /*#__PURE__*/React.createElement("div", {
      className: "c7n-merge-branches",
      style: {
        display: 'flex',
        alignItems: 'center'
      }
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: "branch"
    }), /*#__PURE__*/React.createElement(MouseOverWrapper, {
      text: record.get('sourceBranch'),
      width: 0.1
    }, record.get('sourceBranch')), /*#__PURE__*/React.createElement(_Icon, {
      type: "keyboard_backspace",
      className: "c7n-merge-right"
    }), /*#__PURE__*/React.createElement(_Icon, {
      type: "branch"
    }), /*#__PURE__*/React.createElement("span", null, value));
  }

  function renderCreatedAt(_ref4) {
    var value = _ref4.value,
        record = _ref4.record;
    var author = record.get('author');
    return /*#__PURE__*/React.createElement("div", {
      className: "c7ncd-merge-create-info"
    }, author ? /*#__PURE__*/React.createElement(_Tooltip, {
      title: "".concat(author.name).concat(author.username ? "(".concat(author.username, ")") : '')
    }, author.avatarUrl ? /*#__PURE__*/React.createElement("img", {
      className: "c7n-merge-avatar",
      src: author.avatarUrl,
      alt: "avatar"
    }) : /*#__PURE__*/React.createElement("span", {
      className: "apptag-commit apptag-commit-avatar"
    }, author.name.toString().substr(0, 1))) : /*#__PURE__*/React.createElement("span", {
      className: "apptag-commit apptag-commit-avatar"
    }, "?"), /*#__PURE__*/React.createElement(TimePopover, {
      content: value
    }));
  }

  function renderCommit(_ref5) {
    var value = _ref5.value,
        record = _ref5.record;
    return /*#__PURE__*/React.createElement("div", null, value && value.length ? "".concat(value.length, " commits") : '0 commit');
  }

  function renderUpdateDate(_ref6) {
    var value = _ref6.value;
    return /*#__PURE__*/React.createElement(TimePopover, {
      content: value
    });
  }

  function renderAssignee(_ref7) {
    var value = _ref7.value;
    return value ? /*#__PURE__*/React.createElement(UserInfo, {
      name: value.name || '',
      id: value.username,
      avatar: value.avatarUrl
    }) : formatMessage({
      id: 'merge.noAssignee'
    });
  }

  function renderTable(tabPaneKey) {
    return /*#__PURE__*/React.createElement(_Table, {
      dataSet: openTableDS,
      queryBar: "none"
    }, /*#__PURE__*/React.createElement(Column, {
      name: "title",
      renderer: renderTitle
    }), /*#__PURE__*/React.createElement(Column, {
      name: "iid",
      renderer: renderIid,
      width: 80,
      align: "left"
    }), /*#__PURE__*/React.createElement(Column, {
      name: "targetBranch",
      renderer: renderTargetBranch
    }), tabPaneKey === 'all' && /*#__PURE__*/React.createElement(Column, {
      name: "state",
      width: 90
    }), /*#__PURE__*/React.createElement(Column, {
      name: "createdAt",
      renderer: renderCreatedAt
    }), /*#__PURE__*/React.createElement(Column, {
      name: "commits",
      renderer: renderCommit
    }), /*#__PURE__*/React.createElement(Column, {
      name: "updatedAt",
      renderer: renderUpdateDate,
      width: 100
    }), (tabPaneKey === 'opened' || tabPaneKey === 'assignee') && /*#__PURE__*/React.createElement(Column, {
      name: "assignee",
      renderer: renderAssignee
    }));
  }

  var renderContent = function renderContent(key) {
    return renderTable(key);
  };

  return /*#__PURE__*/React.createElement(Page, {
    className: classNames('c7n-region page-container', 'c7n-merge-wrapper', styles === null || styles === void 0 ? void 0 : styles['c7n-branch-theme4-page']),
    service: []
  }, appServiceDs.status !== 'ready' || !appId ? /*#__PURE__*/React.createElement(Loading, {
    display: true
  }) : !mergedRequestStore.getIsEmpty ? /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(_Radio.Group, {
    className: "c7ncd-merge-radio",
    value: getTabKey,
    onChange: tabChange
  }, map(tabPaneList, function (_ref8) {
    var key = _ref8.key,
        count = _ref8.count;
    return /*#__PURE__*/React.createElement(_Radio.Button, {
      value: key
    }, "".concat(formatMessage({
      id: "merge.tab.".concat(key)
    }), "(").concat(count, ")"));
  }), auditCount > 0 && /*#__PURE__*/React.createElement(_Radio.Button, {
    value: "assignee"
  }, "".concat(formatMessage({
    id: 'merge.tab.assignee'
  }), "(").concat(auditCount || 0, ")"))), renderContent(getTabKey)) : /*#__PURE__*/React.createElement(EmptyPage, {
    title: formatMessage({
      id: 'empty.title.prohibited'
    }),
    describe: formatMessage({
      id: 'empty.title.code'
    }),
    btnText: formatMessage({
      id: 'empty.link.code'
    }),
    pathname: "/rducm/code-lib-management/apply"
  }));
}));
export default RequestPanel;