import "choerodon-ui/lib/modal/style";
import _Modal from "choerodon-ui/lib/modal";
import "choerodon-ui/lib/button/style";
import _Button from "choerodon-ui/lib/button";
import "choerodon-ui/lib/input/style";
import _Input from "choerodon-ui/lib/input";
import "choerodon-ui/lib/spin/style";
import _Spin from "@hzero-front-ui/c7n-ui/lib/Spin";
import "choerodon-ui/lib/form/style";
import _Form from "choerodon-ui/lib/form";

var _dec, _dec2, _class;

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

import React, { Component, Fragment } from 'react';
import { observer, inject } from 'mobx-react';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Choerodon } from '@choerodon/boot';
import { handlePromptError } from "../../../../../utils";
import "./index.less";
var FormItem = _Form.Item;
var HAS_VALID = true;
var DeleteModal = (_dec = _Form.create({}), _dec2 = inject('AppState'), _dec(_class = injectIntl(_class = _dec2(_class = observer(_class = /*#__PURE__*/function (_Component) {
  _inherits(DeleteModal, _Component);

  var _super = _createSuper(DeleteModal);

  function DeleteModal(props) {
    var _this;

    _classCallCheck(this, DeleteModal);

    _this = _super.call(this, props);
    _this.sendMessage = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var _this$props, projectId, objectId, objectType, envId, store, _this$state, notificationId, canSendMessage, count;

      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _this$props = _this.props, projectId = _this$props.AppState.currentMenuType.projectId, objectId = _this$props.objectId, objectType = _this$props.objectType, envId = _this$props.envId, store = _this$props.store;
              _this$state = _this.state, notificationId = _this$state.notificationId, canSendMessage = _this$state.canSendMessage;
              count = _this.state.count;

              if (!(_this.timer || !canSendMessage)) {
                _context.next = 5;
                break;
              }

              return _context.abrupt("return");

            case 5:
              _this.setState({
                canSendMessage: false,
                isError: false
              });

              _context.next = 8;
              return store.sendMessage(projectId, envId, objectId, notificationId, objectType)["catch"](function (e) {
                Choerodon.handleResponseError(e);
              });

            case 8:
              // NOTE: 无论验证码是否发送成功，都要经过1分钟后重新发送
              _this.timer = setInterval(function () {
                _this.setState({
                  count: --count
                }, function () {
                  if (count === 0) {
                    _this.clearTimer();

                    _this.setState({
                      count: 60,
                      canSendMessage: true
                    });
                  }
                });
              }, 1000);

            case 9:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    _this.checkCaptcha = function (e) {
      var value = e.target.value;

      _this.setState({
        canDelete: value && value.length === 6,
        isError: false
      });
    };

    _this.deleteData = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var flag,
          _this$props2,
          projectId,
          refresh,
          objectId,
          objectType,
          store,
          envId,
          res,
          _args2 = arguments;

      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              flag = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : false;
              _this$props2 = _this.props, projectId = _this$props2.AppState.currentMenuType.projectId, refresh = _this$props2.refresh, objectId = _this$props2.objectId, objectType = _this$props2.objectType, store = _this$props2.store, envId = _this$props2.envId;

              _this.setState({
                loading: true
              });

              _context2.prev = 3;
              _context2.next = 6;
              return store.deleteData(projectId, objectId, objectType, envId);

            case 6:
              res = _context2.sent;

              if (handlePromptError(res)) {
                store.removeDeleteModal(objectId, objectType);

                if (flag) {
                  _this.clearTimer();

                  _this.setState({
                    count: 60,
                    canSendMessage: true,
                    canDelete: false
                  });
                }

                refresh();
              }

              _this.setState({
                loading: false
              });

              _context2.next = 15;
              break;

            case 11:
              _context2.prev = 11;
              _context2.t0 = _context2["catch"](3);

              _this.setState({
                loading: false
              });

              Choerodon.handleResponseError(_context2.t0);

            case 15:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[3, 11]]);
    }));

    _this.handleDelete = function (e) {
      e.preventDefault();
      var _this$props3 = _this.props,
          validateFields = _this$props3.form.validateFields,
          projectId = _this$props3.AppState.currentMenuType.id,
          objectId = _this$props3.objectId,
          objectType = _this$props3.objectType,
          envId = _this$props3.envId,
          store = _this$props3.store;
      var isVerification = _this.state.isVerification;

      if (!isVerification) {
        _this.deleteData();

        return;
      }

      _this.setState({
        validateLoading: true
      });

      validateFields(function (err, _ref3) {
        var captcha = _ref3.captcha;

        if (!err) {
          store.validateCaptcha(projectId, envId, objectId, captcha, objectType).then(function (data) {
            if (data && data.failed) {
              _this.setState({
                isError: true,
                canDelete: false
              });
            } else {
              _this.clearTimer();

              _this.deleteData(true);
            }

            _this.setState({
              validateLoading: false
            });
          })["catch"](function (error) {
            _this.setState({
              validateLoading: false
            });

            Choerodon.handleResponseError(error);
          });
        } else {
          _this.setState({
            validateLoading: false
          });
        }
      });
    };

    _this.closeModal = function () {
      var _this$props4 = _this.props,
          resetFields = _this$props4.form.resetFields,
          objectId = _this$props4.objectId,
          objectType = _this$props4.objectType,
          store = _this$props4.store;
      store.closeDeleteModal(objectId, objectType);
      resetFields(['captcha']);

      _this.setState({
        isError: false
      });
    };

    _this.state = _objectSpread({}, _this.getInitState);
    return _this;
  }

  _createClass(DeleteModal, [{
    key: "getInitState",
    get: function get() {
      return {
        count: 60,
        checkLoading: true,
        validateLoading: false,
        isError: false,
        canDelete: false,
        canSendMessage: true,
        isVerification: false,
        user: null,
        method: null,
        notificationId: null,
        loading: false
      };
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      this.initCheck();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState) {
      // NOTE: 由于删除模态框在未确认删除前不会销毁
      //       所以每次显示模态框时
      //       都要校验下是否需要发验证码进行二次校验
      if (this.props.visible && prevProps.visible !== this.props.visible) {
        this.initCheck();
      }
    }
  }, {
    key: "clearTimer",
    value: function clearTimer() {
      clearInterval(this.timer);
      this.timer = null;
    }
  }, {
    key: "initCheck",
    value: function () {
      var _initCheck = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
        var _this2 = this;

        var _this$props5, projectId, objectType, envId, store, result;

        return regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _this$props5 = this.props, projectId = _this$props5.AppState.currentMenuType.id, objectType = _this$props5.objectType, envId = _this$props5.envId, store = _this$props5.store;
                this.setState({
                  checkLoading: true
                });
                _context3.next = 4;
                return store.deleteCheck(projectId, envId, objectType)["catch"](function () {
                  _this2.setState({
                    checkLoading: false
                  });
                });

              case 4:
                result = _context3.sent;

                if (handlePromptError(result)) {
                  if (result && result.notificationId) {
                    this.setState({
                      isVerification: true,
                      method: result.method,
                      user: result.user,
                      notificationId: result.notificationId,
                      canDelete: false
                    });
                  } else {
                    this.clearTimer();
                    this.setState(_objectSpread(_objectSpread({}, this.getInitState), {}, {
                      canDelete: true
                    }));
                  }
                }

                this.setState({
                  checkLoading: false
                });

              case 7:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function initCheck() {
        return _initCheck.apply(this, arguments);
      }

      return initCheck;
    }()
    /**
     * 点击发送验证码
     */

  }, {
    key: "getContent",
    get: function get() {
      var _this$props6 = this.props,
          formatMessage = _this$props6.intl.formatMessage,
          getFieldDecorator = _this$props6.form.getFieldDecorator,
          objectType = _this$props6.objectType;
      var _this$state2 = this.state,
          count = _this$state2.count,
          canSendMessage = _this$state2.canSendMessage,
          method = _this$state2.method,
          user = _this$state2.user,
          isVerification = _this$state2.isVerification,
          checkLoading = _this$state2.checkLoading,
          isError = _this$state2.isError;
      var content = /*#__PURE__*/React.createElement(_Spin, {
        spinning: true
      });

      if (!checkLoading) {
        content = isVerification ? /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "".concat(objectType, ".delete.verify.message")
        }), /*#__PURE__*/React.createElement("br", null), /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "delete.verify.message",
          values: {
            method: method,
            user: user
          }
        }), /*#__PURE__*/React.createElement("div", {
          className: "c7ncd-delete-check"
        }, /*#__PURE__*/React.createElement(_Form, {
          className: "c7ncd-captcha-form"
        }, /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator('captcha', {
          rules: [{
            required: true,
            message: formatMessage({
              id: 'required'
            })
          }]
        })( /*#__PURE__*/React.createElement(_Input, {
          label: /*#__PURE__*/React.createElement(FormattedMessage, {
            id: "captcha"
          }),
          onChange: this.checkCaptcha,
          maxLength: 6
        })))), /*#__PURE__*/React.createElement(_Button, {
          className: "c7ncd-captcha-btn",
          type: "primary",
          funcType: "raised",
          onClick: this.sendMessage,
          disabled: !canSendMessage
        }, canSendMessage ? /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "captcha.send"
        }) : /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", null, count), " ", /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "captcha.resend"
        })))), isError && /*#__PURE__*/React.createElement("span", {
          className: "c7ncd-captcha-error"
        }, formatMessage({
          id: 'captcha.error'
        }))) : /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "".concat(objectType, ".delete.message")
        });
      }

      return content;
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props7 = this.props,
          visible = _this$props7.visible,
          title = _this$props7.title;
      var _this$state3 = this.state,
          validateLoading = _this$state3.validateLoading,
          canDelete = _this$state3.canDelete,
          isVerification = _this$state3.isVerification,
          deleteLoading = _this$state3.loading;
      return /*#__PURE__*/React.createElement(_Modal, {
        visible: visible,
        title: title,
        closable: false,
        footer: [/*#__PURE__*/React.createElement(_Button, {
          key: "back",
          onClick: this.closeModal,
          disabled: validateLoading || deleteLoading
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: isVerification ? 'close' : 'cancel'
        })), /*#__PURE__*/React.createElement(_Button, {
          key: "submit",
          type: "danger",
          loading: validateLoading || deleteLoading,
          disabled: !canDelete,
          onClick: this.handleDelete
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "delete"
        }))]
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-delete-wrap"
      }, this.getContent));
    }
  }]);

  return DeleteModal;
}(Component)) || _class) || _class) || _class) || _class);
export default DeleteModal;