/**
 * tdesign v0.41.7
 * (c) 2022 tdesign
 * @license MIT
 */

import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import throttle from 'lodash/throttle';
import { CloseIcon, InfoCircleFilledIcon, CheckCircleFilledIcon, ErrorCircleFilledIcon } from 'tdesign-icons-vue';
import { prefix } from '../config.js';
import { Button } from '../button/index.js';
import ActionMixin from './actions.js';
import props from './props.js';
import { renderContent, renderTNodeJSX } from '../utils/render-tnode.js';
import mixins from '../utils/mixins.js';
import getConfigReceiverMixins from '../config-provider/config-receiver.js';
import TransferDom from '../utils/transfer-dom.js';
import { emitEvent } from '../utils/event.js';
import { addClass, removeClass } from '../utils/dom.js';
import { updateElement } from '../hooks/useDestroyOnClose.js';
import '../button/button.js';
import '../_chunks/dep-37d5b9c4.js';
import '../utils/classnames.js';
import '../loading/index.js';
import '../loading/loading.js';
import 'vue';
import '../loading/icon/gradient.js';
import '../_common/js/loading/circle-adapter.js';
import '../_common/js/utils/set-style.js';
import '../_common/js/utils/helper.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import '../loading/props.js';
import 'raf';
import 'lodash/isString';
import '../utils/easing.js';
import '@babel/runtime/helpers/typeof';
import '../utils/withInstall.js';
import 'lodash/capitalize';
import './style/css.js';
import '../loading/type.js';
import '../loading/plugin.js';
import '../button/props.js';
import '../utils/ripple.js';
import 'lodash/mergeWith';
import '../config-provider/context.js';
import 'lodash/merge';
import '../_common/js/global-config/default-config.js';
import '../_common/js/global-config/locale/zh_CN.js';
import '../config-provider/type.js';
import '../button/type.js';
import 'lodash/isObject';
import '../utils/helper.js';
import 'lodash/camelCase';

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
var name = "".concat(prefix, "-dialog");
var lockClass = "".concat(prefix, "-dialog--lock");

function getCSSValue(v) {
  return isNaN(Number(v)) ? v : "".concat(Number(v), "px");
}

