<template>
  <transition mode="out-in" appear>
    <div class="goodlist" v-show="tagclick.type == 'goodlist'">
      <div class="head-pages">
        <div>
          <span>{{ current + 1 }}</span
          ><span>/{{ tagclick.data.products ? tagclick.data.products.length : "-" }}</span>
        </div>
        <ui-icon @click.stop="close" type="state_f"></ui-icon>
      </div>
      <div class="swiper-container" id="goodlist">
        <ul class="swiper-wrapper">
          <li class="swiper-slide" v-for="(i, index) in tagclick.data.products" :key="index">
            <div>
              <img v-if="isShowNewGoodType" :src="i.pic" alt="">
              <viewimg  v-else :list="i.pics" :keyid="`viewimg_${index + 1}`" />

              <div class="info">
                <p>{{ i.name }}</p>
                <div v-if="i.skus">
                  <span>{{ i.price[0].symbol }}</span
                  ><span>{{ i.currentSku.price }}</span>
                </div>
                <ul v-if="!isShowNewGoodType">
                  <li>
                    <span>{{$t('common.guige')}}</span>
                    <ul>
                      <li @click.stop="onClickSku(item)" :class="{ active: item.id == i.currentSku.id }" v-for="(item, idx) in i.skus" :key="idx">
                        <span v-if="item.properties[0]">
                          {{ item.properties[0].value }}
                        </span>
                      </li>
                    </ul>
                  </li>
                  <li>
                    <span>{{$t('common.shuliang')}}</span>
                    <div class="number">
                      <ui-icon
                        @click="
                          () => {
                            i.cartnum--;
                            i.cartnum = Math.max(i.cartnum, 0);
                          }
                        "
                        type="cad-neiqiang"
                      ></ui-icon>
                      <input maxlength="5" v-model="i.cartnum" type="number" />
                      <ui-icon
                        @click="
                          () => {
                            i.cartnum++;
                            i.cartnum = Math.min(i.cartnum, 9999);
                          }
                        "
                        type="add"
                      ></ui-icon>
                    </div>
                  </li>
                </ul>
              </div>
              <div class="goods-button">
                <span v-if="i.saleChannel == 1" class="tipss">{{$t('common.onlyOffLine')}}</span>
                <template v-else>
                  <div :style="{width:isShowNewGoodType?'100%':'48%'}" @click.stop="viewDetail(i)">{{$t('common.viewDetail')}}</div>
                  <div v-if="!isShowNewGoodType" @click.stop="addCart(i)">{{$t('common.addCart')}}</div>
                  <div v-if="i?.skuList?.length" @click.stop="onClickTryUse(i)">{{ $t('common.tryUse') }}</div>
                </template>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </transition>
</template>

<script setup>
import { onMounted, watch, toRaw, computed, defineEmits, ref, defineProps, nextTick } from "vue";
import { useApp, getApp } from "@/app";
import { useStore } from "vuex";
import * as apis from "@/apis/index.js";
import { Loading, Dialog } from "@/global_components/";
import browser from "@/utils/browser";
import viewimg from "@/views/viewimg";

import { useI18n, getLocale } from '@/i18n'
const { t } = useI18n({ useScope: 'global' })


// get_product_info
const store = useStore();
const isshoppingguide = computed(() => store.getters["shoppingguide"]);

const tagclick = computed(() => store.getters["tag/tagClickType"]);

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

const current = ref(0);

const mysw = ref(null);

const isShowNewGoodType = computed(()=>tagclick.value&&tagclick.value.data.productSource.mchType == 1);


