<template>
  <div class="max-w1280">
    <div class="layer detail-wrap mb50">
      <template v-if="detailInfo.id">
        <div class="detail-info-wrap d-flex flex-direction-column">
          <div class="info-wrap">
            <div class="detail-info detail-info-1">
              <div class="info-left">
                <h3 class="info-title" title="贴片电容 18pF ±5% 25V">{{detailInfo.name}}</h3>
                <p>品牌<span>{{detailInfo.brandName}}</span></p>
                <p>型号<span>{{detailInfo.materialSn}} </span></p>
                <p>目录<span>目录目录目录</span></p>
                <p>封装<span>{{detailInfo.packageSpecification}}</span></p>
                <p>起订量<span>{{detailInfo.packCount}} {{detailInfo.storeCompany}}</span></p>
                <p>商品编码<span>{{detailInfo.ksn}}</span></p>
                <p>库存<span>有货</span></p>
              </div>
              <div class="info-img">
                <NuxtImg :src="detailInfo.goodsImg" :loading="isClient ? 'lazy' : 'eager'" :placeholder="isClient ? '/img/loading.png' : undefined"></NuxtImg>
              </div>
            </div>

            <div class="detail-info detail-info-2">
              <div class="info-warehouse info-arr">
                <div class="info-label">数据手册</div>
                <div class="arr-list">
                  <a :href="detailInfo.goodsManual" target="_blank" class="pdf"></a>
                </div>
              </div>
              <div class="info-warehouse info-arr">
                <div class="info-label">商品单价</div>
                <div class="arr-list">
                  <div class="priceTemplate">
                    <table>
                      <tbody>
                        <tr>
                          <th>采购数量</th>
                          <th>单价 (含13%增值税)</th>
                        </tr>
                        <tr v-for="(item,idx) in detailInfo.priceTemplateArr" :key="idx">
                          <td>{{item.num}}+</td>
                          <td>¥{{item.price}}/pcs</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
              <!-- <div class="d-flex info-warehouse warehouse-wrap info-arr">
                <div class="info-label">优惠券</div>
                <div class="radio-wrap arr-list">
                  <shippingProduct :warehouseList="warehouseList" :warehouseCode="createOrder.warehouseCode" v-model="createOrder.shippingProductCode"></shippingProduct>
                </div>
              </div> -->
            </div>
            <div class="detail-info detail-info-3">
              <h4>商品参数</h4>
              <div class="tab">
                <div class="tr">
                  <div class="th">属性</div>
                  <div class="th">参数值</div>
                </div>
                <div class="tr">
                  <div class="td">商品类别</div>
                  <div class="td">{{detailInfo.categoryName}}</div>
                </div>
                <div class="tr">
                  <div class="td">包装数量</div>
                  <div class="td">{{detailInfo.packCount}} {{detailInfo.storeCompany}}</div>
                </div>
                <div class="tr">
                  <div class="td">商品毛重</div>
                  <div class="td">--</div>
                </div>
                <template v-if="detailInfo.attrs&&detailInfo.attrs.length>0">
                  <div class="tr" v-for="(item, index) in detailInfo.attrs" :key="index">
                    <div class="td">{{item.attrId}}</div>
                    <div class="td">{{item.attrValue}}</div>
                  </div>
                </template>
                <div class="tr">
                  <div class="td">产品系列</div>
                  <div class="td">--</div>
                </div>
                <div class="tr">
                  <div class="td">行业应用</div>
                  <div class="td">{{detailInfo.industryId || '--'}}</div>
                </div>
                <div class="tr">
                  <div class="td">技术应用</div>
                  <div class="td">{{detailInfo.technologyId || '--'}}</div>
                </div>
              </div>
            </div>
            <div class="buy-btn-wrap">
              <a href="javascript:;" class="btn_monitor" :class="{'current':detailInfo.collect == 1}" @click="collectFun"><i :class="{'current':detailInfo.collect == 1}"></i> {{detailInfo.collect==1?'取消收藏':'加入收藏'}} </a>
              <el-button class="btn_main" @click="pcDialog">
                加入购物车
              </el-button>
            </div>
          </div>
        </div>
      </template>

    </div>
  </div>
  <el-drawer :title="detailInfo.name" 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="detailInfo" @done="done"></editCart>
  </el-drawer>
</template>

