import "choerodon-ui/lib/tooltip/style";
import _Tooltip from "choerodon-ui/lib/tooltip";
import "choerodon-ui/lib/button/style";
import _Button from "choerodon-ui/lib/button";
import "choerodon-ui/pro/lib/spin/style";
import _Spin from "choerodon-ui/pro/lib/spin";
import "choerodon-ui/pro/lib/modal/style";
import _Modal from "choerodon-ui/pro/lib/modal";

var _this = this;

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

import React, { memo, useMemo, Fragment, useImperativeHandle } from 'react';
import { FormattedMessage } from 'react-intl';
import { Header, Permission, Choerodon } from '@choerodon/boot';
import { observer } from 'mobx-react-lite';
import { useAppTopStore } from "../stores";
import { useServiceDetailStore } from "./stores";
import Detail from "./modals/detail";
import EditForm from "../modals/edit-form";
import { handlePromptError } from "../../../utils";

var modalKey1 = _Modal.key();

var modalKey3 = _Modal.key();

var editModalKey = _Modal.key();

var modalStyle = {
  width: 380
};
var HeaderButtons = observer(function (_ref) {
  var children = _ref.children,
      theme4 = _ref.theme4;

  var _useAppTopStore = useAppTopStore(),
      intlPrefix = _useAppTopStore.intlPrefix,
      prefixCls = _useAppTopStore.prefixCls,
      appServiceStore = _useAppTopStore.appServiceStore;

  var _useServiceDetailStor = useServiceDetailStore(),
      formatMessage = _useServiceDetailStor.intl.formatMessage,
      projectId = _useServiceDetailStor.AppState.currentMenuType.projectId,
      detailDs = _useServiceDetailStor.detailDs,
      cRef = _useServiceDetailStor.cRef;

  var serviceActive = useMemo(function () {
    return detailDs.current && detailDs.current.get('active');
  }, [detailDs.current]);
  var detailCurrent = useMemo(function () {
    return detailDs.current;
  }, [detailDs.current]);
  useImperativeHandle(cRef, function () {
    return {
      openDetail: openDetail
    };
  });

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

  function openDetail() {
    _Modal.open({
      key: modalKey1,
      title: formatMessage({
        id: "".concat(intlPrefix, ".detail")
      }),
      children: /*#__PURE__*/React.createElement(Detail, {
        record: detailCurrent,
        intlPrefix: intlPrefix,
        prefixCls: prefixCls,
        formatMessage: formatMessage
      }),
      drawer: true,
      style: modalStyle,
      okText: formatMessage({
        id: 'close'
      }),
      okCancel: false
    });
  }

  function openEdit() {
    var appServiceId = detailCurrent.get('id');

    _Modal.open({
      key: editModalKey,
      drawer: true,
      style: modalStyle,
      title: formatMessage({
        id: "".concat(intlPrefix, ".edit")
      }),
      children: /*#__PURE__*/React.createElement(EditForm, {
        refresh: refresh,
        intlPrefix: intlPrefix,
        prefixCls: prefixCls,
        appServiceId: appServiceId
      }),
      okText: formatMessage({
        id: 'save'
      })
    });
  }

  function getActiveText() {
    var active = serviceActive ? 'disable' : 'enable';
    return /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "".concat(intlPrefix, ".").concat(active)
    });
  }

  function openStop(record) {
    var id = record.get('id');

    var stopModal = _Modal.open({
      key: modalKey3,
      title: formatMessage({
        id: "".concat(intlPrefix, ".check")
      }),
      children: /*#__PURE__*/React.createElement(_Spin, null),
      footer: null
    });

    appServiceStore.checkAppService(projectId, id).then(function (res) {
      if (handlePromptError(res)) {
        var checkResources = res.checkResources,
            checkRule = res.checkRule;
        var status = checkResources || checkRule;
        var childrenContent;

        if (!status) {
          childrenContent = /*#__PURE__*/React.createElement(FormattedMessage, {
            id: "".concat(intlPrefix, ".stop.tips")
          });
        } else if (checkResources && !checkRule) {
          childrenContent = formatMessage({
            id: "".concat(intlPrefix, ".has.resource")
          });
        } else if (!checkResources && checkRule) {
          childrenContent = formatMessage({
            id: "".concat(intlPrefix, ".has.rules")
          });
        } else {
          childrenContent = formatMessage({
            id: "".concat(intlPrefix, ".has.both")
          });
        }

        var statusObj = {
          title: status ? formatMessage({
            id: "".concat(intlPrefix, ".cannot.stop")
          }) : formatMessage({
            id: "".concat(intlPrefix, ".stop")
          }, {
            name: detailDs.current.get('name')
          }),
          // eslint-disable-next-line no-nested-ternary
          children: childrenContent,
          okCancel: !status,
          onOk: function onOk() {
            return status ? stopModal.close() : handleChangeActive(false);
          },
          okText: status ? formatMessage({
            id: 'iknow'
          }) : formatMessage({
            id: 'stop'
          }),
          footer: function footer(okBtn, cancelBtn) {
            return /*#__PURE__*/React.createElement(React.Fragment, null, okBtn, !status && cancelBtn);
          }
        };
        stopModal.update(statusObj);
      } else {
        stopModal.close();
      }
    })["catch"](function (err) {
      stopModal.close();
      Choerodon.handleResponseError(err);
    });
  } // eslint-disable-next-line consistent-return


  function handleChangeActive(_x) {
    return _handleChangeActive.apply(this, arguments);
  }

  function _handleChangeActive() {
    _handleChangeActive = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(active) {
      var current;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              current = detailDs.current;
              _context.prev = 1;
              _context.next = 4;
              return appServiceStore.changeActive(projectId, current.get('id'), active);

            case 4:
              _context.t0 = _context.sent;

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

              detailDs.query();
              _context.next = 10;
              break;

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

            case 10:
              _context.next = 16;
              break;

            case 12:
              _context.prev = 12;
              _context.t1 = _context["catch"](1);
              Choerodon.handleResponseError(_context.t1);
              return _context.abrupt("return", false);

            case 16:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[1, 12]]);
    }));
    return _handleChangeActive.apply(this, arguments);
  }

  return theme4 ? children : /*#__PURE__*/React.createElement(Header, null, /*#__PURE__*/React.createElement(Permission, {
    service: ['choerodon.code.project.develop.app-service.ps.update']
  }, /*#__PURE__*/React.createElement(_Tooltip, {
    title: !serviceActive ? /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "".concat(intlPrefix, ".button.disabled")
    }) : '',
    placement: "bottom"
  }, /*#__PURE__*/React.createElement(_Button, {
    icon: "mode_edit ",
    onClick: openEdit,
    disabled: !serviceActive
  }, /*#__PURE__*/React.createElement(FormattedMessage, {
    id: "".concat(intlPrefix, ".edit")
  })))), /*#__PURE__*/React.createElement(Permission, {
    service: [serviceActive ? 'choerodon.code.project.develop.app-service.ps.disable' : 'choerodon.code.project.develop.app-service.ps.enable']
  }, /*#__PURE__*/React.createElement(_Button, {
    icon: serviceActive ? 'remove_circle_outline' : 'finished' // eslint-disable-next-line react/jsx-no-bind
    ,
    onClick: serviceActive ? openStop.bind(_this, detailCurrent) : handleChangeActive.bind(_this, true)
  }, getActiveText())), /*#__PURE__*/React.createElement(Permission, {
    service: ['choerodon.code.project.develop.app-service.ps.default']
  }, /*#__PURE__*/React.createElement(_Button, {
    icon: "find_in_page",
    onClick: openDetail
  }, /*#__PURE__*/React.createElement(FormattedMessage, {
    id: "".concat(intlPrefix, ".detail")
  }))), children);
});
export default HeaderButtons;