<template>
  <div class="max-w1280">
    <div class="layer cart-wrap" :class="{'noCon':(user.cartGroup.length<1 && user.cartEnd)}"  v-loading="loading">
      <ul class="product-ul" v-if="user.cartGroup?.length>0">
        <li class="product-li" v-for="(item,idx) in user.cartGroup" :id="`item-idx`" :key="idx">
          <div class="check-wrap" @click="updateCartSelectFun(item,idx)">
            <i :class="{check:item.selected==1}"></i>
          </div>
          <NuxtLink :to="{path:`/product`,query:{code:item.goodsId}}">
            <div class="product-img">
              <NuxtImg :src="item.goodsImage" :loading="isClient ? 'lazy' : 'eager'" :placeholder="isClient ? '/img/loading.png' : undefined"></NuxtImg>
            </div>
            <div class="product-info">
              <h3 :title="item.goodsName" class="title">{{item.goodsName}}</h3>
              <p>品牌：{{item.brandName}}</p>
              <p>编号：{{item.customerSn}}</p>
              <p>数量：{{ item.goodsNum }}</p>
              <p class="price"><span class="mainColor">¥{{item.priceNum}}</span></p>
            </div>
          </NuxtLink>
          <div class="opt">
            <i class="sc" @click="delFunDialog(item)"></i>
            <i class="edit" @click="editFun(item)"></i>
          </div>
        </li>
      </ul>
      <template v-if="user.cartGroup.length<1 && user.cartEnd">
        <el-empty description=" " image="https://www.hotking.com/img/cart_null.76bbf18b.png" :image-size="200">
          <div class="noContent">
            <p>购物车内暂时没有商品</p>
            <el-button class="btn_main mt20 linkProduct" type="primary" @click="link">继续逛逛</el-button>
          </div>
        </el-empty>
      </template>
    </div>

    <el-drawer title="" v-model="open.detail" size="auto" direction="btt" append-to-body class="detail-drawer" @close="open.detail = false" :with-header="false" :z-index="2000">
      <editCart :detailInfo="currentItem" @done="done"></editCart>
    </el-drawer>
    <div class="buy-btn-wrap" v-if="user.cartGroup.length>0">
      <div class="tips">
        <p>已选中&nbsp;<span class="mainColor">{{selectedCount}}</span>&nbsp;种商品</p>
        <p>共(未含运费)&nbsp;<span class="mainColor">¥{{allPrice}}</span></p>
      </div>
      <el-button class="btn_main" @click="createOrder">
        去结算
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Search } from "@element-plus/icons-vue";
import empty from "@/assets/img/empty.svg";
import { showLoadingToast, closeToast } from "vant";
let pageTitle: any = ref("HOTKING-购物车");
useHead(() => ({
  title: pageTitle.value,
}));
import { useAll } from "~/api/pubAll/service";
const { delCartGood, updateCart } = useAll();
let currentItem: any = ref({});
const user = useUserStore();
user.value.adminTitle = "购物车";
const open = ref({
  detail: false,
});
const nuxtApp = useNuxtApp();
const isClient = !nuxtApp.ssrContext;
let allPrice: any = ref(0);
let specifications = ref("");
const selectedCount = computed(() => {
  return user.value.cartGroup.filter((item: any) => item.selected == 1).length;
});
watch(
  () => user.value.cartGroup,
  (newVal: any, oldVal: any) => {
    let aa = user.value.cartGroup.filter((item: any) => item.selected == 1);
    allPrice.value = 0;
    aa.forEach((item: any) => {
      let pri = Number(getPrice(item.goodsNum, item));
      console.log(typeof pri);
      let xPrice = Number((pri * item.goodsNum).toFixed(6));
      console.log(typeof xPrice);
      allPrice.value = Number((allPrice.value + xPrice).toFixed(6));
    });
  },
  { immediate: true, deep: true }
);
let loading = ref(false);
onMounted(() => {
  loading.value = true
  user.value.cartUpdate += 1;
  setTimeout(() => {
    loading.value = false
  }, 1000);
});
function createOrder() {
  if (selectedCount.value > 0) {
    navigateTo({
      path: "/cart/order",
    });
  }else{
    ElMessage.success("您未选择任何产品！");
  }
}
function link() {
  navigateTo({
    path: "/search",
    query: {
      key: "",
      pageNum: 1,
      pageSize: 20,
    },
  });
}
function getPrice(b: any, item: any) {
  let a = item.priceTemplateArr;
  for (let i = 0; i < a.length; i++) {
    const min = i === 0 ? a[i].num : a[i].num; // 左区间从当前 num 开始
    const max = a[i + 1] ? a[i + 1].num : Infinity; // 右区间是下一个 num，如果没有就是 Infinity
    if (b >= min && b < max) {
      return a[i].price;
    }
  }
  return a[a.length - 1].price; // b 超过最大 num
}
let selectFalg = false;
async function updateCartSelectFun(item: any, idx: number) {
  const toast = showLoadingToast({
    message: "",
    forbidClick: true,
    duration: 0,
  });
  if (selectFalg) {
    return;
  }
  selectFalg = true;
  item.selected = item.selected == 1 ? 0 : 1;
  let q = { goodsId: item.goodsId, selected: item.selected, id: item.id };
  const res: any = await updateCart(q);
  selectFalg = false;
  toast.close();
  if (res.httpCode != 200) {
    user.value.cartGroup[idx] = item.selected == 1 ? 0 : 1;
  }
}