<script setup lang="ts">
let pageTitle: any = ref("HOTKING-在售商品-详情");
useHead(() => ({
  title: pageTitle.value,
}));
import { useAll } from "~/api/pubAll/service";
const { getProductDetail, saveHktFavorites, deleteFavorites } = useAll();
import { showLoadingToast, closeToast } from "vant";
import { Download } from "@element-plus/icons-vue";
import { DefaultQuery } from "~/domain/query";
import { type spuImgQuery } from "~/api/spu/spuQuery";
import type skuQuery from "~/api/sku/skuQuery";
import { type SkuStockQuery } from "~/api/sku/skuQuery";
import { useSku } from "~/api/sku/skuService";
import type skuType from "~/domain/Sku";
import { useSpu } from "~/api/spu/spuService";
import type addCartQuery from "~/api/cart/cartQuery";
import { useCart } from "~/api/cart/cartService";
import type warehouseType from "~/domain/warehouse";
import { useMonitor } from "~/api/monitor/monitorService";
const { monitorSubscribe, monitorUnsubscribe } = useMonitor();
const { addCart } = useCart();
import { type getPresaleListQuery } from "~/api/spu/spuQuery";
const presaleData: any = ref([]);
const defaultSort = { prop: "onShelfTime", isAsc: "ascending" };
const defaultQuery = () => {
  const q = new DefaultQuery({
    orderByColumn: defaultSort.prop,
    isAsc: defaultSort.isAsc,
  }) as getPresaleListQuery;
  return q;
};
const query: Ref<getPresaleListQuery> = ref(defaultQuery());
const { getSkuList, getSkuPrice, getSkuStock, skuInquiry } = useSku();
const route = useRoute();
import { SpuAttrDim } from "~/dim/spu";
import { useWarehouse } from "~/api/warehouse/warehouseService";
const { getWarehouseList } = useWarehouse();
const nuxtApp = useNuxtApp();
const isClient = !nuxtApp.ssrContext;
const user = useUserStore();
const querySku: Ref<skuQuery> = ref(new DefaultQuery() as skuQuery);
const errorBtnFalg: Ref<Boolean> = ref(false);
import ysIcon from "@/assets/img/ico/ys.png";
let rebateFalg = ref(false);
let rebateData = ref([]);
function rebateOpen() {
  if (!open.value.rebate) {
    open.value.rebate = true;
    Tracking({
      page: "detail",
      cate: "返佣",
      name: "详情梯度点击",
      isLink: false,
      url: "",
    });
  } else {
    open.value.rebate = false;
  }
}

const cartQuery: Ref<addCartQuery> = ref({
  skuCode: "",
  skuCount: 1,
  vendorWarehouseCode: "",
  vendorShippingProductCode: "",
});
const createOrder: Ref<any> = ref({
  warehouseCode: "",
  shippingProductCode: "",
  USPS: "USPS",
});
const open = ref({
  detail: false,
  down: false,
  publish: false,
  title: false,
  restock: false,
  rebate: false,
});
let noEnable: Ref<boolean> = ref(false);
let btnLoading: Ref<boolean> = ref(false);
const warehouseList: Ref<warehouseType[]> = ref([]);
let isWarehouse: Ref<boolean> = ref(false);
let skuArr: Ref<skuType[]> = ref([]);
const queryImg: Ref<spuImgQuery> = ref({
  spuCode: "",
});
let detaileId: Ref<string> = ref("");
let detailInfo: Ref<any> = ref({}); //默认sku信息
let skuPrice: Ref<number> = ref(0.0); //默认sku价格
let detaileImg: Ref<any> = ref([]); // spu图片集合
let attrValueMap: Ref<any> = ref({}); //spu属性集合
let attrMap: Ref<any> = ref({});
let activeArr: Ref<any> = ref([]); //选中的属性
let activeArr2: Ref<any> = ref([]); //选中的属性
let skuExist: Ref<any> = ref([]); //存在的sku组合
let skuExist2: Ref<any> = ref([]); //存在的sku组合
let skuAllMap: Ref<any> = ref([]);
let skuAll: Ref<any> = ref([]); //sku组合带id，并给出具体的键值
let weightKg = ref(0);
let activeName: Ref<string> = ref("1");
let payNum: Ref<number> = ref(1);
let requestFalg = ref(false);
let requestWarehouse = ref(false);
let stockCanSell = ref(0);
let stockData: any = ref({});
let skuInquiryInfo: Ref<any> = ref({
  maxShippingAmount: 0,
  minShippingAmount: 0,
  outAmount: 0,
});
let shippingType: any = ref("vendor");
watch(
  () => createOrder.value.warehouseCode,
  async (first: any, second: any) => {
    if (!requestFalg.value && second) {
      getSkuStockFun({
        skuCode: detailInfo.value.skuCode,
        vendorWarehouseCode: createOrder.value.warehouseCode,
      });
    }
    requestFalg.value = false;
    let list = warehouseList.value.filter(
      (i: warehouseType) => i.warehouseCode == createOrder.value.warehouseCode
    );
    if (list[0].shippingProducts?.length > 0) {
      createOrder.value.shippingProductCode =
        list[0].shippingProducts[0].shippingProductCode;
    } else {
      createOrder.value.shippingProductCode = "";
    }
  }
);

