<template>
  <div class="boxs-bg">
    <div class="bom-wrap">
      <div class="title">BOM专家，一键下单</div>
      <div class="bom-nav">
        <div class="nav-item">
          <img src="@/assets/img/bom/bom-1.png" width="50" v-show="isLoad">
          <p>海量现货库存，一站式配单，一键自动</p>
        </div>
        <div class="nav-item">
          <img src="@/assets/img/bom/bom-2.png" width="50" v-show="isLoad">
          <p>智能推荐，优先保证现货与低价，省时省力</p>
        </div>
        <div class="nav-item">
          <img src="@/assets/img/bom/bom-3.png" width="50" v-show="isLoad">
          <p>随意切换搜索条件，快速同步匹配结果</p>
        </div>
        <div class="nav-item">
          <img src="@/assets/img/bom/bom-4.png" width="50" v-show="isLoad">
          <p>参数智能选型，AI深度学习IDPE/ISPE引擎</p>
        </div>
      </div>

      <van-tabs v-model:active="active" class="mt20">
        <van-tab title="BOM表格上传">
          <div class="fileUpload">
            <div class="btn">
              <input ref='file' type="file" id="file" class="fileExcel" name="file" @change="upfiles" accept="" style="visibility: hidden; width: 0px; height: 0px;">
              <label for="file">{{text}}</label>
            </div>
            <a class="down" href="javascript:;" @click="download">下载BOM标准模板 提升选型准确率</a>
          </div>
          <div class="bom-tip">
            <h3>说明：</h3>
            <p>1、为保证准确性，请下载BOM模板；</p>
            <p>2、复制并粘贴数据到模板中，并将文件保存为xls/xlsx/csv格式；</p>
            <p>3、点击上侧的“上传BOM文件”按钮上传文件；</p>
            <p>4、文件大小必须在5M以内，上传数据不能超过20条；</p>
          </div>
        </van-tab>
        <van-tab title="手动输入型号或参数">
          <textarea v-model="textareVal" placeholder="可手动输入型号或粘贴到此处示例：
RI0603L103JT     100
LL4148     20
SMAJ5.0A     300" id="textare"></textarea>
          <a href="javascript:;" class="pBtn" @click="bomBtn">立即配单</a>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Search } from "@element-plus/icons-vue";
let pageTitle: any = ref("HOTKING-BOM配单");
import { showLoadingToast, closeToast } from "vant";
import { useAll } from "~/api/pubAll/service";
const { bomQuery } = useAll();
useHead(() => ({
  title: pageTitle.value,
}));
let textareVal: any = ref("");
const active = ref(0);
const nuxtApp = useNuxtApp();
const isClient = !nuxtApp.ssrContext;
let isLoad: any = ref(false);
onMounted(() => {
  isLoad.value = true;
});
let file: any = ref("");
let text: any = ref("上传BOM文件");
async function upfiles(e: any) {
  file.value = e.target.files[0];

  if (!file.value) {
    return ElMessage.error("请上传模板文件");
  }

  const toast = showLoadingToast({
    message: "文件上传解析中...",
    forbidClick: true,
    zIndex: 3000,
    className: "my-custom-toast",
    duration: 0,
  });

  text.value = "文件上传解析中...";

  const formData = new FormData();
  formData.append("file", file.value);
  formData.append("language", 1);
  const isLogin: any = useCookie("tokenKey");
  try {
    // ⭐ Nuxt3 用 $fetch 时，不能直接传 FormData 要用 body
    const res: any = await $fetch(
      `${useRuntimeConfig().public.apiBase}/shop/bom/importBomExcel`,
      {
        method: "POST",
        body: formData,
        headers: {
          "access-token": isLogin.value || "",
          // ❗ $fetch 会自动处理 multipart，不要写 Content-Type，否则会报 boundary 错误
          // "Content-Type": "multipart/form-data"
        },
      }
    );

    toast.close();

    if (res.httpCode == 200) {
      text.value = "上传BOM文件";
      if (res.data) {
        localStorage.setItem("excelList", JSON.stringify(res.data));
        navigateTo({
          path: "/match",
          query: { type: 2 },
        });
      } else {
        ElMessageBox.alert(
          "上传成功，识别到BOM不是标准模板，需人工配单！为提升选型准确率，建议您下载页面BOM标准模板",
          "提示",
          { confirmButtonText: "确定" }
        );
      }
    } else {
      text.value = "上传BOM文件";
      ElMessage.error(res.message);
    }

    // 清空 file input
    e.target.value = "";
  } catch (err: any) {
    toast.close();
    text.value = "上传BOM文件";
    ElMessage.error("上传失败，请稍后再试");
  }
}

