<template>
  <div class="max-w1280">
    <div class="layer match-wrap" v-loading="loading">
      <div class="bom-title-wrap mb12">
        <van-cell-group>
          <van-cell title="共匹配到型号" :value="`${bomListObj?.list.length || 0}个`" />
          <van-cell :title="saveBomList.name" is-link value="修改" title-class="bomTitle" @click="editTitleFun" />
          <van-cell title="导出BOM" is-link @click="downBom" value="导出" />
          <van-cell title="我的BOM" is-link to="/home/order/bom" />
        </van-cell-group>
      </div>
      <ul class="product-ul" v-if="bomList?.length>0">
        <li class="product-li" v-for="(item,idx) in bomList" :id="`item-idx`" :key="idx">
          <div class="check-wrap">
            <i :class="{check:item.falg}" :disabled="!item.count || item.dealPrice=='0.0'" @click="singeCheck($event,item)"></i>
          </div>
          <NuxtLink to="javascript:;">
            <div class="product-info">
              <h3 class="title">需求规格：{{item.materialSn || '--'}}</h3>
              <p>参数：{{item.param || '--'}}</p>
              <p v-if="item.brandName">品牌：{{item.brandName}}</p>
              <template v-if="item.count!=0">
                <h3 class="title">匹配商品：<a v-if="item.count>1" class="tiH" href="javascript:;" @click="thFun(item)">可替换商品</a></h3>
                <p>型号：<span class="sn" v-html="item.matchMaterialSn"></span></p>
                <p>品牌：<span class="sn" v-html="item.matchBrandName"></span></p>
                <p>产品参数：<span v-html="item.matchParam"></span></p>
                <p class="matchPdf">产品手册：<a :href="item.matchPdf" target="_blank" class="pdf"></a></p>
                <p>购买数量：
                  <span class="number-box">
                    <el-input-number v-model="item.matchNum" :min="item.packageCount" :max="1000000" :precision="0" :step="item.packageCount" :step-strictly="true" @change="editNumFun2" />
                  </span>
                </p>
                <p>单价：￥{{item.dealPrice ? item.dealPrice : 0}}</p>
              </template>
              <p class="error" v-else>匹配商品：无法匹配，请修改需求型号/参数</p>
            </div>
          </NuxtLink>
          <div class="opt">
            <i class="sc" @click="delFunDialog(item)"></i>
          </div>
        </li>
      </ul>
    </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>

    <van-dialog v-model:show="editTitle" title="修改BOM名称" show-cancel-button :before-close="beforeClose">
      <van-cell-group inset class="mt10_i mb10_i">
        <van-field v-model="editTitleText" name="name" placeholder="请填写BOM名称" :rules="[{ required: true, message: '请填写BOM名称' }]" />
      </van-cell-group>
    </van-dialog>
    <div class="buy-btn-wrap" v-if="user.cartGroup.length>0">
      <div class="tips">
        <p>已选中&nbsp;<span class="mainColor">{{num}}</span>&nbsp;种商品</p>
        <!-- <p>预计总价(未含运费):<span class="mainColor">¥{{total.toFixed(3)}}</span></p> -->
      </div>
      <el-button class="btn_main" @click="shopBtn">
        {{btnText}}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Search } from "@element-plus/icons-vue";
import empty from "@/assets/img/empty.svg";
import { showToast } from "vant";
import { showLoadingToast, closeToast } from "vant";
let pageTitle: any = ref("HOTKING-秒配BOM表，一键下单");
useHead(() => ({
  title: pageTitle.value,
}));
import { useAll } from "~/api/pubAll/service";
const {
  delCartGood,
  get_bom_detail,
  bom_updata_name,
  bom_add_list,
  bom_del,
  batchCart,
} = useAll();
let currentItem: any = ref({});
const user = useUserStore();
user.value.adminTitle = "购物车";
const open = ref({
  detail: false,
});

const route = useRoute();
const nuxtApp = useNuxtApp();
const isClient = !nuxtApp.ssrContext;
let bomListObj: any = ref(null);
let edirP2: any = ref({
  bomId: "",
  materialSn: "",
  num: "",
  param: "",
  brandName: "",
  pageSize: 10,
  pageNum: 1,
});
let downParams: any = ref({
  id: "",
  name: "",
  uuid: "",
  createTime: "",
  list: [],
});
let type: any = ref(route.query.type);
let bomList: any = ref([]);
let total: any = ref(0);
let num: any = ref(0);
let editTitle: any = ref(false);
let saveBomList: any = ref({
  name: "物料清单-" + new Date().valueOf(),
  list: [],
});

let text: any = ref("添加商品");
let pageTotal: any = ref(0);
let bomAddGoods: any = ref(false);
let thFalg: any = ref(false);
let addList: any = ref(null);
let editParam: any = ref(false);
let editParamIdx: any = ref(-1);
let edirP: any = ref({
  id: "",
  materialSn: "",
  num: "",
  param: "",
  brandName: "",
});
let editNum: any = ref(true);
let editNumIdx: any = ref(-1);

