import "choerodon-ui/pro/lib/pagination/style";
import _Pagination from "choerodon-ui/pro/lib/pagination";
import "choerodon-ui/pro/lib/icon/style";
import _Icon from "choerodon-ui/pro/lib/icon";
import "choerodon-ui/pro/lib/button/style";
import _Button from "choerodon-ui/pro/lib/button";
import "choerodon-ui/pro/lib/modal/style";
import _Modal from "choerodon-ui/pro/lib/modal";
import "choerodon-ui/lib/collapse/style";
import _Collapse from "choerodon-ui/lib/collapse";

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, useState } from 'react';
import { observer } from 'mobx-react-lite';
import ReactMarkdown from 'react-markdown';
import map from 'lodash/map';
import classNames from 'classnames';
import { Action, Page, Permission } from '@choerodon/boot';
import UserInfo from "../../../../components/userInfo";
import TimePopover from "../../../../components/timePopover";
import EmptyPage from "../../../../components/empty-page";
import Loading from "../../../../components/loading";
import { handlePromptError } from "../../../../utils";
import { useAppTagStore } from "./stores";
import { useCodeManagerStore } from "../../stores";
import AppTagCreate from "./modals/app-tag-create/AppTagCreate";
import AppTagEdit from "./modals/app-tag-edit/index";
import NewEmptyPage from "../../components/empty-page";
import "./index.less";
var Panel = _Collapse.Panel;

var appTagCreateKey = _Modal.key();

var appTagEditKey = _Modal.key();

var deleteKey = _Modal.key();

