<template>
  <u-popup
    v-model="props.show"
    mode="center"
    closeable
    border-radius="15"
    width="80%"
  >
    <view class="qrcode">
      <view class="title">班级二维码</view>
      <view class="image">
        <u-image
          width="100%"
          height="500rpx"
          :src="baseUrl + '/' + Url"
          ref="canvasRef"
        />
      </view>
    </view>
    <view class="footer">
      <u-button type="primary" size="medium" @tap="updateImage"
        >更新二维码</u-button
      >
      <!-- <u-button type="success" size="medium" @tap="saveImage"
        >保存二维码</u-button
      > -->
    </view>
  </u-popup>
</template>

<script setup lang="ts">
import { baseUrl } from "@/utils/request"
import { toast } from "@/utils/util"

const props = defineProps({
  show: Boolean,
  classId: Number,
  Url: String,
})

const emits = defineEmits(["init", "update:modelValue"])

const canvasRef = ref()

const updateImage = () => {
  uni.chooseImage({
    count: 1,
    success: (chooseImageRes) => {
      const tempFilePaths = chooseImageRes.tempFilePaths
      uni.uploadFile({
        url:
          baseUrl +
          "/LQKJ.K3.PeiXunSystem.WebApi.WebApiEditService.ClassImage,LQKJ.K3.PeiXunSystem.WebApi.common.kdsvc",
        filePath: tempFilePaths[0],
        name: "image",
        formData: {
          classId: props.classId,
        },
        success: ({ data }: any) => {
          const res = JSON.parse(data)
          if (res.code == 200) {
            emits("init")
            emits("update:modelValue", false)
            toast("更新成功")
          }
        },
      })
    },
  })
}

const saveImage = () => {
  downloadImage(baseUrl + "/" + props.Url)
  // downloadFile(baseUrl + "/" + props.Url, "image.jpg")
}

function downloadFile(fileURL: string, fileName: string) {
  fetch(fileURL)
    .then((response) => response.blob())
    .then((blob) => {
      const downloadUrl = URL.createObjectURL(blob)
      const link = document.createElement("a")
      link.href = downloadUrl
      link.download = fileName
      link.click()
      URL.revokeObjectURL(downloadUrl)
    })
}

function downloadImage(url: string) {
  const link = document.createElement("a")
  link.href = url
  link.download = "image.jpg"
  link.style.display = "none"

  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>

<style lang="scss" scoped>
:deep(.u-mode-center-box) {
  background-color: transparent;
}
.qrcode {
  padding: 24rpx;
  background-color: #fff;
  border-bottom-right-radius: 15rpx;
  border-bottom-left-radius: 15rpx;

  .title {
    font-size: larger;
    font-weight: bolder;
  }
  .image {
    padding: 46rpx;
  }
}
.footer {
  box-sizing: border-box;
  margin-top: 50rpx;
  background-color: #fff;
  border-top-left-radius: 10rpx;
  border-top-right-radius: 10rpx;
  padding: 20rpx;
  // display: flex;

  .u-btn {
    width: 100%;
  }
}
</style>
