<template>
  <t-dialog
    v-model:visible="props.visible"
    :title="props.title"
    :footer="false"
    :width="520"
    @close="close"
  >
    <div class="shareModal">
      <div class="item" v-if="shareFlag">
        <t-radio-group v-model:value="isShare" @change="onChange">
          <t-radio :value="true"> {{$t('分享公开')}} </t-radio>
          <t-radio :value="false"> {{$t('不分享')}} </t-radio>
        </t-radio-group>
      </div>
      <div class="item">
        <t-input v-model:value="link" :readonly="true"></t-input>
        <t-button @click="onSearch">{{$t('复制链接')}}</t-button>
      </div>
      <div class="desc">{{$t('分享到')}}</div>
      <t-loading :loading="loading">
        <div class="code-box flex">
          <div class="code flex-1">
            <img class="code-img" :src="qr">
            <p class="subdesc">{{$t('扫一扫')}}</p>
          </div>
          <div class="code flex-1">
            <img class="code-img" ref="codeImg">
            <p class="subdesc">{{$t('微信扫一扫')}}</p>
          </div>
          <div class="remark">
            {{$t('分享私有图纸请确保小程序登录的账号与')}}PC{{$t('端一致')}}，{{$t('或者将私有图纸设置为分享公开')}}，{{$t('才可以正常扫码预览')}}。
          </div>
        </div>
      </t-loading>
    </div>
  </t-dialog>
</template>

<script lang="ts" setup>
import { defineComponent, nextTick, ref, computed, watch, getCurrentInstance } from "vue";
import QRCode from "qrcode";
import { useRoute } from "vue-router";
import { MessagePlugin } from "tdesign-vue-next";
import axios from "@/http";
import { Meta2dBackData } from "@/services/utils";
import { useUser } from "@/services/user";
import { rootDomain } from "@/services/defaults";
const { proxy } = getCurrentInstance();
const $t = proxy.$t
const props = defineProps<{
  visible: boolean;
  shared: boolean;
  title?: string;
}>();
const emit = defineEmits(["update:visible", "change"]);
const link = ref("");
const isShare = ref(false);
const loading = ref(false);
const shareFlag = ref(false);
const qr = ref("#");
// const wxImg = ref<string>('');
const route = useRoute();
const codeImg = ref<any>();
const { user } = useUser();
function close() {
  emit("update:visible", false);
}
function onChange(e) {
  share(e);
}
function onSearch() {
  copy2clipboard(link.value);
  MessagePlugin.success($t("复制链接成功！"));
}
function copy2clipboard(copyText: string) {
  //1 手动创建可编辑元素，比如textarea，
  var textArea = document.createElement("textarea");
  //2 然后将要拷贝的值设置为它的Value
  textArea.value = copyText;
  //将textarea插入页面
  document.body.appendChild(textArea);
  //调用textarea的 select() 方法将值选中
  textArea.select();
  // 3 textarea要设置样式为不可见(使用样式将其移出可视区域即可)
  textArea.style.position = "fixed";
  textArea.style.top = "-9999px";
  textArea.style.left = "-9999px";
  // 4 调用document.execCommand('copy')
  document.execCommand("copy"); // 复制
  // document.execCommand('cut')// 剪切
  textArea.remove();
}

//TODO 配置shared无用，图纸不能根据用户id查找
async function share(shared: boolean) {
  const id = route.query.id;
  if (!id) {
    // 提示需要先保存
    MessagePlugin.warning($t("请先保存！"));
    return;
  }
  const res: any = await axios.post(`/api/data/v/update`, {
    _id: id,
    id: id,
    shared,
  });
  if (res.error) {
    return;
  }
  MessagePlugin.success(shared ? $t("分享成功！") : $t("取消分享成功"));
}
async function getQRcode(url: string) {
  const q: any = await QRCode.toDataURL(url, { margin: 0 });
  qr.value = q;
}
//TODO 小程序码接口
async function getWXCode(id: string) {
  const res: any = await axios.get("/api/account/miniprogram/code", {
    params: { id },
    responseType: "blob",
  });
  codeImg.value.src = URL.createObjectURL(res); // 将生成的blob对象的值赋值给img的src属性
  codeImg.value.onLoad = () => {
    URL.revokeObjectURL(codeImg.value.src); // 在图片加载完成后释放
  };
}

watch(
  () => props.visible,
  (newV) => {
    if (newV) {
      const id = route.query.id;
      const url = `https://view${rootDomain}/v/?id=${id}`;
      link.value = url;
      const data: Meta2dBackData = meta2d.data();
      // 只有图纸的拥有者才有分享和取消分享的曲线
      shareFlag.value = (data as any).ownerId === user.id;
      nextTick(async () => {
        loading.value = true;
        isShare.value = props.shared;
        try {
          await getQRcode(url);
        } catch (error) {
          MessagePlugin.warning($t("获取二维码失败！"));
        }
        try {
          await getWXCode((id as string).split("-").join(""));
        } catch (error) {
          MessagePlugin.warning($t("获取微信小程序码失败！"));
          loading.value = false;
        }
        loading.value = false;
      });
    }
  }
);
</script>

<style lang="postcss" scoped>
/* .ant-modal-wrap{
  z-index: 9999 !important;
} */
.shareModal {
  .item {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
  }
  .desc {
    line-height: 36px;
    margin-bottom: 4px;
    color: #fff;
  }
  .code-box {
    display: flex;
    justify-content: space-between;
    color: #fff;
    .code {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      .code-img {
        width: 120px;
        height: 120px;
        margin-bottom: 8px;
      }
      .subdesc{
        text-align: center;
      }
    }
    .remark{
      width: 26%;
      font-size: 14px;
      text-align: center;
    }
  }
}
</style>