let loading = ref(true);
let selectedCount: any = ref(0);
onMounted(() => {
  if ((type.value == 1 || type.value == 2) && bomListObj.value) {
    bomListObj.value = JSON.parse(localStorage.getItem("excelList") as any);
    edirP2.value.bomId = bomListObj.value.uuid;
    bomList.value = bomListObj.value.allList;
    bomList.value.forEach((item: any) => {
      item.falg = item.count && item.dealPrice != "0.0";
      if (item.falg) {
        selectedCount.value += 1;
      }
    });
    downParams.value = {
      id: bomListObj.value.id,
      name: bomListObj.value.name,
      uuid: bomListObj.value.uuid,
      createTime: bomListObj.value.createTime,
      list: [],
    };
    loading.value = false
    count();
  } else {
    getBomDetail(route.query.id);
  }
});

function delFunDialog(item: any) {
  ElMessageBox.confirm("确定要删除这个商品吗？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      bomDel(item);
    })
    .catch(() => {
      // catch error
    });
}
async function bomDel(obj: any) {
  const toast = showLoadingToast({
    message: "",
    forbidClick: true,
    duration: 0,
    zIndex: 3000,
    className: "my-custom-toast",
  });
  const res: any = await bom_del({ id: obj.id });
  setTimeout(() => {
    toast.close();
  }, 1000);
  if (res.httpCode == 200) {
    bomListObj.value.allList.forEach((item: any, index: any) => {
      if (item.id == obj.id) {
        bomListObj.value.allList.splice(index, 1);
      }
    });
    bomListObj.value.list.forEach((item: any, index: any) => {
      if (item.id == obj.id) {
        bomListObj.value.list.splice(index, 1);
      }
    });
    bomListObj.value.unList.forEach((item: any, index: any) => {
      if (item.id == obj.id) {
        bomListObj.value.unList.splice(index, 1);
      }
    });
    localStorage.setItem("excelList", JSON.stringify(bomListObj.value));
  }
}

async function getBomDetail(id: any) {
  let res: any = await get_bom_detail({ id: id });
  if (res.httpCode == 200) {
    loading.value = false
    saveBomList.value.name = res.data.name;
    bomListObj.value = res.data;
    edirP2.value.bomId = bomListObj.value.uuid;
    bomList.value = bomListObj.value.allList;
    downParams.value = {
      id: bomListObj.value.id,
      name: bomListObj.value.name,
      uuid: bomListObj.value.uuid,
      createTime: bomListObj.value.createTime,
      list: [],
    };
  } else {
    return ElMessage.error(res.message);
  }
}

let editTitleText: any = ref("");
function editTitleFun() {
  editTitle.value = true;
  editTitleText.value = saveBomList.value.name;
}
const beforeClose = async (action: any) => {
  if (action === "cancel") {
    return true;
  }

  if (action === "confirm") {
    if (!editTitleText.value) {
      ElMessage.error("请填写BOM名称");
      return false; // 校验失败，不关闭
    }
    try {
      const res: any = await bom_updata_name({
        id: bomListObj.value.id,
        name: editTitleText.value,
      });
      if (res.httpCode === 200) {
        ElMessage.success("修改成功");
        saveBomList.value.name = editTitleText.value;
        return true; // 允许关闭
      } else {
        ElMessage.error(res.message || "修改失败");
        return false; // 不关闭弹窗
      }
    } catch (e) {
      ElMessage.error("网络异常，请稍后重试");

      return false; // 不关闭弹窗
    }
  }
  return true;
};

// 导出结果
async function downBom() {
  downParams.value.list = bomListObj.value.list;
  let obj = {
    method: "post",
    url: `${useRuntimeConfig().public.apiBase}/bom/exportBomExcel`,
    fileName: `bom查询结果导出`,
    params: downParams.value,
  };
  exportMethod2(obj); // 模板导出
}
function clickPopBox() {
  window.open(
    "https://hm.baidu.com/hm.js?30d5f0cd8e30265492389905f69cf896",
    "",
    "height=600px,width=800px"
  );
}
function change(val: any) {
  edirP2.value.pageNum = val;
  addBom();
}
function blurFun(e: any, packageCount: any, idx: any) {}
function addFun() {
  text.value = "添加商品";
  pageTotal.value = 0;
  bomAddGoods.value = true;
  thFalg.value = false;
  addList.value = null;
  edirP2.value = {
    bomId: bomListObj.value.uuid,
    materialSn: "",
    num: "",
    param: "",
    brandName: "",
    pageSize: 10,
    pageNum: 1,
  };
}
function thFun(item: any) {
  text.value = "替换商品";
  addList.value = null;
  thFalg.value = true;
  edirP2.value = {
    bomId: bomListObj.value.uuid,
    materialSn: item.materialSn,
    num: item.num,
    param: item.param,
    brandName: item.brandName,
    pageSize: 10,
    pageNum: 1,
    rowId: item.id,
  };
  bomAddGoods.value = true;
  addBom();
}
function editParamFun(idx: any, type: any, item: any) {
  editParam.value = true;
  if (type == 1) {
    editParam.value = false;
  } else {
    edirP.value = {
      id: item.id,
      materialSn: item.materialSn,
      num: item.num,
      param: item.param,
      brandName: item.brandName,
    };
  }
  editParamIdx.value = idx;
}
function editNumFun2() {
  total.value = 0;
  num.value = 0;
  console.log(bomList.value);
  for (let i = 0; i < bomList.value.length; i++) {
    if (bomList.value[i].falg) {
      total.value += parseFloat(bomList.value[i].totalMoney);
      num.value += 1;
    }
  }
}
function editNumFun(idx: any, type: any, e: any, obj: any) {
  editNum.value = true;
  if (type == 1) {
    editNum.value = false;
    if (obj.packageCount) {
      let num = parseInt(e.target.parentElement.children[0].value);
      let a = num;
      let b = a % parseInt(obj.packageCount);

      if (a > parseInt(obj.packageCount)) {
        if (b != 0) {
          a += parseInt(obj.packageCount) - b;
        }
        if (a > 1000000) {
          let c = 1000000 % parseInt(obj.packageCount);
          if (c != 0) {
            a = 1000000 - c;
          } else {
            a = 1000000;
          }
        }
      } else {
        a = parseInt(obj.packageCount);
      }
      bomListObj.value.allList.forEach((item: any, index: any) => {
        if (item.id == obj.id) {
          bomListObj.value.allList[index].matchNum = a;
        }
      });
      bomListObj.value.list.forEach((item: any, index: any) => {
        if (item.id == obj.id) {
          bomListObj.value.list[index].matchNum = a;
        }
      });
      bomListObj.value.unList.forEach((item: any, index: any) => {
        if (item.id == obj.id) {
          bomListObj.value.unList[index].matchNum = a;
        }
      });
    }
  }
  editNumIdx.value = idx;
}