watch(
  () => createOrder.value.shippingProductCode,
  async (first: any, second: any) => {
    if (
      createOrder.value.shippingProductCode &&
      createOrder.value.shippingProductCode != " "
    ) {
      let list: any = warehouseList.value.filter(
        (i: warehouseType) => i.warehouseCode == createOrder.value.warehouseCode
      );
      let list2 = list[0].shippingProducts.filter(
        (i: any) =>
          i.shippingProductCode == createOrder.value.shippingProductCode
      );
      shippingType.value = list2[0].shippingType;
      skuInquiryFun();
    }
  }
);

let skuk = "";
watch(
  () => route.query.code,
  async (first: any, second: any) => {
    skuk = "";
    czFun();
    detaileId.value = route.query.code as string;
    queryImg.value.spuCode = detaileId.value;
    querySku.value.spuId = detaileId.value;
    user.value.cartFalg = false;
    getDetailFun();
  }
);

watch(
  () => detailInfo.value.skuCode,
  async (first: any, second: any) => {
    createOrder.value.shippingProductCode = " ";
  }
);
function pcDialog() {
  open.value.detail = true;
}
function done() {
  cancel();
}
async function collectFun() {
  if (!user.value.isLogin) {
    return navigateTo({
      path: "/login",
      query: { redirect: route.fullPath },
    });
  }
  let res: any = null;
  // 显示加载
  const toast = showLoadingToast({
    message: "",
    forbidClick: true,
    duration: 0,
  });
  if (detailInfo.value.collect == 1) {
    res = await deleteFavorites({ goodsId: detailInfo.value.id });
  } else {
    let params = {
      goodsImg: detailInfo.value.goodsImg,
      brandName: detailInfo.value.brandName,
      categoryName: detailInfo.value.categoryName,
      deliveryDate: detailInfo.value.deliveryNo,
      favoriteType: 1,
      goodsId: detailInfo.value.id,
      goodsName: detailInfo.value.name,
      materialSn: detailInfo.value.materialSn,
      packCount: detailInfo.value.packCount,
      packageSpecification: detailInfo.value.packageSpecification,
      setUp: detailInfo.value.setUp,
      specifications: detailInfo.value.specParam,
      status: 1, //状态(1已收藏|2已取消) ,
      storeCount: detailInfo.value.storeCount,
      priceTemplate: JSON.stringify(detailInfo.value.priceTemplate),
    };
    res = await saveHktFavorites(params);
  }
  toast.close();
  if (res.httpCode == 200) {
    if (detailInfo.value.collect == 1) {
      ElMessage.success("取消成功");
      detailInfo.value.collect = 2;
    } else {
      ElMessage.success("收藏成功");
      detailInfo.value.collect = 1;
    }
  }
}
async function getInboundListFun(res: any) {
  // const q = JSON.parse(JSON.stringify(query.value));
  // q.spuCode = detailInfo.value.spuCode;
  // q.pageSize = 9999;
  // const res: any = await getInboundList(q);
  if (res.code == 200) {
    // 提取相同 skuCode 的数据并整合
    presaleData.value = res.rows.map((itemA: any) => {
      const matchingB = skuAll.value.find(
        (itemB: any) => itemB.skuCode === itemA.skuCode
      );
      if (matchingB) {
        // 合并 attr 数据
        const { totalStockCanSell, totalStockIncoming, skuCode, ...attr } =
          matchingB;
        return {
          ...itemA,
          attr, // 添加 attr 属性
        };
      }
      return itemA; // 没有匹配项时，直接返回原数据
    });
  }
}
function openDown() {
  if (!user.value.isLogin) {
    return navigateTo({
      path: "/login",
      query: { redirect: route.fullPath },
      // replace: true,
    });
  }
  open.value.down = true;
}
function openPublish() {
  open.value.publish = true;
}
function cancel() {
  Object.keys(open.value).forEach(
    (key) => (open.value[key as keyof typeof open.value] = false)
  );
}
function publishDone() {
  cancel();
}
async function getSkuStockFun(que: SkuStockQuery) {
  const res: any = await getSkuStock(que);
  if (res.code == 200) {
    stockCanSell.value = res.data.stockCanSell;
    stockData.value = res.data;
  }
}