var bigModelStyle = {
  width: 'calc(100vw - 3.52rem)'
};
export default observer(function (props) {
  var appTagStore = useAppTagStore();
  var formatMessage = appTagStore.formatMessage,
      handleMapStore = appTagStore.handleMapStore,
      appTagDs = appTagStore.appTagDs,
      projectId = appTagStore.projectId,
      tagStore = appTagStore.tagStore,
      appTagCreateDs = appTagStore.appTagCreateDs;

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

  var appServiceId = selectAppDs.current.get('appServiceId');
  var appTagData = appTagDs.toData() || [];
  var styles = props.styles;

  var getSelfToolBarObj = function getSelfToolBarObj() {
    return {
      name: formatMessage({
        id: 'apptag.create'
      }),
      icon: 'playlist_add',
      disabled: !selectAppDs.current.get('appServiceId'),
      display: true,
      permissions: ['choerodon.code.project.develop.code-management.ps.tag.create'],
      handler: openCreate
    };
  };
  /**
   * 生成特殊的自定义tool-bar
   */


  var getSelfToolBar = function getSelfToolBar() {
    return /*#__PURE__*/React.createElement(Permission, {
      service: ['choerodon.code.project.develop.code-management.ps.tag.create']
    }, /*#__PURE__*/React.createElement(_Button, {
      type: "primary",
      funcType: "flat",
      icon: "playlist_add",
      onClick: openCreate,
      disabled: !selectAppDs.current.get('appServiceId')
    }, formatMessage({
      id: 'apptag.create'
    })));
  };

  useEffect(function () {
    handleMapStore.setCodeManagerAppTag({
      refresh: refresh,
      getSelfToolBar: getSelfToolBar,
      getSelfToolBarObj: getSelfToolBarObj
    });
  }, [getSelfToolBar]);

  function refresh() {
    appTagDs.query();
  }

  function handleCreate() {
    return _handleCreate.apply(this, arguments);
  }

  function _handleCreate() {
    _handleCreate = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return appTagCreateDs.submit();

            case 2:
              res = _context2.sent;

              if (res) {
                _context2.next = 5;
                break;
              }

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

            case 5:
              refresh();
              appTagCreateDs.reset();

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

  function handleRemove(_x) {
    return _handleRemove.apply(this, arguments);
  }
  /**
   * 打开删除确认框
   * @param tag
   */


  function _handleRemove() {
    _handleRemove = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(tag) {
      var res;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _context3.prev = 0;
              _context3.next = 3;
              return tagStore.deleteTag(projectId, tag, appServiceId);

            case 3:
              res = _context3.sent;

              if (!handlePromptError(res, false)) {
                _context3.next = 7;
                break;
              }

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

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

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

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

  function openRemove(_x2) {
    return _openRemove.apply(this, arguments);
  }

  function _openRemove() {
    _openRemove = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(tag) {
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.prev = 0;
              _context4.next = 3;
              return tagStore.checkCreate(projectId, appServiceId, 'TAG_DELETE');

            case 3:
              _Modal.open({
                key: deleteKey,
                title: formatMessage({
                  id: 'apptag.action.delete.title'
                }, {
                  name: tag
                }),
                children: formatMessage({
                  id: 'apptag.delete.tooltip'
                }),
                onOk: function onOk() {
                  return handleRemove(tag);
                },
                okText: formatMessage({
                  id: 'delete'
                }),
                okProps: {
                  color: 'red'
                },
                cancelProps: {
                  color: 'dark'
                }
              });

              _context4.next = 8;
              break;

            case 6:
              _context4.prev = 6;
              _context4.t0 = _context4["catch"](0);

            case 8:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4, null, [[0, 6]]);
    }));
    return _openRemove.apply(this, arguments);
  }

  var openCreate = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var createProps;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return tagStore.checkCreate(projectId, appServiceId);

            case 3:
              tagStore.queryBranchData({
                projectId: projectId,
                appServiceId: appServiceId
              });
              createProps = {
                appTagStore: appTagStore,
                tagStore: tagStore,
                projectId: projectId,
                appServiceId: appServiceId
              };

              _Modal.open({
                key: appTagCreateKey,
                title: formatMessage({
                  id: 'apptag.create'
                }),
                children: /*#__PURE__*/React.createElement(AppTagCreate, createProps),
                drawer: true,
                style: bigModelStyle,
                okText: formatMessage({
                  id: 'create'
                }),
                onCancel: function onCancel() {
                  appTagCreateDs.reset();
                },
                onOk: handleCreate
              });

              _context.next = 10;
              break;

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

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

    return function openCreate() {
      return _ref.apply(this, arguments);
    };
  }();

  var openEdit = function openEdit(tag, release) {
    var editProps = {
      tag: tag,
      release: release,
      tagStore: tagStore,
      refresh: refresh,
      projectId: projectId,
      appServiceId: appServiceId,
      appTagStore: appTagStore
    };

    _Modal.open({
      key: appTagEditKey,
      title: formatMessage({
        id: 'apptag.update'
      }),
      children: /*#__PURE__*/React.createElement(AppTagEdit, editProps),
      drawer: true,
      style: bigModelStyle,
      okText: formatMessage({
        id: 'save'
      })
    });
  };

  function getTagList() {
    return map(appTagData, function (item) {
      var _item$commit = item.commit,
          authorName = _item$commit.authorName,
          committedDate = _item$commit.committedDate,
          commitMsg = _item$commit.message,
          shortId = _item$commit.shortId,
          url = _item$commit.url,
          commitUserImage = item.commitUserImage,
          release = item.release;
      var header = /*#__PURE__*/React.createElement("div", {
        className: "c7n-tag-panel"
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7n-tag-panel-info"
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7n-tag-panel-name"
      }, /*#__PURE__*/React.createElement(_Icon, {
        type: "local_offer"
      }), /*#__PURE__*/React.createElement("div", {
        className: "c7n-tag-name"
      }, /*#__PURE__*/React.createElement("span", {
        className: "c7n-tag-name-text"
      }, release.tagName)), /*#__PURE__*/React.createElement("div", {
        className: "c7n-tag-action",
        onClick: stopPropagation
      }, /*#__PURE__*/React.createElement(Action, {
        data: [{
          service: ['choerodon.code.project.develop.code-management.ps.tag.update'],
          text: formatMessage({
            id: 'edit'
          }),
          action: function action() {
            openEdit(release.tagName, release.description !== 'empty' ? release.description : formatMessage({
              id: 'apptag.release.empty'
            }));
          }
        }, {
          service: [// 'choerodon.code.project.develop.code-management.ps.tag.delete',
          ],
          text: formatMessage({
            id: 'delete'
          }),
          action: function action() {
            openRemove(release.tagName);
          }
        }]
      }))), /*#__PURE__*/React.createElement("div", {
        className: "c7n-tag-panel-detail"
      }, /*#__PURE__*/React.createElement(_Icon, {
        className: "c7n-tag-icon-point",
        type: "point"
      }), /*#__PURE__*/React.createElement("a", {
        href: url,
        rel: "nofollow me noopener noreferrer",
        target: "_blank"
      }, shortId), /*#__PURE__*/React.createElement("span", {
        className: "c7n-divide-point"
      }, "\u2022"), /*#__PURE__*/React.createElement("span", {
        className: "c7n-tag-msg"
      }, commitMsg), /*#__PURE__*/React.createElement("span", {
        className: "c7n-divide-point"
      }, "\u2022"), /*#__PURE__*/React.createElement("span", {
        className: "c7n-tag-panel-person"
      }, /*#__PURE__*/React.createElement(UserInfo, {
        name: authorName || '',
        avatar: commitUserImage
      })), /*#__PURE__*/React.createElement("span", {
        className: "c7n-divide-point"
      }, "\u2022"), /*#__PURE__*/React.createElement("div", {
        className: "c7n-tag-time"
      }, /*#__PURE__*/React.createElement(TimePopover, {
        content: committedDate
      })))));
      return /*#__PURE__*/React.createElement(Panel, {
        header: header,
        key: release.tagName
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7n-tag-release"
      }, release ? /*#__PURE__*/React.createElement("div", {
        className: "c7n-md-parse c7n-md-preview"
      }, /*#__PURE__*/React.createElement(ReactMarkdown, {
        source: release.description !== 'empty' ? release.description : formatMessage({
          id: 'apptag.release.empty'
        }),
        skipHtml: false,
        escapeHtml: false
      })) : formatMessage({
        id: 'apptag.release.empty'
      })));
    });
  }

  function getContent() {
    return appTagData.length > 0 ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_Collapse, {
      bordered: false
    }, getTagList()), /*#__PURE__*/React.createElement("div", {
      className: "c7n-tag-pagin"
    }, /*#__PURE__*/React.createElement(_Pagination, {
      dataSet: appTagDs
    }))) : /*#__PURE__*/React.createElement(EmptyPage, {
      title: formatMessage({
        id: 'code-management.tag.empty'
      }),
      describe: formatMessage({
        id: 'code-management.tag.empty.des'
      }),
      btnText: formatMessage({
        id: 'apptag.create'
      }),
      onClick: openCreate,
      access: true
    });
  }

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Page, {
    className: classNames('c7n-tag-wrapper', 'page-container', styles === null || styles === void 0 ? void 0 : styles['c7n-branch-theme4-page']),
    service: []
  }, appServiceDs.status !== 'ready' || appTagDs.status !== 'ready' ? /*#__PURE__*/React.createElement(Loading, {
    display: true
  }) : /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-tag-content"
  }, tagStore.getIsEmpty ? /*#__PURE__*/React.createElement(NewEmptyPage, {
    title: formatMessage({
      id: 'empty.title.prohibited'
    }),
    describe: formatMessage({
      id: 'empty.title.code'
    }),
    btnText: formatMessage({
      id: 'empty.link.code'
    }),
    pathname: "/rducm/code-lib-management/apply"
  }) : getContent())));
});

function stopPropagation(e) {
  e.stopPropagation();
}