const viewDetail = (item) => {
  if (isshoppingguide.value) {
    return;
  }
  apis.burying_point({ type: 3, productId: item.id });

  console.log(tagclick.value.data.productSource,'itemitemitem');

  if (tagclick.value.data.productSource.mchType == 1) {
    if (browser.detectIOS()) {
      window.location.href = item.url;
    } else {
      window.open(item.url, "_blank");
    }
  }else{
    browser.openLink(
      `/pages/item/item?productId=${item.id}`,
      `${tagclick.value.data.productSource.cdfHost}/shop/${tagclick.value.data.productSource.cdfMchId}/item?productId=${item.id}`,
      `/pages/item/item?productId=${item.id}`,
      `${tagclick.value.data.productSource.cdfHostPc}/item/${item.id}`
    );
    console.log(`${tagclick.value.data.productSource.cdfHost}/shop/${tagclick.value.data.productSource.cdfMchId}/item?productId=${item.id}`);
  }


};

const onClickSku = (item) => {
  let tempData = toRaw(tagclick.value.data);

  tempData.products[current.value] = {
    ...tempData.products[current.value],
    currentSku: { ...item },
  };

  store.commit("tag/setTagClickType", {
    type: tagclick.value.type,
    data: tempData,
  });
};

function onClickTryUse(productInfo) {
  const urlObj = new URL(productInfo.skuList[0].url)
  urlObj.searchParams.set('tagid', tagclick.value.data.sid)
  location.assign(urlObj.href)
}

const addCart = async (item) => {
  if (isshoppingguide.value) {
    return;
  }
  Loading.show();

  let result = await apis.inCat({
    AccessToken: browser.getURLParam("AccessToken"),
    skuId: item.currentSku.id,
    num: item.cartnum,
    rnd: Math.random(),
    productSourceId:tagclick.value.data.productSourceId
  });

  Loading.hide();
  if (result.code === 0) {
    apis.burying_point({ type: 7, productId: item.id });
    return Dialog.toast({ content: t('common.addSuccess'), type: "success" });
  } else {
    let callbackUrl = `${window.location.origin}${window.location.pathname}?m=${browser.getURLParam("m")}&${getApp().Camera.getPoseUrlParams()}`;

    if (!browser.hasURLParam("tagid")) {
      callbackUrl += `&tagid=${tagclick.value.data.sid}`;
    } else {
      callbackUrl = browser.replaceQueryString(callbackUrl, "tagid", tagclick.value.data.sid);
    }
    console.log(callbackUrl);
    //  Dialog.toast({ content: `登錄狀態失效，請重新登錄`, type: 'error' })
    browser.openLink(
      `/pages/login/login?callbackHttpUrl=${encodeURIComponent(callbackUrl)}`,
      `${tagclick.value.data.productSource.cdfHost}/shop/${tagclick.value.data.productSource.cdfMchId}/h5login?redirectUrl=${encodeURIComponent(callbackUrl)}`,
      `/pages/login/login?callbackHttpUrl=${encodeURIComponent(callbackUrl)}`
      `${tagclick.value.data.productSource.cdfHostPc}/login?redirectUrl=${encodeURIComponent(callbackUrl)}`,
    );
  }
};

const close = () => {
  emit("close");
};

const updateProductsById = async (idx) => {
  if (tagclick.value.data.productSource.mchType == 1) {
    return
  }
  if (!tagclick.value.data.products[idx]) {
    Dialog.toast({ content: t('common.viewDetailFail'), type: "error" });
    close();
    return;
  }
  Loading.show();
  console.log(tagclick.value,'tagclick.value.data');
  try {
    
    let res = await apis.get_product_info({
      // productId: 'p15677829'
      productId: tagclick.value.data.products[idx].id,
      productSourceId:tagclick.value.data.productSourceId
    });

    let tempData = toRaw(tagclick.value.data);

    tempData.products[idx] = {
      ...tempData.products[idx],
      ...res.data,
      currentSku: res.data.skus[0] || {
        price: "",
        id: "",
      },
      cartnum: 1,
    };

    store.commit("tag/setTagClickType", {
      type: tagclick.value.type,
      data: tempData,
    });
    Loading.hide();
  } catch (error) {
    Loading.hide();
  }
};

watch(
  () => tagclick.value.type,
  (val, old) => {
    if (mysw.value) {
      if (val === "goodlist") {
        current.value = 0;
        updateProductsById(current.value);
      }
      if (!val) {
        mysw.value.slideTo(0);
      }
    }
  }
);