var _Dialog = mixins(ActionMixin, getConfigReceiverMixins("dialog")).extend({
  name: "TDialog",
  components: {
    CloseIcon: CloseIcon,
    InfoCircleFilledIcon: InfoCircleFilledIcon,
    CheckCircleFilledIcon: CheckCircleFilledIcon,
    ErrorCircleFilledIcon: ErrorCircleFilledIcon,
    TButton: Button
  },
  data: function data() {
    return {
      scrollWidth: 0,
      disX: 0,
      disY: 0,
      windowInnerWidth: 0,
      windowInnerHeight: 0,
      offsetX: 0,
      offsetY: 0,
      dialogW: 0,
      dialogH: 0,
      dLeft: 0,
      dTop: 0
    };
  },
  props: _objectSpread({}, props),
  computed: {
    isModal: function isModal() {
      return this.mode === "modal";
    },
    isModeless: function isModeless() {
      return this.mode === "modeless";
    },
    maskClass: function maskClass() {
      return ["".concat(name, "__mask"), !this.showOverlay && "".concat(prefix, "-is-hidden")];
    },
    dialogClass: function dialogClass() {
      var dialogClass = ["".concat(name), "".concat(name, "--default"), "".concat(name, "--").concat(this.placement), "".concat(name, "__modal-").concat(this.theme)];

      if (["modeless", "modal"].includes(this.mode)) {
        dialogClass.push("".concat(name, "--fixed"));

        if (this.isModal && this.showInAttachedElement) {
          dialogClass.push("".concat(name, "--absolute"));
        }
      }

      return dialogClass;
    },
    dialogStyle: function dialogStyle() {
      var top = this.top,
          placement = this.placement;
      var topStyle = {};

      if (top) {
        var topValue = getCSSValue(top);
        topStyle = {
          top: topValue,
          transform: "translate(-50%, 0)",
          transformOrigin: "25% 25%",
          maxHeight: "calc(100% - ".concat(topValue, ")"),
          zIndex: this.zIndex
        };
      } else if (placement === "top") {
        topStyle = {
          maxHeight: "calc(100% - 20%)"
        };
      }

      return _objectSpread({
        width: getCSSValue(this.width)
      }, topStyle);
    }
  },
  watch: {
    visible: function visible(value) {
      var _this = this;

      if (value) {
        var scrollWidth = this.scrollWidth;

        if (this.isModal && !this.showInAttachedElement) {
          if (scrollWidth > 0) {
            var bodyCssText = "position: relative;width: calc(100% - ".concat(scrollWidth, "px);");
            document.body.style.cssText = bodyCssText;
          }

          addClass(document.body, lockClass);
        }
      } else {
        document.body.style.cssText = "";
        removeClass(document.body, lockClass);
      }

      this.addKeyboardEvent(value);

      if (this.isModeless && this.draggable) {
        this.initDragEvent(value);
      }

      if (value && !this.destroyOnClose && requestAnimationFrame) {
        requestAnimationFrame(function () {
          updateElement(_this);
        });
      }
    }
  },
  mounted: function mounted() {
    this.scrollWidth = window.innerWidth - document.body.offsetWidth;

    if (this.draggable) {
      window.addEventListener("resize", throttle(this.resizeAdjustPosition, 1e3));
    }

    if (this.visible && this.isModal && this.preventScrollThrough) {
      addClass(document.body, lockClass);
    }
  },
  beforeDestroy: function beforeDestroy() {
    this.addKeyboardEvent(false);
  },
  directives: {
    TransferDom: TransferDom
  },
  methods: {
    addKeyboardEvent: function addKeyboardEvent(status) {
      if (status) {
        document.addEventListener("keydown", this.keyboardEvent);
      } else {
        document.removeEventListener("keydown", this.keyboardEvent);
      }
    },
    keyboardEvent: function keyboardEvent(e) {
      if (e.code === "Escape") {
        emitEvent(this, "esc-keydown", {
          e: e
        });

        if (this.closeOnEscKeydown) {
          this.emitCloseEvent({
            trigger: "esc",
            e: e
          });
        }
      }
    },
    overlayAction: function overlayAction(e) {
      emitEvent(this, "overlay-click", {
        e: e
      });

      if (this.closeOnOverlayClick) {
        this.emitCloseEvent({
          trigger: "overlay",
          e: e
        });
      }
    },
    closeBtnAction: function closeBtnAction(e) {
      emitEvent(this, "close-btn-click", {
        e: e
      });
      this.emitCloseEvent({
        trigger: "close-btn",
        e: e
      });
    },
    cancelBtnAction: function cancelBtnAction(e) {
      emitEvent(this, "cancel", {
        e: e
      });
      this.emitCloseEvent({
        trigger: "cancel",
        e: e
      });
    },
    confirmBtnAction: function confirmBtnAction(e) {
      emitEvent(this, "confirm", {
        e: e
      });
    },
    afterEnter: function afterEnter() {
      emitEvent(this, "opened");
    },
    afterLeave: function afterLeave() {
      emitEvent(this, "closed");
    },
    emitCloseEvent: function emitCloseEvent(context) {
      emitEvent(this, "close", context);
      this.$emit("update:visible", false);
    },
    hasEventOn: function hasEventOn(name2) {
      var _this$_events;

      var eventFuncs = (_this$_events = this["_events"]) === null || _this$_events === void 0 ? void 0 : _this$_events[name2];
      return !!(eventFuncs !== null && eventFuncs !== void 0 && eventFuncs.length);
    },
    getIcon: function getIcon() {
      var h = this.$createElement;
      var icon = {
        info: h(InfoCircleFilledIcon, {
          "class": "".concat(prefix, "-is-info")
        }),
        warning: h(ErrorCircleFilledIcon, {
          "class": "".concat(prefix, "-is-warning")
        }),
        danger: h(ErrorCircleFilledIcon, {
          "class": "".concat(prefix, "-is-error")
        }),
        success: h(CheckCircleFilledIcon, {
          "class": "".concat(prefix, "-is-success")
        })
      };
      return icon[this.theme];
    },
    mousedownHandler: function mousedownHandler(targetEvent) {
      var target = this.$refs.dialog;
      this.disX = targetEvent.clientX - target.offsetLeft;
      this.disY = targetEvent.clientY - target.offsetTop;
      this.dialogW = target.offsetWidth;
      this.dialogH = target.offsetHeight;

      var _this$getTranslateXY = this.getTranslateXY(target),
          _this$getTranslateXY2 = _slicedToArray(_this$getTranslateXY, 2),
          x = _this$getTranslateXY2[0],
          y = _this$getTranslateXY2[1];

      this.offsetX = x;
      this.offsetY = y;
      this.windowInnerWidth = window.innerWidth;
      this.windowInnerHeight = window.innerHeight;
      document.addEventListener("mousemove", this.mouseMoverHandler);
      document.addEventListener("mouseup", this.mouseUpHandler);
      document.addEventListener("dragend", this.mouseUpHandler);
    },
    mouseMoverHandler: function mouseMoverHandler(documentEvent) {
      var target = this.$refs.dialog;
      var left = documentEvent.clientX - this.disX;
      var top = documentEvent.clientY - this.disY;

      if (left + this.dialogW - this.offsetX > this.windowInnerWidth) {
        this.dLeft = this.windowInnerWidth - this.dialogW + this.offsetX;
      } else {
        this.dLeft = target.offsetLeft < this.offsetX || left <= this.offsetX ? this.offsetX : left;
      }

      target.style.left = "".concat(this.dLeft, "px");

      if (top + this.dialogH - this.offsetY > this.windowInnerHeight) {
        this.dTop = this.windowInnerHeight - this.dialogH + this.offsetY;
      } else {
        this.dTop = top < this.offsetY ? this.offsetY : top;
      }

      target.style.top = "".concat(this.dTop, "px");
    },
    mouseUpHandler: function mouseUpHandler() {
      document.removeEventListener("mousemove", this.mouseMoverHandler);
      document.removeEventListener("mouseup", this.mouseUpHandler);
      document.removeEventListener("dragend", this.mouseUpHandler);
    },
    initDragEvent: function initDragEvent(status) {
      var target = this.$refs.dialog;

      if (status) {
        target.addEventListener("mousedown", this.mousedownHandler);
      } else {
        target.removeEventListener("mousedown", this.mousedownHandler);
      }
    },
    getTranslateXY: function getTranslateXY(target) {
      var transformStyle = document.defaultView.getComputedStyle(target).transform;
      var reg = /(\d+(\.\d+)?)/g;
      var tarnsArr = transformStyle.match(reg);
      return [parseFloat(tarnsArr[4]), parseFloat(tarnsArr[5])];
    },
    resizeAdjustPosition: function resizeAdjustPosition() {
      if (this.visible) {
        var target = this.$refs.dialog;
        target.style.left = "".concat(this.dLeft * (window.innerWidth / this.windowInnerWidth), "px");
        target.style.top = "".concat(this.dTop * (window.innerHeight / this.windowInnerHeight), "px");
      }
    },
    renderDialog: function renderDialog() {
      var h = this.$createElement;
      var defaultHeader = h("h5", {
        "class": "title"
      });
      var defaultCloseBtn = h("close-icon");
      var body = renderContent(this, "default", "body");
      var defaultFooter = h("div", [this.getCancelBtn({
        cancelBtn: this.cancelBtn,
        globalCancel: this.global.cancel,
        className: "".concat(prefix, "-dialog__cancel")
      }), this.getConfirmBtn({
        theme: this.theme,
        confirmBtn: this.confirmBtn,
        globalConfirm: this.global.confirm,
        globalConfirmBtnTheme: this.global.confirmBtnTheme,
        className: "".concat(prefix, "-dialog__confirm")
      })]);
      var bodyClassName = this.theme === "default" ? "".concat(name, "__body") : "".concat(name, "__body__icon");
      return h("div", {
        "key": "dialog",
        "ref": "dialog",
        "class": this.dialogClass,
        "style": this.dialogStyle
      }, [h("div", {
        "class": "".concat(name, "__header")
      }, [this.getIcon(), renderTNodeJSX(this, "header", defaultHeader)]), this.closeBtn ? h("span", {
        "class": "".concat(name, "__close"),
        "on": {
          "click": this.closeBtnAction
        }
      }, [renderTNodeJSX(this, "closeBtn", defaultCloseBtn)]) : null, h("div", {
        "class": bodyClassName
      }, [body]), h("div", {
        "class": "".concat(name, "__footer")
      }, [renderTNodeJSX(this, "footer", defaultFooter)])]);
    }
  },
  render: function render() {
    var _ref;

    var h = arguments[0];
    var maskView = this.isModal && h("div", {
      "key": "mask",
      "class": this.maskClass,
      "on": {
        "click": this.overlayAction
      }
    });
    var dialogView = this.renderDialog();
    var view = [maskView, dialogView];
    var ctxStyle = {
      zIndex: this.zIndex
    };
    var ctxClass = ["".concat(name, "__ctx"), (_ref = {}, _defineProperty(_ref, "".concat(prefix, "-dialog__ctx--fixed"), this.mode === "modal"), _defineProperty(_ref, "".concat(prefix, "-dialog__ctx--absolute"), this.isModal && this.showInAttachedElement), _ref)];
    return h("transition", {
      "attrs": {
        "duration": 300,
        "name": "".concat(name, "-zoom__vue")
      },
      "on": {
        "afterEnter": this.afterEnter,
        "afterLeave": this.afterLeave
      }
    }, [(!this.destroyOnClose || this.visible) && h("div", {
      "directives": [{
        name: "show",
        value: this.visible
      }, {
        name: "transfer-dom",
        value: this.attach
      }],
      "class": ctxClass,
      "style": ctxStyle
    }, [view])]);
  }
});

export { _Dialog as default };
//# sourceMappingURL=dialog.js.map
