<template>
  <div class="wrap">
    <view class="save-btn" @click="createCanvas"> 点击保存 </view>
    <!-- 简图轮播 -->
    <div class="swiper">
      <swiper
        duration="100"
        :current="current"
        :indicator-dots="false"
        :autoplay="false"
        :interval="3000"
        :duration="1000"
        @change="swiperChange"
      >
        <!--  -->
        <swiper-item
          v-for="(item, index) in list"
          :key="index"
          :style="{
            padding: `calc((100vh - ${swiper_height}px - 60px) / 2) 0`,
            display: 'flex',
            justifyContent: 'center',
          }"
        >
          <view class="swiper-item" :id="'swiper-item' + index">
            <view
              class="title-box"
              :style="
                meun_info.jt_bg1
                  ? { background: `url(${BASE_URL + meun_info.jt_bg1})` }
                  : ''
              "
            >
              <limeQrcodeVue
                v-if="item.id"
                size="112rpx"
                ref="qrcodeRef"
                :value="
                  BASE_URL1 +
                  `/h5/#/pages/deal/product_info?id=${item.id}&rand_num=${item.rand_num}`
                "
              ></limeQrcodeVue>
              <view class="title">
                <p>{{ item.title1 }}</p>
                <p>{{ item.title2 }}</p>
                <p class="warn">{{ item.title3 }}</p>
              </view>
            </view>
            <view
              class="content"
              v-if="item.detail"
              :style="
                meun_info.jt_bg2
                  ? { background: 'url(' + BASE_URL + meun_info.jt_bg2 + ')' }
                  : ''
              "
            >
              <u-parse :content="item.detail"></u-parse>
              <view
                class="watermark"
                v-if="
                  item.watermark_info &&
                  (item.watermark_info.type == 1 ||
                    item.watermark_info.type == 3)
                "
              >
                <image
                  v-if="
                    item.watermark_info.image && item.watermark_info.type == 1
                  "
                  v-for="i in 100"
                  :style="item.style"
                  :src="BASE_URL + item.watermark_info.image"
                ></image>
                <text
                  v-if="
                    item.watermark_info.water_text &&
                    item.watermark_info.type == 3
                  "
                  v-for="i in 100"
                  :style="item.style"
                  >{{ item.watermark_info.water_text }}</text
                >
              </view>
              <view
                class="watermark-position"
                v-if="
                  item.watermark_info &&
                  (item.watermark_info.type == 2 ||
                    item.watermark_info.type == 4)
                "
                :style="item.style_position"
              >
                <image
                  v-if="
                    item.watermark_info.image && item.watermark_info.type == 2
                  "
                  :style="item.style"
                  :src="BASE_URL + item.watermark_info.image"
                ></image>
                <text
                  v-if="
                    item.watermark_info.water_text &&
                    item.watermark_info.type == 4
                  "
                  :style="item.style"
                  >{{ item.watermark_info.water_text }}
                </text>
              </view>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </div>

    <!-- 简图 -->
    <u-overlay :show="popup_diagram" @click="popup_diagram = false">
      <view class="window">
        <view class="diagram" @tap.stop>
          <image :src="diagram_url" mode="widthFix"></image>
          <!-- <p @touchstart.prevent="touchstart" @touchend.prevent="touchend">
            长按保存到本地
          </p> -->
          <p @click="popup_diagram = false">长按保存到本地</p>
        </view>
      </view>
    </u-overlay>

    <!-- 操作提示 -->
    <u-overlay :show="popup_tips" @click="popup_tips = false">
      <view class="window">
        <view class="tips">
          <image src="@/static/swiper1.png" mode=""></image>
          <p style="color: #fff">{{ tips_value }}</p>
        </view>
      </view>
    </u-overlay>

    <!-- 收藏 -->
    <u-overlay :show="popup_collect" @click="popup_collect = false">
      <view class="window">
        <view class="collect" @tap.stop>
          <image src="@/static/warn.png" mode=""></image>
          <p>{{ collect_value }}</p>
          <u-button
            color="#A5CF49"
            type="success"
            shape="circle"
            text="确认收藏"
            @click="addFavorite"
          ></u-button>
        </view>
      </view>
    </u-overlay>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { onLoad, onShow, onPullDownRefresh, onReady } from "@dcloudio/uni-app";