async function skuInquiryFun() {
  if (
    !createOrder.value.warehouseCode ||
    !createOrder.value.shippingProductCode
  ) {
    return;
  }
  let que = {
    skuCode: detailInfo.value.skuCode,
    skuCount: payNum.value,
    fromWarehouseCode: createOrder.value.warehouseCode,
    shippingProductCode: createOrder.value.shippingProductCode,
    inquiryShippingRange: "yes",
  };
  const res: any = await skuInquiry(que);
  if (res.code == 200) {
    skuInquiryInfo.value = res.data;
    weightKg.value = skuInquiryInfo.value.totalWeightkg;
    skuPrice.value = skuInquiryInfo.value.skuAmount;
    errorBtnFalg.value = false;
  } else {
    skuInquiryInfo.value = {
      maxShippingAmount: 0,
      minShippingAmount: 0,
      outAmount: 0,
    };
    errorBtnFalg.value = true;
  }
}

function czFun() {
  btnLoading.value = false;
  warehouseList.value = [];
  isWarehouse.value = false;
  requestWarehouse.value = false;
  skuArr.value = [];
  detaileId.value = "";
  detailInfo.value = {}; //默认spu信息
  detailInfo.value = {}; //默认sku信息
  skuPrice.value = 0.0; //默认sku价格
  detaileImg.value = []; // spu图片集合
  attrValueMap.value = {}; //spu属性集合
  attrMap.value = {};
  activeArr.value = []; //选中的属性
  activeArr2.value = []; //选中的属性
  skuExist.value = []; //存在的sku组合
  skuExist2.value = []; //存在的sku组合
  skuAllMap.value = [];
  skuAll.value = []; //sku组合带id，并给出具体的键值
  weightKg.value = 0;
  activeName.value = "1";
  payNum.value = 1;
  errorBtnFalg.value = false;
}
async function addCartFun() {
  if (noEnable.value) {
    return;
  }
  if (skuInquiryInfo.value.maxShippingAmount === undefined) {
    return ElMessage.error("运费异常，无法加购，请联系客服");
  }
  btnLoading.value = true;
  const res: any = await addCart(cartQuery.value);
  btnLoading.value = false;
  if (res.code == 200) {
    ElMessage.success("加购成功");
    user.value.cartUpdate += 1;
  }
}

let warehouseCodesStocks: any = ref([]);
async function getWarehouseListFun() {
  let res: any = await getWarehouseList({ skuCode: detailInfo.value.skuCode });
  if (res.code == 200) {
    let rows = res.data;
    resetFun(rows);
  }
}
function resetFun(list: warehouseType[]) {
  list.forEach((item: any, index: number) => {
    if (item.shippingProducts && item.shippingProducts.length > 1) {
      item.shippingProducts.sort((a: any, b: any) => {
        if (a.shippingType === "vendor" && b.shippingType !== "vendor") {
          return -1; // a 在 b 前
        } else if (a.shippingType !== "vendor" && b.shippingType === "vendor") {
          return 1; // b 在 a 前
        } else {
          return 0; // 保持原顺序
        }
      });
    }
  });
  createOrder.value.shippingProductCode = " ";
  warehouseList.value = list;
  requestWarehouse.value = true;
  if (list.length > 0) {
    createOrder.value.warehouseCode = warehouseList.value[0].warehouseCode;
    let list = warehouseList.value.filter(
      (i: warehouseType) => i.warehouseCode == createOrder.value.warehouseCode
    );
    if (list[0].shippingProducts?.length > 0) {
      createOrder.value.shippingProductCode =
        list[0].shippingProducts[0].shippingProductCode;
    } else {
      createOrder.value.shippingProductCode = "";
    }
    // skuInquiryFun();
    getSkuStockFun({
      skuCode: detailInfo.value.skuCode,
      vendorWarehouseCode: createOrder.value.warehouseCode,
    });
    requestFalg.value = true;
    isWarehouse.value = true;
  } else {
    isWarehouse.value = false;
  }
}

