<script setup lang="ts">
definePageMeta({
  layout: "login-default",
});
import { Events } from "~/dim/event";
const emit = defineEmits([Events.done]);
const props = defineProps<{ detailInfo: any }>();
import type { FormInstance } from "element-plus";
import { useLogin } from "~/api/login/loginService";
import type { SignupRequest } from "~/domain/Register";
import { showLoadingToast, closeToast } from "vant";
import { useAll } from "~/api/pubAll/service";
const { saveCart, updateCart } = useAll();
const signupRequest: Ref<SignupRequest> = ref({} as SignupRequest);
const user = useUserStore();
const route = useRoute();
let query: any = ref({});
watch(
  () => props?.detailInfo?.id,
  async (first: any, second: any) => {
    console.log(props.detailInfo)
    if (route.path == "/cart") {
      query.value = {
        customerSn: props.detailInfo.materialSn,
        goodsId: props.detailInfo.goodsId,
        goodsNum: props.detailInfo.goodsNum,
        id: props.detailInfo.id,
      };
    } else {
      query.value = {
        customerSn: props.detailInfo.materialSn,
        goodsId: props.detailInfo.id,
        goodsName:
          props.detailInfo.gn ||
          props.detailInfo.name ||
          props.detailInfo.goodsName,
        goodsNum: props.detailInfo.priceTemplateArr[0].num,
        goodsImage: props.detailInfo.goodsImg,
        goodsCategoryName: props.detailInfo.parentCategoryName,
        price: props.detailInfo.price,
        xPrice: 0,
        priceTemplate: props.detailInfo.priceTemplate,
        setUp: props.detailInfo.setUp,
        storeCount: props.detailInfo.storeCount,
        categoryId: props.detailInfo.categoryId,
        stepSample: props.detailInfo.stepSample,
        packCount: props.detailInfo.packCount,
        brandName: props.detailInfo.brandName,
        isSample: props.detailInfo.isSample,
      };
      query.value.xPrice = Number(
        (getPrice(query.value.goodsNum) * query.value.goodsNum).toFixed(6)
      );
    }
    console.log(query.value)
    changeNum();
  },
  { immediate: true, deep: true }
);

onMounted(async () => {});
function changeNum() {
  let pri = getPrice(query.value.goodsNum);
  query.value.xPrice = Number((pri * query.value.goodsNum).toFixed(6));
}
async function editCart() {
  const toast = showLoadingToast({
    message: "",
    forbidClick: true,
    zIndex: 3000,
    className: "my-custom-toast",
    duration: 0,
  });
  let res: any = await updateCart(query.value);
  toast.close();
  if (res.httpCode == 200) {
    user.value.cartUpdate += 1;
    emit(Events.done);
  }
}
async function addCart() {
  if (!user.value.isLogin) {
    return navigateTo({
      path: "/login",
      query: { redirect: route.fullPath },
    });
  }
  const toast = showLoadingToast({
    message: "",
    forbidClick: true,
    zIndex: 3000,
    className: "my-custom-toast",
    duration: 0,
  });
  let res: any = await saveCart(query.value);
  toast.close();
  if (res.httpCode == 200) {
    ElMessage.success("加购成功");
    user.value.cartUpdate += 1;
    emit(Events.done);
  }
}
function getPrice(b: any) {
  let a = props.detailInfo.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
}

function priceFormat(price: any) {
  if (!isNaN(price)) {
    let priceData = "";
    var priceArr = price.toString().split(".", 2);
    if (priceArr.length == 1) {
      priceData = price + ".00";
    }

    if (priceArr.length == 2) {
      var dotAfterArr = priceArr[1].split("");
      if (dotAfterArr.length > 4) {
        dotAfterArr = dotAfterArr.slice(0, 4);
      }
      if (dotAfterArr.length < 4) {
        var pad_len = 4 - dotAfterArr.length;
        for (var i = 0; i < pad_len; i++) {
          dotAfterArr.push("0");
        }
      }

      var tail = "";
      if ("00" == dotAfterArr[2] + dotAfterArr[3]) {
        tail = dotAfterArr[0] + dotAfterArr[1];
      } else {
        tail = dotAfterArr.join("");
      }

      priceData = priceArr[0] + "." + tail;
    }
    return priceData;
  }

  return false;
}
</script>
<template>
  <div class="add-detail">
    <h3 class="title">{{detailInfo.gn||detailInfo.name||detailInfo.goodsName}}</h3>
    <div class="info">
      <p>品牌<span>{{detailInfo.brandName}}</span></p>
      <p>型号<span>{{detailInfo.materialSn || detailInfo.customerSn}} </span></p>
      <p>目录<span>目录目录目录</span></p>
      <p v-if="detailInfo.packageSpecification">封装<span>{{detailInfo.packageSpecification}}</span></p>
      <p>起订量<span>{{detailInfo.packCount}} {{detailInfo.storeCompany}}</span></p>
      <p>商品编码<span>{{detailInfo.ksn || detailInfo.customerSn}}</span></p>
      <p>库存<span>有货</span></p>
      <p>单价</p>
      <div class="tab">
        <div class="tr">
          <div class="th">采购数量</div>
          <div class="th">单价（含税）</div>
        </div>
        <div class="tr" v-for="(item,idx) in detailInfo.priceTemplateArr" :key="idx">
          <div class="td">{{item.num}}</div>
          <div class="td">{{item.price}}</div>
        </div>
      </div>
      <div class="inp-wrap">
        购买量 {{ query.goodsNum }}
        <div class="number-box">
          <el-input-number v-model="query.goodsNum" :min="detailInfo.priceTemplateArr[0].num" :precision="0" :step="detailInfo.priceTemplateArr[0].num" :step-strictly="true" @change="changeNum" />
        </div>
      </div>
      <div class="footer-btn">
        <p>应付金额：¥{{query.xPrice}}</p>
        <el-button class="btn_main" @click="editCart" v-if="route.path=='/cart'">
          确定
        </el-button>
        <el-button class="btn_main" @click="addCart" v-else>
          加入购物车
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
a {
}
</style>