import { BASE_URL, BASE_URL1 } from "@/utils/http.js";
import {
  getsimpleimages,
  getplatformeditor,
  getplatformmeun,
} from "@/utils/api.js";
import limeQrcodeVue from "@/uni_modules/lime-qrcode/components/l-qrcode/l-qrcode.vue";
// import domtoimage from "dom-to-image";
import domtoimage from "@/components/dom-to-image.js";
const current = ref(0), // 当前选中项
  form = ref({ page: 1, page_num: 12 }), // 请求列表数据form
  list = ref([]), // 列表数据
  meun_info = ref({}), // tabbar等信息
  popup_diagram = ref(false), // 简图弹窗
  popup_tips = ref(false), // 操作提示弹窗
  tips_value = ref(""), // 操作提示弹窗内容
  popup_collect = ref(false), // 收藏弹窗
  collect_value = ref(""), // 收藏弹窗内容
  swiper_height = ref(67), // 轮播高度
  loop = ref(() => {}), // 长按延时事件
  diagram_url = ref(""); // 简图地址

// 切换轮播图
function swiperChange(index) {
  const current_index = index.detail.current;
  current_index == list.value.length - 3 ? getData("getsimpleimages") : "";
  current.value = current_index;
  setTimeout(() => {
    computeSwiperHeight();
  });
}

// 计算轮播高度
function computeSwiperHeight() {
  let dom = document.getElementById("swiper-item" + current.value); // 获取dom元素
  if (dom && dom.children[1]) {
    swiper_height.value = 67 + dom.children[1].clientHeight;
  } else {
    swiper_height.value = 67;
  }
}

// 生成简图图片---domtoimage截图
function createCanvas() {
  let dom = document.getElementById("swiper-item" + current.value),
    item = list.value[current.value]; // 获取dom元素

  if (item.diagram_url) {
    diagram_url.value = item.diagram_url;
    popup_diagram.value = true;
    return;
  }
  const width = dom.clientWidth;
  domtoimage
    .toPng(dom, {
      bgcolor: "#fff",
      cacheBust: true,
      width: width,
      height: swiper_height.value,
      scale: 4,
      filter: (el) => {
        if (el.contains(dom) || dom.contains(el)) {
          return true;
        }
        return false;
      },
    })
    .then(function (dataUrl) {
      diagram_url.value = dataUrl.replace("image/png", "image/octet-stream");
      item.diagram_url = diagram_url.value;
      popup_diagram.value = true;
    });
}

// 长按开始
function touchstart() {
  clearTimeout(loop.value);
  setTimeout(() => {
    saveImage();
  }, 600);
}

// 长按结束
function touchend() {
  clearTimeout(loop.value);
}

// 保存图片
function saveImage() {
  let blob = new Blob([""], { type: "application/octet-stream" });
  let url = URL.createObjectURL(blob);
  let a = document.createElement("a");
  a.href = diagram_url.value;
  // a.download = diagram_url.value
  //   .replace(/(.*\/)*([^.]+.*)/gi, "$2")
  //   .split("?")[0];
  a.download = "斑马简图.png";
  let e = document.createEvent("MouseEvents");
  e.initMouseEvent("click", true);
  a.dispatchEvent(e);
  URL.revokeObjectURL(url);
}

// 收藏本站
let addFavorite = () => {
  var url = window.location;
  var title = "斑马交易平台";
  var ua = navigator.userAgent.toLowerCase();
  if (ua.indexOf("360se") > -1) {
    alert("您的浏览器不支持自动加入收藏，请手动设置！");
  } else if (ua.indexOf("msie 8") > -1) {
    window.external.AddToFavoritesBar(url, title); //IE8
  } else if (document.all) {
    //IE类浏览器
    try {
      window.external.addFavorite(url, title);
    } catch (e) {
      alert("您的浏览器不支持自动加入收藏，请手动设置！");
    }
  } else if (window.sidebar) {
    //firfox等浏览器；
    window.sidebar.addPanel(title, url, "");
  } else {
    alert("您的浏览器不支持自动加入收藏，请手动设置！");
  }
  popup_collect.value = false;
};

