import { defineComponent, ref, watchEffect, onMounted, onUnmounted, openBlock, createElementBlock, normalizeClass, unref, createElementVNode, withModifiers, normalizeStyle, Fragment, renderList, createVNode, withDirectives, vShow, createCommentVNode, toDisplayString } from "vue";
import "../../../adapter-vue.mjs";
import { TUITranslateService } from "@tencentcloud/chat-uikit-engine";
import { getPlatform, TUIGlobal } from "@tencentcloud/universal-api";
import Icon from "../Icon.vue.mjs";
import closeIcon from "../../../assets/icon/icon-close.svg.mjs";
import iconArrowLeft from "../../../assets/icon/icon-arrow-left.svg.mjs";
import iconZoomIn from "../../../assets/icon/zoom-in.svg.mjs";
import iconZoomOut from "../../../assets/icon/zoom-out.svg.mjs";
import iconRotateLeft from "../../../assets/icon/rotate-left.svg.mjs";
import iconRotateRight from "../../../assets/icon/rotate-right.svg.mjs";
import iconDownload from "../../../assets/icon/download.svg.mjs";
import _sfc_main$1 from "./image-item.vue.mjs";
/* empty css                 */
import { Toast } from "../Toast/index.mjs";
import { isMobile, isUniFrameWork, isPC } from "../../../utils/env.mjs";
import TOAST_TYPE from "../Toast/type.mjs";
const _hoisted_1 = { class: "image-counter" };
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "index",
  props: {
    imageList: { default: () => [] },
    currentImage: {}
  },
  emits: ["close"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const imageFormatMap = /* @__PURE__ */ new Map([
      [1, "jpg"],
      [2, "gif"],
      [3, "png"],
      [4, "bmp"]
    ]);
    const emit = __emit;
    const zoom = ref(1);
    const rotate = ref(0);
    const minZoom = ref(0.1);
    const currentImageIndex = ref(0);
    const image = ref();
    const ulRef = ref();
    let startX = 0;
    const touchStore = {};
    let moveFlag = false;
    let twoTouchesFlag = false;
    let timer = null;
    watchEffect(() => {
      currentImageIndex.value = props.imageList.findIndex((message) => {
        var _a;
        return message.ID === ((_a = props == null ? void 0 : props.currentImage) == null ? void 0 : _a.ID);
      });
    });
    const isNumber = (value) => {
      return typeof value === "number" && isFinite(value);
    };
    const handleTouchStart = (e) => {
      e.preventDefault();
      moveInit(e);
      twoTouchesInit(e);
    };
    const handleTouchMove = (e) => {
      e.preventDefault();
      moveFlag = true;
      if (e.touches && e.touches.length === 2) {
        twoTouchesFlag = true;
        handleTwoTouches(e);
      }
    };
    const handleTouchEnd = (e) => {
      var _a;
      e.preventDefault();
      e.stopPropagation();
      let moveEndX = 0;
      let X = 0;
      if (twoTouchesFlag) {
        if (!timer) {
          twoTouchesFlag = false;
          delete touchStore.pageX2;
          delete touchStore.pageY2;
          timer = setTimeout(() => {
            timer = null;
          }, 200);
        }
        return;
      }
      if (timer === null) {
        switch (moveFlag) {
          case true:
            moveEndX = (_a = e == null ? void 0 : e.changedTouches[0]) == null ? void 0 : _a.pageX;
            X = moveEndX - startX;
            if (X > 100) {
              goPrev();
            } else if (X < -100) {
              goNext();
            }
            break;
          case false:
            close();
            break;
        }
        timer = setTimeout(() => {
          timer = null;
        }, 200);
      }
    };
    const handleTouchCancel = () => {
      twoTouchesFlag = false;
      delete touchStore.pageX1;
      delete touchStore.pageY1;
    };
    const handleWheel = (e) => {
      e.preventDefault();
      if (Math.abs(e.deltaX) !== 0 && Math.abs(e.deltaY) !== 0) return;
      let scale = zoom.value;
      scale += e.deltaY * (e.ctrlKey ? -0.01 : 2e-3);
      scale = Math.min(Math.max(0.125, scale), 4);
      zoom.value = scale;
    };
    const moveInit = (e) => {
      var _a;
      startX = (_a = e == null ? void 0 : e.changedTouches[0]) == null ? void 0 : _a.pageX;
      moveFlag = false;
    };
    const twoTouchesInit = (e) => {
      const touch1 = e == null ? void 0 : e.touches[0];
      const touch2 = e == null ? void 0 : e.touches[1];
      touchStore.pageX1 = touch1 == null ? void 0 : touch1.pageX;
      touchStore.pageY1 = touch1 == null ? void 0 : touch1.pageY;
      if (touch2) {
        touchStore.pageX2 = touch2 == null ? void 0 : touch2.pageX;
        touchStore.pageY2 = touch2 == null ? void 0 : touch2.pageY;
      }
    };
    const handleTwoTouches = (e) => {
      const touch1 = e == null ? void 0 : e.touches[0];
      const touch2 = e == null ? void 0 : e.touches[1];
      if (touch2) {
        if (!isNumber(touchStore.pageX2)) {
          touchStore.pageX2 = touch2.pageX;
        }
        if (!isNumber(touchStore.pageY2)) {
          touchStore.pageY2 = touch2.pageY;
        }
      }
      const getDistance = (startX2, startY, stopX, stopY) => {
        return Math.hypot(stopX - startX2, stopY - startY);
      };
      if (!isNumber(touchStore.pageX1) || !isNumber(touchStore.pageY1) || !isNumber(touchStore.pageX2) || !isNumber(touchStore.pageY2)) {
        return;
      }
      const touchZoom = getDistance(touch1.pageX, touch1.pageY, touch2.pageX, touch2.pageY) / getDistance(
        touchStore.pageX1,
        touchStore.pageY1,
        touchStore.pageX2,
        touchStore.pageY2
      );
      zoom.value = Math.min(Math.max(0.5, zoom.value * touchZoom), 4);
    };
    onMounted(() => {
      (document == null ? void 0 : document.addEventListener) && (document == null ? void 0 : document.addEventListener("keydown", handleEsc));
    });
    const handleEsc = (e) => {
      e.preventDefault();
      if ((e == null ? void 0 : e.keyCode) === 27) {
        close();
      }
    };
    const zoomIn = () => {
      zoom.value += 0.1;
    };
    const zoomOut = () => {
      zoom.value = zoom.value - 0.1 > minZoom.value ? zoom.value - 0.1 : minZoom.value;
    };
    const close = () => {
      emit("close");
    };
    const rotateLeft = () => {
      rotate.value -= 90;
    };
    const rotateRight = () => {
      rotate.value += 90;
    };
    const goNext = () => {
      currentImageIndex.value < props.imageList.length - 1 && currentImageIndex.value++;
      initStyle();
    };
    const goPrev = () => {
      currentImageIndex.value > 0 && currentImageIndex.value--;
      initStyle();
    };
    const initStyle = () => {
      zoom.value = 1;
      rotate.value = 0;
    };
    const getImageUrl = (message) => {
      var _a, _b, _c, _d;
      if (isPC) {
        return (_b = (_a = message == null ? void 0 : message.payload) == null ? void 0 : _a.imageInfoArray[0]) == null ? void 0 : _b.url;
      } else {
        return (_d = (_c = message == null ? void 0 : message.payload) == null ? void 0 : _c.imageInfoArray[2]) == null ? void 0 : _d.url;
      }
    };
    const save = () => {
      var _a, _b;
      const imageMessage = props.imageList[currentImageIndex.value];
      const imageSrc = (_b = (_a = imageMessage == null ? void 0 : imageMessage.payload) == null ? void 0 : _a.imageInfoArray[0]) == null ? void 0 : _b.url;
      if (!imageSrc) {
        Toast({
          message: TUITranslateService.t("component.图片 url 不存在"),
          type: TOAST_TYPE.ERROR
        });
        return;
      }
      switch (getPlatform()) {
        case "wechat":
          TUIGlobal.getSetting({
            success: (res) => {
              if (!(res == null ? void 0 : res.authSetting["scope.writePhotosAlbum"])) {
                TUIGlobal.authorize({
                  scope: "scope.writePhotosAlbum",
                  success() {
                    downloadImgInUni(imageSrc);
                  },
                  fail() {
                    TUIGlobal.showModal({
                      title: "您已拒绝获取相册权限",
                      content: "是否进入权限管理，调整授权？",
                      success: (res2) => {
                        if (res2.confirm) {
                          TUIGlobal.openSetting({
                            success: (res3) => {
                              console.log(res3.authSetting);
                            }
                          });
                        } else if (res2.cancel) {
                          return Toast({
                            message: TUITranslateService.t("component.已取消"),
                            type: TOAST_TYPE.ERROR
                          });
                        }
                      }
                    });
                  }
                });
              } else {
                downloadImgInUni(imageSrc);
              }
            },
            fail: () => {
              Toast({
                message: TUITranslateService.t("component.获取权限失败"),
                type: TOAST_TYPE.ERROR
              });
            }
          });
          break;
        case "app":
          downloadImgInUni(imageSrc);
          break;
        default:
          downloadImgInWeb(imageSrc);
          break;
      }
    };
    const downloadImgInUni = (src) => {
      TUIGlobal.showLoading({
        title: "大图提取中"
      });
      TUIGlobal.downloadFile({
        url: src,
        success: function(res) {
          TUIGlobal.hideLoading();
          TUIGlobal.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              Toast({
                message: TUITranslateService.t("component.已保存至相册"),
                type: TOAST_TYPE.SUCCESS
              });
            }
          });
        },
        fail: function() {
          TUIGlobal.hideLoading();
          Toast({
            message: TUITranslateService.t("component.图片下载失败"),
            type: TOAST_TYPE.ERROR
          });
        }
      });
    };
    const downloadImgInWeb = (src) => {
      var _a;
      const option = {
        mode: "cors",
        headers: new Headers({
          "Content-Type": "application/x-www-form-urlencoded"
        })
      };
      const imageMessage = props.imageList[currentImageIndex.value];
      const imageFormat = (_a = imageMessage == null ? void 0 : imageMessage.payload) == null ? void 0 : _a.imageFormat;
      if (!imageFormatMap.has(imageFormat)) {
        Toast({
          message: TUITranslateService.t("component.暂不支持下载此类型图片"),
          type: TOAST_TYPE.ERROR
        });
        return;
      }
      if (window.fetch) {
        fetch(src, option).then((res) => res.blob()).then((blob) => {
          const a = document.createElement("a");
          const url = window.URL.createObjectURL(blob);
          a.href = url;
          a.download = url + "." + imageFormatMap.get(imageFormat);
          a.click();
        });
      } else {
        const a = document.createElement("a");
        a.href = src;
        a.target = "_blank";
        a.download = src + "." + imageFormatMap.get(imageFormat);
        a.click();
      }
    };
    onUnmounted(() => {
      (document == null ? void 0 : document.removeEventListener) && (document == null ? void 0 : document.removeEventListener("keydown", handleEsc));
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        class: normalizeClass(["image-previewer", [unref(isMobile) && "image-previewer-h5"]])
      }, [
        createElementVNode("div", {
          ref_key: "image",
          ref: image,
          class: "image-wrapper",
          onTouchstart: withModifiers(handleTouchStart, ["stop"]),
          onTouchmove: withModifiers(handleTouchMove, ["stop"]),
          onTouchend: withModifiers(handleTouchEnd, ["stop"]),
          onTouchcancel: withModifiers(handleTouchCancel, ["stop"]),
          onWheel: withModifiers(handleWheel, ["stop"])
        }, [
          createElementVNode("ul", {
            ref_key: "ulRef",
            ref: ulRef,
            class: "image-list",
            style: normalizeStyle({
              width: `${_ctx.imageList.length * 100}%`,
              transform: `translateX(-${unref(currentImageIndex) * 100 / _ctx.imageList.length}%)`,
              transition: "0.5s"
            })
          }, [
            (openBlock(true), createElementBlock(Fragment, null, renderList(_ctx.imageList, (item, index) => {
              return openBlock(), createElementBlock("li", {
                key: index,
                class: "image-item"
              }, [
                createVNode(_sfc_main$1, {
                  zoom: unref(zoom),
                  rotate: unref(rotate),
                  src: getImageUrl(item),
                  messageItem: item,
                  class: normalizeClass([unref(isUniFrameWork) ? "image-item" : ""])
                }, null, 8, ["zoom", "rotate", "src", "messageItem", "class"])
              ]);
            }), 128))
          ], 4)
        ], 544),
        withDirectives(createElementVNode("div", {
          class: "icon icon-close",
          onClick: close
        }, [
          createVNode(Icon, {
            file: unref(closeIcon),
            width: "16px",
            height: "16px"
          }, null, 8, ["file"])
        ], 512), [
          [vShow, unref(isPC)]
        ]),
        unref(isPC) && unref(currentImageIndex) > 0 ? (openBlock(), createElementBlock("div", {
          key: 0,
          class: "image-button image-button-left",
          onClick: goPrev
        }, [
          createVNode(Icon, { file: unref(iconArrowLeft) }, null, 8, ["file"])
        ])) : createCommentVNode("", true),
        unref(isPC) && unref(currentImageIndex) < _ctx.imageList.length - 1 ? (openBlock(), createElementBlock("div", {
          key: 1,
          class: "image-button image-button-right",
          onClick: goNext
        }, [
          createVNode(Icon, { file: unref(iconArrowLeft) }, null, 8, ["file"])
        ])) : createCommentVNode("", true),
        createElementVNode("div", {
          class: normalizeClass(["actions-bar", unref(isMobile) && "actions-bar-h5"])
        }, [
          unref(isPC) ? (openBlock(), createElementBlock("div", {
            key: 0,
            class: "icon-zoom-in",
            onClick: zoomIn
          }, [
            createVNode(Icon, {
              file: unref(iconZoomIn),
              width: "27px",
              height: "27px"
            }, null, 8, ["file"])
          ])) : createCommentVNode("", true),
          unref(isPC) ? (openBlock(), createElementBlock("div", {
            key: 1,
            class: "icon-zoom-out",
            onClick: zoomOut
          }, [
            createVNode(Icon, {
              file: unref(iconZoomOut),
              width: "27px",
              height: "27px"
            }, null, 8, ["file"])
          ])) : createCommentVNode("", true),
          unref(isPC) ? (openBlock(), createElementBlock("div", {
            key: 2,
            class: "icon-refresh-left",
            onClick: rotateLeft
          }, [
            createVNode(Icon, {
              file: unref(iconRotateLeft),
              width: "27px",
              height: "27px"
            }, null, 8, ["file"])
          ])) : createCommentVNode("", true),
          unref(isPC) ? (openBlock(), createElementBlock("div", {
            key: 3,
            class: "icon-refresh-right",
            onClick: rotateRight
          }, [
            createVNode(Icon, {
              file: unref(iconRotateRight),
              width: "27px",
              height: "27px"
            }, null, 8, ["file"])
          ])) : createCommentVNode("", true),
          createElementVNode("span", _hoisted_1, toDisplayString(unref(currentImageIndex) + 1) + " / " + toDisplayString(_ctx.imageList.length), 1)
        ], 2),
        createElementVNode("div", {
          class: "save",
          onClick: withModifiers(save, ["stop", "prevent"])
        }, [
          createVNode(Icon, {
            file: unref(iconDownload),
            width: "20px",
            height: "20px"
          }, null, 8, ["file"])
        ])
      ], 2);
    };
  }
});
export {
  _sfc_main as default
};