async function addBom() {
  const toast = showLoadingToast({
    message: "",
    forbidClick: true,
    zIndex: 3000,
    className: "my-custom-toast",
    duration: 0,
  });
  let res: any = await bom_add_list(edirP2.value);
  toast.close();
  if (res.httpCode == 200) {
    addList.value = res.data.records;
    pageTotal.value = res.data.total;
    addList.value.forEach((item: any) => {
      if (!item.count) {
        item.count = 1;
      }
    });
  } else {
    return ElMessage.error(res.message);
  }
}
function singeCheck(e: any, item: any) {
  item.falg = !item.falg;
  if (!item.falg) {
    total.value = parseFloat(total.value) - parseFloat(item.totalMoney);
    num.value -= 1;
    selectedCount.value -= 1;
  } else {
    total.value = parseFloat(total.value) + parseFloat(item.totalMoney);
    num.value += 1;
    selectedCount.value += 1;
  }
  if (total.value < 0) {
    total.value = 0;
  }
}
function count() {
  for (let i = 0; i < bomList.value.length; i++) {
    if (bomList.value[i].count > 0) {
      total.value += parseFloat(bomList.value[i].totalMoney);
      num.value += 1;
    }
  }
}

let shopList: any = ref([]);
let btnText: any = "一键加入购物车";
async function shopBtn() {
  shopList.value = [];
  bomList.value.forEach((item: any) => {
    if (item.falg) {
      shopList.value.push(item);
    }
  });
  if (shopList.value.length > 0) {
    const toast = showLoadingToast({
      message: "",
      forbidClick: true,
      zIndex: 3000,
      className: "my-custom-toast",
      duration: 0,
    });
    let res: any = await batchCart({
      goodsInfo: shopList.value,
      language: "1",
    });
    toast.close();
    if (res.httpCode == 200) {
      ElMessage.success("您选中的商品已成功加入购物车!");
      // this.$router.push('/cart')
      navigateTo({
        path: "/cart",
      });
    }
  } else {
    return ElMessage.error("请勾选商品在加入购物车");
  }
}

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;
}
.match-wrap {
  background: linear-gradient(180deg, #f7f7f7, #fff0 2.666667rem) !important;
  padding-top: 12px;
  min-height: calc(100vh - 44px - 54px);
  padding-bottom: 124px;
  &.noCon {
    background: #fff !important;
  }
  .product-ul {
    margin-left: 12px;
    margin-right: 12px;
    .product-info {
      max-width: 275px;
      padding-top: 0;
      padding-bottom: 0;
      .title {
        font-size: 14px;
        line-height: 22px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-top: 5px;
      }
      p {
        font-size: 12px;
        line-height: 20px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        &.error {
          color: $mainColor;
        }
        &.price {
          margin-top: 2px;
        }
        &.matchPdf {
          display: flex;
        }
        .pdf {
          width: 16px;
          height: 20px;
          display: block;
          background: url("@/assets/img/pdf.svg") no-repeat left center;
          background-size: 14px auto;
        }
      }
      .el-input-number {
        height: 22px;
      }
    }
  }
  .product-li {
    background: #fff;
    border-radius: 8px;
    position: relative;
    padding: 7px 0px 12px 30px;
    a {
      align-items: center;
      padding-left: 0;
    }
    .check-wrap {
      width: 36px;
      min-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;
        min-width: 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;
      }
    }
  }
  :deep(.bomTitle span) {
    display: flex;
    width: max-content;
  }
}
.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: 888;
  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>