// 获取数据
function getData(url) {
  switch (url) {
    case "getplatformeditor": // 获取平台信息
      getplatformeditor().then(({ data }) => {
        collect_value.value = data.alert1;
        tips_value.value = data.alert2;
      });
      break;
    case "getplatformmeun": // 获取tabbar等信息
      getplatformmeun().then(({ data }) => {
        uni.setNavigationBarTitle({
          title: data.name,
        });
        meun_info.value = data;
      });
      break;
    case "getsimpleimages": // 获取列表数据
      getsimpleimages(form.value).then(({ data }) => {
        data.forEach((item) => {
          let { watermark_info } = item,
            family_arr = [
              "fangsong",
              "Helvetica",
              "Arial",
              "Tahoma",
              "Microsoft YaHei",
              "SimSun",
            ];
          item.style = {
            opacity: (100 - watermark_info.opacity * 1) * 0.01,
            color: watermark_info.color,
            fontSize: watermark_info.text_font + "px",
            fontWeight: watermark_info.bold == 1 ? "bold" : "",
            // fontFamily: `typeface${watermark_info.typeface}`,
            fontFamily: family_arr[watermark_info.typeface - 1],
            transform: `rotate(${watermark_info.angle}deg)`,
          };
          item.style_position = {
            top: watermark_info.yy + "px",
            left: watermark_info.xx + "px",
          };
          if (watermark_info.type == "4") {
            item.style_position.height = item.style.lineHeight =
              item.style.fontSize;
          }
        });
        if (form.value.page == 1) {
          list.value = data;
          popup_tips.value = true;
          setTimeout(() => {
            popup_tips.value = false;
          }, 5000);
        } else {
          list.value = [...list.value, ...data];
        }
        form.value.page++;
        setTimeout(() => {
          computeSwiperHeight();
        });
      });
      break;
  }
}

onLoad(() => {
  getData("getplatformeditor");
  getData("getplatformmeun");
  getData("getsimpleimages");
});
onReady(() => {
  let flag = uni.getStorageSync("collect");
  if (!flag) {
    popup_collect.value = true;
    uni.setStorageSync("collect", true);
  }
});
</script>

<style lang="scss" scoped>
.wrap {
  .save-btn {
    font-size: 35rpx;
    color: #fff;
    text-align: center;
    line-height: 90rpx;
    float: right;
    width: 200rpx;
    height: 90rpx;
    background: #a5cf49;
    border-radius: 0rpx 0rpx 0rpx 32rpx;
    position: fixed;
    right: 0;
    top: 0;
    z-index: 1000;
  }
  .swiper {
    // width: 694rpx;
    // position: fixed;
    // top: 50%;
    // left: 50%;
    // transform: translate(-50%, -50%);
    > :first-child {
      height: 100vh;
      // width: 100vw;
      display: flex;
      align-items: center;
    }
    .swiper-item {
      max-width: 60vh;
      .title-box {
        font-size: 28rpx;
        color: #666666;
        padding: 6rpx;
        // background: #fff5e5;
        display: flex;
        align-items: flex-end;

        image {
          margin-right: 4rpx;
          width: 112rpx;
          height: 112rpx;
        }

        .warn {
          font-size: 32rpx;
          color: #ff2828;
        }
        .title {
          margin-left: 4rpx;
        }
      }
      .content {
        padding-left: 10rpx;
        padding-right: 10rpx;
        overflow: hidden;
        position: relative;
        word-break: break-all;
        word-wrap: break-word;
        overflow: hidden;
        position: relative;

        .watermark {
          position: absolute;
          display: flex;
          flex-wrap: wrap;
          top: 0;
          left: 0;
          right: 0;
          image {
            width: 100rpx;
            height: 100rpx;
          }
        }
        .watermark-position {
          position: absolute;
          display: flex;
          image {
            width: 100rpx;
            height: 100rpx;
          }
        }
        text {
          white-space: nowrap;
        }
      }
    }
  }
  .window {
    padding: 0 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    .diagram {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 694px;
      height: auto;

      image {
        width: 100%;
      }

      p {
        font-size: 48rpx;
        color: #fff;
        margin-top: 12rpx;
        width: 100%;
        text-align: center;
      }
    }
    .tips {
      display: flex;
      flex-direction: column;
      align-items: center;

      image {
        width: 374rpx;
        height: 361rpx;
      }
      @keyframes example1 {
        0% {
          transform: translate(0);
        }

        50% {
          transform: translate(-40px);
        }

        100% {
          transform: translate(-80px);
        }

        0% {
          transform: translate(0);
        }
      }

      transform: translate(0);
      animation: example1 1s linear 0s backwards;
      animation-iteration-count: infinite;
    }
    .collect {
      padding: 60rpx 60rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 558rpx;
      // height: 438rpx;
      background: #ffffff;
      border-radius: 20rpx;

      image {
        max-width: 96rpx;
        max-height: 96rpx;
      }

      p {
        font-size: 30rpx;
        margin: 62rpx 0 40rpx;
      }

      // background-color: #fff;
    }
  }
}
</style>
