<template>
  <div class="sign-box">
    <img class="sign-result-img" :src="valueData" v-if="valueData" />
    <t-popup
      v-if="!valueData && !disabled"
      trigger="click"
      :onVisibleChange="visibleChange"
    >
      <template #triggerElement>
        <t-button>添加签名</t-button>
      </template>
      <template #content>
        <vue-qrcode
          :value="createQrcodeValue"
          :options="{ width: 200 }"
        ></vue-qrcode>
      </template>
    </t-popup>
  </div>
</template>

<script setup name="SIGN">
import { computed, onMounted, ref, watch, onBeforeUnmount } from 'vue';
import VueQrcode from '@chenfengyuan/vue-qrcode';
import { useUserStore } from '@/store';
import { useIntervalFn } from '@vueuse/core';
import { getAttachmentListByKey } from '@/api/user';
const key = ref('');

const userStore = useUserStore();
const props = defineProps({
  config: { type: Object },
  modelValue: { type: String },
});
const emit = defineEmits(['update:modelValue', 'change']);
const disabled = computed(() => {
  return !props.config?.writable;
});

const valueData = ref('');
const getSignResultImg = () => {
  getAttachmentListByKey(key.value).then((res) => {
    //先用体验版的测试扫码链接，只能写死传'1'，后期小程序发正式版本再增加支持活的参数
    // getAttachmentListByKey('1').then((res) => {
    if (Array.isArray(res)) {
      if (res && res[0]?.url) {
        valueData.value = res[res.length - 1].url;
        emitChange();
        pause();
      }
    }
  });
};
const { pause, resume, isActive } = useIntervalFn(
  () => {
    getSignResultImg();
  },
  5000,
  { immediate: false }
);
onBeforeUnmount(() => {
  pause();
});
onMounted(() => {
  key.value =
    location.host === 'sop.qmth.com.cn'
      ? userStore.user?.id + '_' + new Date().getTime()
      : '1';
  valueData.value = props.modelValue;
});
const emitChange = () => {
  emit('update:modelValue', valueData.value);
  emit('change', valueData.value);
};
watch(
  () => props.modelValue,
  (val, oldval) => {
    valueData.value = val;
  },
  {
    immediate: true,
  }
);
const visibleChange = (visible) => {
  console.log('vvv', visible);
  if (visible) {
    resume();
  } else {
    // pause();
  }
};
const createQrcodeValue = computed(() => {
  //先用体验版的测试扫码链接，只能写死，后期小程序发正式版本再增加支持活的参数
  return 'https://sopwxapp.qmth.com.cn/sign/?key=' + key.value;
});
</script>

<style lang="less" scoped>
.sign-box {
  .sign-result-img {
    height: 100px;
  }
}
</style>