function generateCombinations(
  arrays: any,
  index: any,
  currentCombination: any,
  combinations: any
) {
  if (index === arrays.length) {
    combinations.push(currentCombination.join("^"));
    return;
  }

  for (let value of arrays[index]) {
    currentCombination.push(value);
    generateCombinations(arrays, index + 1, currentCombination, combinations);
    currentCombination.pop();
  }
}
async function getDetailImgFun(res: any) {
  // const q = JSON.parse(JSON.stringify(queryImg.value));
  // const res: any = await getDetailImg(q);
  if (res.code == 200) {
    // 保留已存在的 mainImageUrl（兼容 SSR 反序列化丢失的情况）
    const existingMainImage = detaileImg.value.find(
      (img: any) => img.url === detailInfo.value.mainImageUrl
    );

    // 合并新数据
    detaileImg.value = [
      ...(existingMainImage ? [existingMainImage] : []),
      ...res.rows.filter(
        (img: any) => img.url !== detailInfo.value.mainImageUrl
      ),
    ];

    // 如果完全没有 mainImageUrl，再添加
    if (!existingMainImage && detailInfo.value.mainImageUrl) {
      detaileImg.value.unshift({ url: detailInfo.value.mainImageUrl });
    }
  }
}

async function getSkuListFun() {
  const q = JSON.parse(JSON.stringify(querySku.value));
  const res: any = await getSkuList(q);
  if (res.code == 200) {
    // spuArr.value.filter((item: spuType,idx:number) => {
    //   if(item.id == spuId){
    //     spuArr.value[idx].children = res.rows
    //   }
    // })
    skuArr.value = res.rows;
    if (res.rows.length > 0) {
      //getSkuPriceFun("", "");
    } else {
      ElMessage.error("没有sku商品！");
    }
  }
}
function outStockFun(keys: any, i: string, index: number) {
  let falg: any = false;
  let totalStock = 0;
  let totalStockIncoming = 0;
  if (index == 0) {
    // 计算第一个变体属性的总库存是否为0
    totalStock = skuAll.value
      .filter((item: any) => item[keys] === i)
      .reduce((total: any, item: any) => total + item.totalStockCanSell, 0);

    totalStockIncoming = skuAll.value
      .filter((item: any) => item[keys] === i)
      .reduce((total: any, item: any) => total + item.totalStockIncoming, 0);
  } else if (index == 1) {
    if (activeArr2.value.length == 0) {
      return;
    }
    let firstAttr = activeArr2.value.split("^")[0];
    let firstAttrKey =
      Object.entries(activeArr.value).find(
        ([key, value]) => value === firstAttr
      )?.[0] || "";
    totalStock = skuAll.value
      .filter(
        (item: any) => item[firstAttrKey] === firstAttr && item[keys] === i
      )
      .reduce((total: any, item: any) => total + item.totalStockCanSell, 0);

    totalStockIncoming = skuAll.value
      .filter(
        (item: any) => item[firstAttrKey] === firstAttr && item[keys] === i
      )
      .reduce((total: any, item: any) => total + item.totalStockIncoming, 0);
  } else {
    if (activeArr2.value.length == 0) {
      return;
    }
    let AttrArr = activeArr2.value.split("^");
    let firstAttr = AttrArr[0];
    let twoAttr = AttrArr[1];
    let firstAttrKey =
      Object.entries(activeArr.value).find(
        ([key, value]) => value === firstAttr
      )?.[0] || "";
    let twoAttrKey =
      Object.entries(activeArr.value).find(
        ([key, value]) => value === twoAttr
      )?.[0] || "";
    totalStock = skuAll.value
      .filter(
        (item: any) =>
          item[firstAttrKey] === firstAttr &&
          item[twoAttrKey] === twoAttr &&
          item[keys] === i
      )
      .reduce((total: any, item: any) => total + item.totalStockCanSell, 0);

    totalStockIncoming = skuAll.value
      .filter(
        (item: any) =>
          item[firstAttrKey] === firstAttr &&
          item[twoAttrKey] === twoAttr &&
          item[keys] === i
      )
      .reduce((total: any, item: any) => total + item.totalStockIncoming, 0);
  }
  if (totalStockIncoming > 0 && totalStock == 0) {
    //库存为0，且是补货，就是补货
    falg = 1;
  }
  if (totalStock == 0 && totalStockIncoming == 0) {
    //库存为0，且不是补货，就是缺货
    falg = true;
  } else if (totalStockIncoming == 0 && totalStock > 0) {
    falg = false;
  }
  return falg;
}
// let zh3 = [];
function disabledFun(keys: any, item: string, index: number, idx: number) {
  if (index > 0) {
    if (Object.keys(activeArr.value).length > 2) {
      if (index > 1) {
        let zh4 = activeArr2.value + "^" + item;
        if (skuExist.value.indexOf(zh4) > -1) {
          return false;
        } else {
          return true;
        }
      } else {
        let zh3 = skuk + "^" + item;
        if (skuExist2.value.indexOf(zh3) > -1) {
          return false;
        } else {
          return true;
        }
      }
    } else {
      let zh = skuk + "^" + item;
      if (skuExist.value.indexOf(zh) > -1) {
        return false;
      } else {
        return true;
      }
    }
  } else {
    skuk = activeArr.value[keys]?.trim();
    return false;
  }
}
let outStockFalg = ref(true);
async function getSkuPriceFun(
  keys: any,
  item: string,
  index: number,
  idx: number
) {
  if (noEnable.value) {
    return;
  }
  if (disabledFun(keys, item, index, idx)) {
    return;
  }
  // if(skuExist.value.indexOf(zh)>-1){
  //   return false
  // }
  outStockFalg.value = false;
  let attrKeyIdx = 0; //归属的key index
  for (const key in attrMap.value) {
    if (attrMap.value[key] == keys) {
      attrKeyIdx = parseInt(key.replace("attrCode0", "")) - 1;
    }
  }
  if (attrKeyIdx != Object.keys(activeArr.value).length - 1) {
    let skuExistAttr: any[] = [];
    let skuExistAttr2: any[] = [];
    let skuExistAttr3: any[] = [];
    let yesCurrent = skuExist.value.filter(
      (i: string, index: number) => i.indexOf(item + "^") > -1
    ); //能否被选择的 attrCode02
    yesCurrent.forEach((i: string, index: number) => {
      let idx = getAllIndexes(i, "^");
      if (idx.length == 1) {
        //attrCode01  才会触发
        skuExistAttr.push(i.substring(idx[0] + 1));
      } else {
        // 超过2个数下预留
        if (
          attrKeyIdx == 1 &&
          i.indexOf(activeArr.value[attrMap.value["attrCode01"]]) < 0
        ) {
          //排除 非选中 attrCode01 的值
          return;
        }
        let as2 = i.substring(idx[0] + 1);
        let idx2 = getAllIndexes(as2, "^");
        let as3 = as2.substring(idx2[0] + 1);
        skuExistAttr2.push(as2.substring(0, idx2[0]));
        skuExistAttr3.push(as3);
      }
    });
    skuExistAttr3 = [...new Set(skuExistAttr3)];
    if (Object.keys(activeArr.value).length > 2) {
      activeArr.value[attrMap.value["attrCode02"]] = skuExistAttr2[0];
      activeArr.value[attrMap.value["attrCode03"]] = skuExistAttr3[0];
    } else {
      for (const key in activeArr.value) {
        if (keys != key) {
          activeArr.value[key] = skuExistAttr[0];
        }
      }
    }
  }
  if (keys.length > 0) {
    activeArr.value[keys] = item;
  }

  let falgIdx = 0;
  let skuCode = "";
  let isSkuImgAttrVal = "";
  skuAll.value.forEach((item: any, index: number) => {
    if (falgIdx > 0) return;
    falgIdx = 0;
    for (const key in item) {
      if (
        key != "skuCode" &&
        key != "totalStockCanSell" &&
        key != "totalStockIncoming"
      ) {
        if (item[key] != activeArr.value[key]) {
          falgIdx -= 1;
        }
      }
    }
    if (falgIdx > -1) {
      falgIdx = index;
      skuCode = item.skuCode;
    }
  });
  errorBtnFalg.value = false;
  const res: any = await getSkuPrice(skuCode);
  if (res.code == 200) {
    skuPrice.value = res.data.sellPrice;
    detailInfo.value = res.data;
    const filteredProduct = detailInfo.value.skus.find(
      (product: any) => product.skuCode === skuCode
    );
    detailInfo.value.totalStockCanSell = filteredProduct.totalStockCanSell;
    detailInfo.value.totalStockIncoming = filteredProduct.totalStockIncoming;
    detailInfo.value.priceDecreaseAmount = filteredProduct.priceDecreaseAmount;
    detailInfo.value.priceDecreaseOn = filteredProduct.priceDecreaseOn;
    detailInfo.value.priceDecreasePercent =
      filteredProduct.priceDecreasePercent;
    detailInfo.value.priceIncreaseLaterAmount =
      filteredProduct.priceIncreaseLaterAmount;
    detailInfo.value.priceIncreaseLaterOn =
      filteredProduct.priceIncreaseLaterOn;
    detailInfo.value.priceIncreaseLaterPercent =
      filteredProduct.priceIncreaseLaterPercent;
    detailInfo.value.priceIncreaseLaterSellPrice =
      filteredProduct.priceIncreaseLaterSellPrice;
    detailInfo.value.priceIncreaseLeftHours =
      filteredProduct.priceIncreaseLeftHours;
    detailInfo.value.priceIncreaseLaterTime =
      filteredProduct.priceIncreaseLaterTime;
    detailInfo.value.priceIncreaseLaterSellPrice =
      filteredProduct.priceIncreaseLaterSellPrice;

    payNum.value = 1;
    detailInfo.value.weightKg = res.data.spuWeightKg;
    weightKg.value = detailInfo.value.weightKg;
    if (
      detailInfo.value.attrCode01.length > 0 &&
      detailInfo.value.attrCode02.length > 0 &&
      detailInfo.value.attrCode03.length > 0
    ) {
      activeArr2.value =
        detailInfo.value.attrValue01?.trim() +
        "^" +
        detailInfo.value.attrValue02?.trim();
    } else if (
      detailInfo.value.attrCode01.length > 0 &&
      detailInfo.value.attrCode02.length > 0
    ) {
      activeArr2.value = detailInfo.value.attrValue01?.trim();
    }
  }
  outStockFalg.value = true;

  getWarehouseListFun();
}