function editFun(item: any) {
  currentItem.value = item;
  open.value.detail = true;
}
function delFunDialog(item: any) {
  ElMessageBox.confirm("确认删除该商品？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(() => {
      delCartGoodFun(item);
    })
    .catch(() => {
      // catch error
    });
}
async function delCartGoodFun(item: any) {
  const toast = showLoadingToast({
    message: "",
    forbidClick: true,
    duration: 0,
  });
  const res: any = await delCartGood(item.goodsId);
  setTimeout(() => {
    toast.close();
  }, 1000);
  if (res.httpCode == 200) {
    user.value.cartUpdate += 1;
  }
}
function done() {
  cancel();
}
function cancel() {
  Object.keys(open.value).forEach(
    (key) => (open.value[key as keyof typeof open.value] = false)
  );
}
</script>
<style scoped lang="scss">
.max-w1280 {
  background-color: #f7f7f7;
}
.cart-wrap {
  background: linear-gradient(180deg, #f7f7f7, #fff0 2.666667rem) !important;
  padding-top: 12px;
  min-height: calc(100vh - 44px - 54px);
  padding-bottom: 70px;
  &.noCon {
    background: #fff !important;
  }
  .product-ul {
    margin-left: 12px;
    margin-right: 12px;
    .product-img {
      min-width: 90px;
      width: 90px;
      height: 90px;
      img {
        border: 1px solid #f3f3f3;
        border-radius: 5px;
        height: 90px;
        width: 90px;
        min-width: 90px;
      }
    }
    .product-info {
      max-width: 175px;
      padding-top: 0;
      padding-bottom: 0;
      .title {
        font-size: 14px;
        line-height: 20px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      p {
        font-size: 12px;
        line-height: 16px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        &.price {
          margin-top: 2px;
        }
      }
    }
  }
  .product-li {
    padding-left: 36px;
    background: #fff;
    border-radius: 8px;
    position: relative;
    padding: 12px 12px 12px 36px;
    a {
      align-items: center;
      padding-left: 0;
    }
    .check-wrap {
      width: 36px;
      height: 100%;
      border-radius: 50%;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: auto;
      i {
        width: 16px;
        height: 16px;
        border: 1px solid #e8e8e8;
        border-radius: 50%;
        display: block;
        &.check {
          background: url(@/assets/img/icon/check.svg) no-repeat center center;
          background-size: 16px auto;
        }
      }
    }
  }
  .opt {
    display: flex;
    position: absolute;
    right: 0;
    flex-direction: column;
    top: 0;
    bottom: 0;
    margin: auto;
    height: max-content;
    width: 44px;
    z-index: 2;
    i {
      width: 44px;
      height: 40px;
      &.edit {
        background: url(@/assets/img/icon/edit.svg) no-repeat center center;
        background-size: 28px auto;
      }
      &.sc {
        background: url(@/assets/img/icon/del.svg) no-repeat center center;
        background-size: 20px auto;
      }
    }
  }
}
.linkProduct {
  border-radius: 25px !important;
  min-width: 120px;
}
.buy-btn-wrap {
  display: flex;
  position: fixed;
  bottom: 54px;
  background: #fff;
  width: 100%;
  height: 60px;
  align-items: center;
  justify-content: space-between;
  left: 0;
  padding: 0 15px;
  z-index: 1000;
  box-shadow: 0 0 18px rgba(0, 0, 0, 0.1);
  .tips {
    color: #666;
    &.mainColor {
      font-size: 16px;
    }
  }
  .btn_main {
    border-radius: 25px !important;
    flex: 1;
    margin-left: 20px;
    height: 42px !important;
    &.is-disabled {
      background: #e9e9e9;
      color: #fff;
    }
  }
}
</style>