<template>
  <div class="main-box product product-new">
    <div class="banner"></div>
    <div class="breadcrumb-wrap">
      <div class="container">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item to="/">Home</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: `/newProduct/flq`, query: { sort: 2 } }">
            Discrete Components
          </el-breadcrumb-item>
          <el-breadcrumb-item>{{ pageName }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="product-list-wrap auto">
      <div class="top-con d-flex">
        <h3 class="page-title">{{ pageName }}</h3>
        <p>If you have any questions about the datasheet, please contact customer service.</p>

        <div class="search-wrap search-wrap2">
          <el-input v-model="searchCon" class="t15" placeholder="Search by model or package" @keyup.enter="searchLink" />
          <el-button class="el-search" @click="searchLink">Search</el-button>
        </div>
      </div>

      <div class="filter-wrap" v-if="false">
        <table width="100%" border="0" align="center" cellpadding="1" cellspacing="1" class="data">
          <thead>
            <tr>
              <template v-for="(v, i) in newTitle.dw" :key="i">
                <th v-if="newTopFilter[i]?.[0]">
                  {{ v }}
                </th>
              </template>
            </tr>
          </thead>

          <tbody>
            <tr>
              <template v-for="(v, i) in newTopFilter" :key="i">
                <td v-if="v?.[0]">
                  <el-input v-if="inpVal.length > 0" v-model="inpVal[i][1]" class="inp" disabled />
                  <el-slider v-model="inpVal[i]" :min="v[0]" :max="v[1]" :step="step" range vertical height="100px" @change="getSlider($event, i)" />
                  <el-input v-if="inpVal.length > 0" v-model="inpVal[i][0]" class="inp" disabled />
                </td>
              </template>
            </tr>
          </tbody>
        </table>

        <div class="filter-top"></div>
        <div class="filter-bottom"></div>
      </div>

      <div class="table-wrap">
        <table width="100%" border="0" align="center" cellpadding="1" cellspacing="1" class="data">
          <thead>
            <tr class="tr-header">
              <td rowspan="2">Model</td>
              <td rowspan="2">Image</td>
              <td rowspan="2">Package Type</td>
              <td rowspan="2">Datasheet</td>
              <template v-for="(v, i) in newTitle.title" :key="i">
                <td v-show="v?.length > 0">
                  <span>{{ v }}</span>
                </td>
              </template>
            </tr>

            <tr class="tr-header">
              <template v-for="(v, i) in newTitle.dw" :key="i">
                <td v-show="i < newTitle.title.length">
                  <span>{{ v }}</span>
                </td>
              </template>
            </tr>
          </thead>

          <tbody>
            <tr>
              <td>
                <el-select v-model="params.records[0].goodsType" class="t15" clearable style="width: 100px" @change="changePagination(1, 1)">
                  <el-option label="ALL" value="" />
                  <el-option v-for="item in newFilter.goodsType" :key="item" :label="item" :value="item" />
                </el-select>
              </td>

              <td></td>

              <td>
                <el-select v-model="params.records[0].packageSpecification" class="t15" clearable style="width: 100px" @change="changePagination(1, 1)">
                  <el-option label="ALL" value="" />
                  <el-option v-for="item in newFilter.packageSpecification" :key="item" :label="item" :value="item" />
                </el-select>
              </td>

              <td></td>

              <template v-for="(v, i) in newFilter.pp" :key="i">
                <td v-if="i < newTitle.title.length">
                  <el-select v-model="params.records[0][`attr${i + 1}`]" class="t15" clearable style="width: 100px" @change="changePagination(1, 1)">
                    <el-option label="ALL" value="" />
                    <el-option v-for="item in v" :key="item" :label="item" :value="item" />
                  </el-select>
                </td>
              </template>
            </tr>

            <tr v-for="(v, i) in newProductList" :key="i" class="tr-two">
              <td>{{ v.goodsType }}</td>
              <td>
                <img :src="v.img" width="45" />
              </td>
              <td>{{ v.packageSpecification }}</td>
              <td>
                <a v-if="v.manual" :href="v.manual" target="_blank">
                  <img src="@/assets/img/d.png" :alt="v.manual" style="margin-top:6px; width: 18px; min-width:18px;">
                </a>
              </td>

              <template v-for="(item, index) in newTitle.title" :key="index">
                <td v-show="item?.length > 0">
                  <span>{{ v[`attr${index + 1}`] }}</span>
                </td>
              </template>
            </tr>
          </tbody>
        </table>
      </div>

      <div v-if="newProductList.length" class="page-size">
        <el-pagination v-model:current-page="currentPage" :page-size="pageSize" :page-sizes="[30, 60, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="totalPage" @current-change="changePagination" @size-change="handleSizeChange" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useAll } from "~/api/pubAll/service";

interface TitleState {
  title: string[];
  dw: string[];
}

const route = useRoute();
const router = useRouter();
const { flqGoodsList, flqFindScope } = useAll();

const step = ref(0.1);
const searchCon = ref("");
const clickIdx = ref(1);

const pageName = computed(() => String(route.query.name || ""));
const routePage = computed(() => Number(route.query.page || 1));

const currentPage = ref(routePage.value);
const pageSize = ref(30);
const totalPage = ref(0);

const params = ref<any>({
  current: routePage.value,
  size: 30,
  records: [
    {
      categoryId: String(route.params.id || ""),
      goodsType: "",
      packageSpecification: "",
    },
  ],
});

const params2 = ref<any>({
  current: routePage.value,
  size: 30,
  records: [
    {
      categoryId: String(route.params.id || ""),
    },
  ],
});

const newProductList = ref<any[]>([]);
const newTitle = ref<TitleState>({
  title: [],
  dw: [],
});
const newFilter = ref<any>({
  goodsType: [],
  packageSpecification: [],
  pp: [[], [], [], [], [], [], [], [], [], []],
});
const newTopFilter = ref<any[]>([]);
const inpVal = ref<any[]>([]);

function normalizeNewProductResult(rawResult: any) {
  const raw = rawResult?.data?.data || rawResult?.data || rawResult || {};

  const titleState: TitleState = {
    title: [],
    dw: [],
  };

  if (raw?.typeHead2) {
    Object.keys(raw.typeHead2).forEach((key) => {
      if (key.includes("attr") && raw.typeHead2[key]?.length > 0) {
        titleState.title.push(raw.typeHead2[key]);
      }
    });
  }

  if (raw?.typeHead3) {
    Object.keys(raw.typeHead3).forEach((key) => {
      if (key.includes("attr")) {
        titleState.dw.push(raw.typeHead3[key]);
      }
    });
  }

  const filterState = {
    goodsType: [] as string[],
    packageSpecification: [] as string[],
    pp: [[], [], [], [], [], [], [], [], [], []] as any[],
  };

  if (raw?.SortData) {
    Object.keys(raw.SortData).forEach((key) => {
      if (key.includes("attr")) {
        const idx = Number(key.replace("attr", "")) - 1;
        filterState.pp[idx] = raw.SortData[key];
      }
    });

    filterState.goodsType = raw.SortData.goodsType || [];
    filterState.packageSpecification = raw.SortData.packageSpecification || [];
  }

  const topFilterState: any[] = [];
  if (raw?.page?.records?.[0]) {
    const first = raw.page.records[0];
    Object.keys(first).forEach((key) => {
      if (key.includes("attr") && first[key]) {
        topFilterState.push([
          parseFloat(first[key].smallAttr),
          parseFloat(first[key].maxAttr),
        ]);
      }
    });
  }

  return {
    list: raw?.page?.records || [],
    total: raw?.page?.total || 0,
    titleState,
    filterState,
    topFilterState,
  };
}

function cleanRecord(record: Record<string, any>) {
  const next = { ...record };
  Object.keys(next).forEach((key) => {
    if (next[key] === "") {
      delete next[key];
    }
  });
  return next;
}

async function loadDefaultList() {
  clickIdx.value = 1;

  const req = {
    ...params.value,
    records: [cleanRecord(params.value.records[0])],
  };

  const result = await flqGoodsList(req);
  const normalized = normalizeNewProductResult(result);

  newProductList.value = normalized.list;
  totalPage.value = normalized.total;
  newTitle.value = normalized.titleState;
  newFilter.value = normalized.filterState;
  newTopFilter.value = normalized.topFilterState;
  inpVal.value = JSON.parse(JSON.stringify(normalized.topFilterState));
}


async function loadScopeList() {
  const record: Record<string, any> = {
    categoryId: String(route.params.id || ""),
  };

  inpVal.value.forEach((item, index) => {
    record[`attr${index + 1}`] = {
      maxAttr: item?.[1] || "",
      smallAttr: item?.[0] || "",
    };
  });

  const req = {
    ...params2.value,
    records: [record],
  };

  const result = await flqFindScope(req);
  const normalized = normalizeNewProductResult(result);

  newProductList.value = normalized.list;
  totalPage.value = normalized.total;
  newTitle.value = normalized.titleState;
  newFilter.value = normalized.filterState;
  newTopFilter.value = normalized.topFilterState;
}

await loadDefaultList();

useHead({
  title: "Schottky Diodes - Zener Diodes - Fast Recovery Diodes - Shenzhen Hotking Electronics Co., Ltd.",
  meta: [
    {
      name: "description",
      content:
        "Provides detailed package, model, and parameter information for Hotking discrete components, along with PDF downloads, including Schottky diodes, Zener diodes, TVS diodes, switching diodes, fast recovery diodes, MOSFETs, transistors, bridge rectifiers, and integrated circuits.",
    },
    {
      name: "keywords",
      content:
        "Schottky diode, Zener diode, fast recovery diode, MOSFET, TVS diode, ESD diode, PNP transistor, bridge rectifier",
    },
  ],
});

function searchLink() {
  if (!searchCon.value) return;

  router.push({
    path: `/cproducts/${route.params.cid}/${route.params.id}`,
    query: {
      page: "1",
      seekType: "2",
      sort: "2",
      con: searchCon.value,
      name: pageName.value,
    },
  });
}

async function getSlider(val: number[], index: number) {
  inpVal.value[index] = val;

  await router.push({
    path: `/newProduct/${route.params.cid}/${route.params.id}`,
    query: {
      page: String(params2.value.current),
      name: pageName.value,
    },
  });

  params.value = {
    current: Number(route.query.page || 1),
    size: pageSize.value,
    records: [
      {
        categoryId: String(route.params.id || ""),
        goodsType: "",
        packageSpecification: "",
      },
    ],
  };

  params2.value.current = 1;
  params.value.current = 1;
  currentPage.value = 1;
  clickIdx.value = 2;

  await loadScopeList();
}

async function handleSizeChange(size: number) {
  pageSize.value = Number(size);

  if (clickIdx.value === 1) {
    params.value.size = Number(size);

    await router.push({
      path: `/newProduct/${route.params.cid}/${route.params.id}`,
      query: {
        page: String(params.value.current),
        name: pageName.value,
      },
    });

    await loadDefaultList();
  } else {
    params2.value.size = Number(size);
    await loadScopeList();
  }
}

async function changePagination(page: number, type?: number) {
  if (type === 1) {
    clickIdx.value = 1;
  }

  if (clickIdx.value === 1) {
    params.value.current = Number(page);
    currentPage.value = Number(page);

    await router.push({
      path: `/newProduct/${route.params.cid}/${route.params.id}`,
      query: {
        page: String(params.value.current),
        name: pageName.value,
      },
    });

    await loadDefaultList();
  } else {
    params2.value.current = Number(page);
    currentPage.value = Number(page);
    await loadScopeList();
  }
}

watch(
  () => route.query.page,
  (val) => {
    currentPage.value = Number(val || 1);
  }
);
</script>

<style scoped lang="scss">
/* 旧样式直接搬过来即可，这里先留空 */
.product-list-wrap {
  margin: 0 auto;
  width: 90%;
  max-width: 1600px;
  .tr-two {
    img {
      margin: 0 auto;
    }
  }
  table {
    border-collapse: collapse;
    border-spacing: 0;
  }
}
.product-new .page-size {
  display: flex;
  justify-content: flex-end;
}
</style>