const brandScroll = () => {
  nextTick(() => {
    let t = setTimeout(() => {
      clearTimeout(t);
      mysw.value = new Swiper("#goodlist", {
        effect: "coverflow",
        grabCursor: true,
        centeredSlides: true,
        slidesPerView: "auto",
        coverflowEffect: {
          rotate: 0,
          stretch: -40,
          depth: 100,
          modifier: 1,
          slideShadows: false,
        },
        on: {
          touchMove(swiper, e) {
            e.stopPropagation();
            e.preventDefault();
          },
          slideChange() {
            if (tagclick.value.type) {
              current.value = this.activeIndex;
              updateProductsById(current.value);
            }
          },
        },
      });
    }, 100);
  });
};

onMounted(() => {
  brandScroll();
});
</script>

<style lang="scss" scoped>
.goodlist {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: 0 auto;
  max-width: 500px;
  z-index: 101;
  background: rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  .head-pages {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    width: 76%;
    > div {
      span {
        font-size: 14px;
        &:last-of-type {
          color: rgba(255, 255, 255, 0.5);
        }
      }
    }
    > i {
      color: rgba(0, 0, 0, 1);
      font-size: 20px;
    }
  }
  #goodlist {
    width: 100%;
    overflow: hidden;
    padding-right: 2px;
    position: relative;
    > ul {
      > li {
        width: 76%;
        border-radius: 2px;
        position: relative;
        font-size: 0;
        overflow: hidden;

        > div {
          background: #fff;
          padding-bottom: 14px;
          height: 95%;
          display: flex;
          flex-direction: column;
          >.imgcon{
            flex: 0;
          }
          >img{
            width: 100%;
          }
          .info {
            font-size: 14px;
            color: #131d34;
            padding: 16px 20px;
            flex: 0 1 auto;
            overflow: auto;
            > p {
              font-size: 16px;
              width: 100%;
              line-height: 1.5;
              word-break: break-all;
            }
            > div {
              color: var(--editor-main-color);
              padding: 8px 0px 10px;
              border-bottom: 1px solid #ebebeb;
              > span {
                font-size: 16px;
                &:first-of-type {
                  font-size: 12px;
                  margin-right: 4px;
                }
              }
            }
            > ul {
              padding: 12px 0;
              border-bottom: 1px solid #ebebeb;

              > li {
                margin: 10px 0;
                color: #909090;
                &:last-of-type {
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                }
                > span {
                  font-size: 12px;
                }
                > ul {
                  display: block;
                  > li {
                    display: inline-block;
                    > span {
                      display: inline-block;
                      border: 1px solid #ebebeb;
                      padding: 2px 4px;
                      min-width: 73px;
                      height: 30px;
                      line-height: 30px;
                      margin: 8px 8px 0 0;
                      text-align: center;
                      border-radius: 4px;
                      font-size: 12px;
                    }
                    &.active {
                      > span {
                        border: solid 1px var(--editor-main-color);
                        color: var(--editor-main-color);
                      }
                    }
                  }
                }
                .number {
                  display: flex;
                  i {
                    font-size: 12px;
                    border: 1px solid #ebebeb;
                    padding: 2px 8px;
                    border-radius: 15px;
                  }
                  input {
                    max-width: 40px;
                    text-align: center;
                    color: #131d34;
                  }
                }
              }
            }
          }
          .goods-button {
            flex: 0;
            display: flex;
            justify-content: space-between;
            font-size: 16px;
            padding: 0 20px;
            gap: 10px;

            > div {
              height: 42px;
              background: #ff8e24;
              border-radius: 4px;
              width: 48%;
              text-align: center;
              line-height: 42px;
              &:last-of-type {
                background: var(--editor-main-color);
              }
            }
            .tipss {
              color: #909090;
              display: inline-block;
              margin: 0 auto;
            }
          }
        }
      }
    }
  }
}
</style>