<template>
  <div
    style="max-width: 800px"
    v-bind:style="{
      display: success ? 'inherit' : 'none',
      margin: isPCDevice ? '0 auto' : '',
    }"
  >
    <a v-if="success" v-bind:href="link">
      <div v-if="type === 'video'">
        <video
          loop
          autoplay
          muted
          width="100%"
          max-width="800px"
          height="auto"
          playsinline
        >
          <source v-bind:src="srcUrl" width="100%" height="100%" />
        </video>
      </div>
      <div v-if="type === 'image'">
        <img width="100%" height="auto" v-bind:src="srcUrl" />
      </div>
    </a>
  </div>
</template>

<script>
import axios from "axios";
import { BASE_URL } from "../shared";

export default {
  name: "nsDealAd",
  props: {
    cateCd: String,
    isMobileDevice: Boolean,
    isApp: Boolean,
  },
  data() {
    return {
      success: false,
      type: "",
      srcUrl: "",
      link: "",
    };
  },
  created: function () {
    this.loadData();
  },
  computed: {
    isPCDevice: () => {
      return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent)
        ? false
        : true;
    },
  },
  methods: {
    async loadData() {
      try {
        this.loading = true;
        const res = await axios.get(
          BASE_URL +
            "/ns_api/v1/banners?type=advertise&postLocation=storeDetail&cateCd=" +
            this.cateCd
        );
        if (res.data && res.data.length > 0) {
          const data = res.data[0];
          this.link = data.link;
          this.success = true;

          // 모바일 또는 앱 + video 우선 + videoUrl이 있을 때
          if (
            (this.isMobileDevice || this.isApp) &&
            data.videoFirst &&
            data.videoUrl
          ) {
            this.type = "video";
            this.srcUrl = data.videoUrl;
            return;
          }
          // 모바일 또는 앱 + image 우선
          if (
            (this.isMobileDevice || this.isApp) &&
            (data.videoFirst === undefined || !data.videoFirst) &&
            data.mImageUrl
          ) {
            this.type = "image";
            this.srcUrl = data.mImageUrl;
            return;
          }
          // pc + image만 보여주기 (비디오 X)
          if (!this.isMobileDevice && data.pcImageUrl) {
            this.type = "image";
            this.srcUrl = data.pcImageUrl;
            return;
          }

          // 여기까지 오면 위 해당사항이 없으므로 보여주지 않기
          this.success = false;
        } else {
          this.success = false;
        }
      } catch (e) {
        this.success = false;
        console.log(e);
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style></style>