function download() {
  let obj = {
    method: "get",
    url: `${useRuntimeConfig().public.apiBase}/bom/downloadExcel`,
    fileName: `bom查询模板导出`,
    params: "",
  };
  exportMethod(obj); // 模板导出
}

let params: any = ref([]);
function bomBtn() {
  params.value = [];
  if (textareVal.value) {
    let attrs = textareVal.value.replace(/[\r\n]/g, ",");
    let attr = attrs.split(",");

    for (let i = 0; i < attr.length; i++) {
      if (attr[i].trim().length > 0) {
        let idx = attr[i].trim().lastIndexOf(" ");
        let num = attr[i].trim().substr(idx + 1);
        let materialSn = attr[i].substr(0, idx);
        let re = /^[0-9]+.?[0-9]*$/;
        params.value.push({
          materialSn: materialSn,
          num: num,
          language: "1",
        });
      }
    }
    bomCopyAjax(params.value);
  } else {
    return ElMessage.error("请输入对应的格式");
  }
}
async function bomCopyAjax(arry: any) {
  const toast = showLoadingToast({
    message: "配单中...",
    forbidClick: true,
    zIndex: 3000,
    className: "my-custom-toast",
    duration: 0,
  });
  localStorage.setItem("bomparams", JSON.stringify(arry));
  let res: any = await bomQuery(arry);
  toast.close();
  if (res.httpCode == 200) {
    localStorage.setItem("excelList", JSON.stringify(res.data));
    navigateTo({
      path: "/match",
      query: {
        type: 1,
      },
    });
  }
}
</script>
<style scoped lang="scss">
.boxs-bg {
  background-color: #f7f7f7;
}
.bom-wrap {
  min-height: calc(100vh - 44px);
  background: linear-gradient(180deg, $mainColor, hsla(0, 0%, 100%, 0) 270px);
  padding: 12px 0;
  .title {
    font-size: 16px;
    font-weight: bold;
    color: #fff;
    text-align: center;
  }
  .bom-nav {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .nav-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 48%;
      min-width: 48%;
      margin-top: 18px;
      font-size: 12px;
      img {
        margin-bottom: 8px;
      }
      p {
        text-align: center;
        padding: 0 25px;
      }
    }
  }
  .fileUpload {
    text-align: center;
    background: #fff url("@/assets/img/bom/bom-icon.png") no-repeat top 25px
      center;
    background-size: 94px 94px;
    border: 1px solid #0067ed;
    padding: 1px 12px 0;
    height: 240px;
    margin: 12px;
    border-radius: 4px;
    p {
      text-align: center;
    }

    .btn {
      text-align: center;
      margin-bottom: 11px;
      margin-top: 140px;
      display: block;

      label {
        background: #ff8a14;
        height: 40px;
        line-height: 40px;
        border: 1px solid #ff8a14;
        border-radius: 4px;
        text-align: center;
        color: #fff;
        font-size: 14px;
        display: inline-block;
        width: 150px;
        box-shadow: 0 3px 8px 0 rgba(255, 138, 20, 0.3);
        cursor: pointer;

        &:hover {
          background: #f38517;
        }
      }
    }

    .down {
      text-decoration: underline !important;
      font-size: 12px;
      display: block;
    }
  }
  .bom-tip {
    font-size: 12px;
    color: #666;
    padding: 0 12px;
    line-height: 20px;
    h3 {
      font-size: 14px;
      color: #333;
      margin-bottom: 0;
      padding-left: 0;
      font-weight: bold;
    }
  }

  textarea {
    display: block;
    margin: 12px;
    width: calc(100% - 24px);
    resize: unset;
    padding: 12px;
    font-size: 14px;
    height: 296px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    outline: none;
    font-family: "\5FAE\8F6F\96C5\9ED1";
    color: #5c5c5c;
    line-height: 24px;
  }
  .pBtn {
    background: #ff8a14;
    border-color: #ff8a14;
    border-radius: 4px;
    height: 40px;
    line-height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 12px;
    color: #fff;

    &:hover {
      background: #f38517;
    }
  }
}
</style>