function getAllIndexes(str: string, char: string) {
  let indexes = [];
  for (let i = 0; i < str.length; i++) {
    if (str[i] === char) {
      indexes.push(i);
    }
  }
  return indexes;
}

async function getDetailFun() {
  const res: any = await getProductDetail(detaileId.value);
  resultDetail(res);
}
async function resultDetail(res: any) {
  if (res.httpCode == 200) {
    if (res.data?.priceTemplate?.length > 0) {
      res.data.priceTemplateArr = JSON.parse(res.data?.priceTemplate);
    }
    detailInfo.value = res.data;
    console.log(detailInfo.value.priceTemplateArr)
    pageTitle.value = "HOTKING-在售商品-" + detailInfo.value.name;
  }
}

function getParams() {
  if (route.query.code) {
    detaileId.value = route.query.code as string;
    queryImg.value.spuCode = detaileId.value;
    querySku.value.spuId = detaileId.value;
  } else {
    navigateTo({ path: "/" });
  }
}

getParams();
const {
  data: ssrDetail,
  error,
  refresh,
} = await useAsyncData<any>(`getProductDetail`, () =>
  getProductDetail(detaileId.value)
);
if (ssrDetail.value) {
  resultDetail(ssrDetail.value);
} else {
  getDetailFun();
}

onMounted(() => {
  getParams();
});

// Use multiple languages ​​in ts
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance()!;
const isOpen = ref(true);

let controlledSwiper: any = ref(null);
let controlledSwiper2: any = ref(null);
let swiperIdx = ref(0);
// 获取实例 swiper
function setControlledSwiper(swiper: any) {
  controlledSwiper.value = swiper;
}
// 获取实例 swiper
function setControlledSwiper2(swiper: any) {
  controlledSwiper2.value = swiper;
}
function slideTo(idx: number) {
  swiperIdx.value = controlledSwiper.value.clickedIndex;
  controlledSwiper2.value.slideTo(idx, 1000, false);
}
function slideChangeFun(e: any) {
  swiperIdx.value = controlledSwiper2.value.activeIndex;
}
function handleChange(val: number) {
  weightKg.value = parseFloat((val * detailInfo.value.weightKg).toFixed(2));
  if (createOrder.value.shippingProductCode) {
    skuInquiryFun();
  }
}
const handleClick = (name: any) => {};
</script>
<style scoped lang="scss">
@import "@/assets/css/detail.scss";
</style>
<style lang="scss">
a {
}
</style>


