<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">
            <viewimg :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>
                <li>
                  <span>規格：</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>數量：</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">僅供線下門店購買</span>
               <template  v-else>
                <div @click.stop="viewDetail(i)">查看詳情</div>
                <div @click.stop="addCart(i)">加入購物車</div>
              </template>
            </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";

// get_product_info
const store = useStore();

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

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

const current = ref(0);

const viewDetail = (item) => {
  apis.burying_point({ type: 3 });
  browser.openLink(
  `/pages/item/item?productId=${item.id}`, 
  `https://m.cdfmembers.com/shop/600667208/item?productId=${item.id}`,
  `/pages/item/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,
  });
};

const addCart = async (item) => {
  Loading.show();

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

  Loading.hide();
  if (result.code === 0) {
    apis.burying_point({ type: 7, productId: item.id});
    return Dialog.toast({ content: `添加成功`, 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)}`,
      `https://m.cdfmembers.com/shop/600667208/h5login?redirectUrl=${encodeURIComponent(callbackUrl)}`,
      `/pages/login/login?callbackHttpUrl=${encodeURIComponent(callbackUrl)}`
    );
  }
};

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

const updateProductsById = async (idx) => {
  if (!tagclick.value.data.products[idx]) {
    Dialog.toast({ content: `获取商品详情失败，请稍后再试`, type: "error" });
    close();
    return;
  }
  Loading.show();
  let res = await apis.get_product_info({
    // productId: 'p15677829'
    productId: tagclick.value.data.products[idx].id,
  });

  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();
};

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

const brandScroll = () => {
  nextTick(() => {
    let t = setTimeout(() => {
      clearTimeout(t);
      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() {
            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;
        background: #fff;
        padding-bottom: 14px;

        .info {
          font-size: 14px;
          color: #131d34;
          padding: 16px 20px;
          > 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 {
          display: flex;
          justify-content: space-between;
          font-size: 16px;
          padding: 0 20px;

          > 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>
