<template>
  <Popup ref="popRef" mode="center" closeOnClickOverlay>
    <template #content>
      <view class="content">
        <image
          :src="coupon.picture"
          class="img"
          mode="widthFix"
          v-if="coupon.picture"
          @click="drawCoupon"
        >
        </image>
      </view>
    </template>
    <template #footer>
      <view class="close" @click="close">
        <image
          class="icon-font"
          mode="widthFix"
          src="/static/home/close.png"
        ></image>
      </view>
    </template>
  </Popup>
</template>

<script setup>
import { ref, watch, computed, nextTick } from "vue";
import Popup from "@/components/popup.vue";
import { t } from "@/locale";
import { useSystemStore } from "@/store";
import { SHOP_GET_COUPON } from "@/api";
import { Toast, TimeOut } from "@/utils";

const useSystem = useSystemStore();
const coupon = computed(() => useSystem.getCoupon);
const props = defineProps({
  coponData: {
    type: Object,
  },
});
const popRef = ref(null);

const emit = defineEmits(["open", "close"]);

const open = () => {
  popRef.value && popRef.value.open();
};

const close = () => {
  popRef.value && popRef.value.close();
  emit("close");
};

const drawCoupon = async () => {
  if (!coupon.value.id) return;
  try {
    const res = await SHOP_GET_COUPON(coupon.value.id);
    Toast(res.msg).then(() => {
      TimeOut(() => {
        close();
        useSystem.setCoupon();
        uni.navigateTo({ url: "/pages/user/coupon" });
      });
    });
  } catch (error) {
    Toast(error.msg);
  }
};

watch(
  () => coupon.value?.show,
  (val) => {
    if (val) {
      nextTick(() => {
        open();
      });
    } else {
      close();
    }
  },
  {
    immediate: true,
  }
);

defineExpose({ open, close });
</script>

<style lang="less" scoped>
@import url("@/style.less");

:deep(.conts) {
  width: 600rpx;
  padding: 0 !important;
}

:deep(.u-popup__content) {
  background-color: transparent !important;
}

:deep(.footer) {
  padding: 0 !important;
}

.content {
  width: 100%;

  .img {
    width: 100%;
    height: auto;
    display: block;
  }
}

.close {
  .flex_center();
  height: 76rpx;
  width: 100%;
  background-color: transparent;

  .icon-font {
    width: 46rpx;
    height: 46rpx;
  }
}
</style>