// 載入共用 template
$('#navbar').load('../../template/navbar.html');
$('#footer').load('../../template/footer.html');
$('#btn-box').load('../../template/button.html');
$('#topCarousel').load('../../template/top_carousel.html');

let assignOrder = ""; // 當前排序

// new, hot, recommend 排序 (預設推薦)
$(".search-btn-filter button").click(function () {
  // 切換選取狀態
  $('.search-btn-filter').find('.active').removeClass('active');
  $(this).addClass('active');
  assignOrder = $(this).attr('id');
  dataSearch();
});

let page = 1; // 當前頁數
let pageSize = 18; // 每頁數量
let isFirstLoad = true; // 初始載入

let assignTab = "caseTab"; // 指定類別 (預設為空間靈感)

// 列表篩選
async function dataSearch(type = "") {
  let url;
  $('#dataSpinner').show();
  $('#dataList').hide();

  switch (assignTab) {
    case "caseTab":
      url = `https://m3.hhh.com.tw:18673/case_search?page=${page}&page_size=${pageSize}`;
      break;

    case "designerTab":
      url = `https://m3.hhh.com.tw:18673/designer_search?page=${page}&page_size=${pageSize}`;
      break;

    case "videoTab":
      url = `https://m3.hhh.com.tw:18673/video_search?page=${page}&page_size=${pageSize}`;
      break;

    case "columnTab":
      url = `https://m3.hhh.com.tw:18673/column_search?page=${page}&page_size=${pageSize}`;
      break;

    case "builderTab":
      url = `https://m3.hhh.com.tw:18673/builder_search?page=${page}&page_size=${pageSize}`;
      break;

    default:
      break;
  }

  let input = $(".keywords").val();

  if (input !== "") {
    let isExist = filterList.some((item) => item.id === "keyword"); // 判斷是否已存在關鍵字

    const newItem = {
      id: "keyword",
      text: "關鍵字",
      value: input
    };

    if (!isExist) {
      filterList.push(newItem);
      createFilterHtml(newItem);
    } else {
      // 移除原本關鍵字
      $('.budget p.me-1').each(function () {
        if ($(this).text().includes('關鍵字')) {
          $(this).closest('.me-3').remove();
        }
      });

      if (filterList.length === 0) {
        $('#removeResultBtn').hide();
      }

      filterList = filterList.filter(item => item.text !== "關鍵字");

      filterList.push(newItem);
      createFilterHtml(newItem);

    }
    $(".keywords").val("")
  }

  if (filterList.length) {
    filterList.map(item => {
      if (item.id === "fee") {
        // 裝修預算
        switch (item.value) {
          case "100萬以下":
            url += `&${item.id}=1`;
            break;
          case "101~200萬":
            url += `&${item.id}=2`;
            break;
          case "201~300萬":
            url += `&${item.id}=3`;
            break;
          case "301萬以上":
            url += `&${item.id}=4`;
            break;

          default:
            break;
        }
      } else if (item.id === "area") {
        // 房屋坪數
        switch (item.value) {
          case "20坪以下":
            url += `&${item.id}=1`;
            break;
          case "21-30坪":
            url += `&${item.id}=2`;
            break;
          case "31-50坪":
            url += `&${item.id}=3`;
            break;
          case "51坪以上":
            url += `&${item.id}=4`;
            break;

          default:
            break;
        }
      } else if (item.id === 'budget') {
        switch (item.value) {
          case "100萬以下":
            url += `&${item.id}=1`;
            break;
          case "100~200萬":
            url += `&${item.id}=2`;
            break;
          case "200~300萬":
            url += `&${item.id}=3`;
            break;
          case "300~400萬":
            url += `&${item.id}=4`;
            break;
          case "400~500萬":
            url += `&${item.id}=5`;
            break;
          case "500萬以上":
            url += `&${item.id}=6`;
            break;
          default:
            break;
        }
      } else {
        url += `&${item.id}=${item.value}`;
      }
    });
  }

  // 排序
  if (assignOrder === "") {
    // 預設
    if (assignTab === "designerTab") {
      url += "&order_by=recommend";
    } else {
      url += "&order_by=new";
    }
  } else {
    url += `&order_by=${assignOrder}`;
  }

  try {
    let isExist = filterList.some((item) => item.id === "keyword"); // 判斷是否已存在關鍵字

    if (isExist) {
      getAllSearchCount(); // 重新取得總筆數
    }

    const response = await axios.get(url);

    let totalCount = response.data.total_count;
    let totalPages = Math.ceil(totalCount / pageSize);

    if (totalPages) {
      $('.filter-list .pagination').show();
      setPagination(totalPages); // 分頁處理
    } else {
      $('.filter-list .pagination').hide();
    }

    let resultHtml = '';

    switch (assignTab) {
      case "caseTab":
        if (response.data.cases.length) {
          response.data.cases.forEach((item) => {
            let tagList = item.CaseTag.split(',');
            let tagsHtml = '';

            tagList.forEach((tag) => {
              if (tag !== "") {
                tagsHtml += `<span class="tag-item" data-tag="${tag}">${tag}</span>`;
              }
            });

            resultHtml += `
              <div class="col-md-4 mb-4">
                <a href="${item.DesignerLink}">
                  <div class="card lists-card">
                    <img src="${item.CaseCoverImg}" class="cover-img" alt="${item.DesignerName} ${item.DesignerTitle}">
                      <div class="card-body d-flex flex-column">
                        <div class="d-flex align-items-center">
                          <div class="person-img me-3 me-md-2 me-lg-3" style="background-image: url('${item.DesignerCoverImg}');"></div>
                          <section>
                            <h5 class="text-muted mb-2">${item.DesignerTitle}</h5>
                            <h6 class="mb-0 text-dark">
                              <span class="font-weight-bold">
                                ${item.DesignerName}
                              </span>
                              設計師
                            </h6>
                          </section>
                        </div>
                        <p class="mt-3 text-dark title">${item.CaseTitle}</p>
                        <div class="tags-container my-3 me-auto">${tagsHtml}</div>
                        <small class="d-block ms-auto mt-auto date-item">上架日期 ${item.CaseSdate}</small>
                      </div>
                  </div>
                </a>
              </div>`;
          });
        } else {
          resultHtml += "<p class='text-center mt-5'>找不到符合的資料，請重新搜尋。</p>"
        }

        let caseCount = response.data.total_count.toLocaleString();
        setTimeout(() => {
          $("#caseCount").html(`(${caseCount})`);
        }, 100)

        break;

      case "designerTab":
        if (response.data.designers.length) {
          response.data.designers.forEach((item) => {
            resultHtml += `
            <div class="col-md-4 mb-4">
              <a href="${item.DesignerLink}">
                <div class="card lists-card">
                  <img src="${item.CaseCoverImg}" class="cover-img" alt="${item.DesignerName} ${item.DesignerTitle}">
                    <div class="card-body d-flex align-items-center">
                      <div class="person-img me-3 me-md-2 me-lg-3" style="background-image: url('${item.DesignerCoverImg}');"></div>
                      <section>
                        <h5 class="text-muted mb-2">${item.DesignerTitle}</h5>
                        <h6 class="mb-0 text-dark">
                          <span class="font-weight-bold">
                            ${item.DesignerName}
                          </span>
                          設計師
                        </h6>
                      </section>
                    </div>
                </div>
              </a>
            </div>`;
          });
        } else {
          resultHtml += "<p class='text-center mt-5'>找不到符合的資料，請重新搜尋。</p>"
        }

        let designerCount = response.data.total_count.toLocaleString();
        setTimeout(() => {
          $("#designerCount").html(`(${designerCount})`);
        }, 100)

        break;

      case "videoTab":
        if (response.data.videos.length) {
          response.data.videos.forEach((item) => {
            let tagsHtml = '';

            item.VideoTag.forEach((tag) => {
              if (tag !== "") {
                tagsHtml += `<span class="tag-item" data-tag="${tag}">${tag}</span>`;
              }
            });

            resultHtml += `
            <div class="col-md-4 mb-4">
              <a href="${item.DesignerLink}">
                <div class="card lists-card">
                  <img src="${item.VideoCoverImg}" class="video-cover-img" alt="${item.DesignerName} ${item.DesignerTitle}">
                    <div class="card-body d-flex flex-column align-items-center">
                      <section class="d-flex align-items-center w-100">
                        <div class="person-img me-3 me-md-2 me-lg-3" style="background-image: url('${item.DesignerCoverImg}');"></div>
                        <h5 class="text-muted mb-2">${item.DesignerTitle}</h5>
                      </section>
                      <h3 class="my-3 video-title">${item.VideoTitle}</h3>
                      <div class="tags-container mt-2 me-auto">${tagsHtml}</div>
                    </div>
                </div>
              </a>
            </div>`;
          });
        } else {
          resultHtml += "<p class='text-center mt-5'>找不到符合的資料，請重新搜尋。</p>"
        }

        let videoCount = response.data.total_count.toLocaleString();
        setTimeout(() => {
          $("#videoCount").html(`(${videoCount})`);
        }, 100)

        break;

      case "columnTab":
        if (response.data.columns.length) {
          // 取得當前日期並計算三天前的日期
          const currentDate = new Date();
          const threeDaysAgo = new Date();
          threeDaysAgo.setDate(currentDate.getDate() - 3);

          response.data.columns.forEach((item, index) => {
            // 將 ColumnDate 轉換成日期物件
            const columnDate = new Date(item.ColumnDate);

            // 判斷 ColumnDate 是否在三天內
            const isNew = columnDate >= threeDaysAgo && columnDate <= currentDate;

            const newItemClass = isNew ? '' : 'd-none'; // 非三天內則隱藏 New 標籤

            let tagList = item.ColumnTag.split(',');
            let tagsHtml = '';

            tagList.forEach((tag) => {
              if (tag !== "") {
                tagsHtml += `<span class="tag-item" data-tag="${tag}">${tag}</span>`;
              }
            });

            resultHtml += `
              <div class="col-md-4 mb-4">
                <a href="${item.ColumnLink}">
                  <div class="card lists-card h-auto">
                    <img src="${item.ColumnCoverImg}" class="cover-img" alt="${item.ColumnTitle}">
                      <div class="card-body d-flex flex-column">
                        <h5 class="text-dark title">${item.ColumnTitle}</h5>
                        <div class="tags-container columns-tag mt-3 me-auto">${tagsHtml}</div>
                      </div>
                      <span class="new-item ${newItemClass}">NEW</span>
                  </div>
                </a>
              </div>`;
          });

          $('#dataList').append(resultHtml);
        } else {
          resultHtml += "<p class='text-center mt-5'>找不到符合的資料，請重新搜尋。</p>"
        }

        let columnCount = response.data.total_count.toLocaleString();
        setTimeout(() => {
          $("#columnCount").html(`(${columnCount})`);
        }, 100)

        break;

      case "builderTab":
        if (response.data.videos.length) {
          response.data.videos.forEach((item) => {
            resultHtml += `
              <div class="col-md-4 mb-4">
                <a href="${item.DesignerLink}">
                  <div class="card lists-card">
                    <div class="position-relative">
                      <img src="../../img/icon/play.svg" class="play-img${item.Is_video === '0' ? ' d-none' : ''}" alt="play-img">
                        <img src="${item.BuilderCoverImg}" class="cover-img" alt="${item.BuilderTitle}">
                        </div>
                        <div class="card-body p-4">
                          <section>
                            <h5 class="text-dark">${item.BuilderTitle}</h5>
                            <p class="text-dark my-3">${item.BuilderDescr}</p>
                            <h6 class="mb-0 text-muted fw-normal">
                              ${item.BuilderAddress}
                            </h6>
                          </section>
                        </div>
                    </div>
                </a>
              </div>`;
          });
        } else {
          resultHtml += "<p class='text-center mt-5'>找不到符合的資料，請重新搜尋。</p>"
        }

        let builderCount = response.data.total_count.toLocaleString();
        setTimeout(() => {
          $("#builderCount").html(`(${builderCount})`);
        }, 100)

        break;

      default:
        break;
    }

    // if (response.data.videos.length) {
    //   response.data.videos.forEach((item) => {
    //     resultHtml += `
    //       <div class="col-md-4 mb-4">
    //         <a href="${item.DesignerLink}">
    //           <div class="card lists-card">
    //             <div class="position-relative">
    //               <img src="../../img/icon/play.svg" class="play-img${item.Is_video === '0' ? ' d-none' : ''}" alt="play-img">
    //                 <img src="${item.BuilderCoverImg}" class="cover-img" alt="${item.BuilderTitle}">
    //                 </div>
    //                 <div class="card-body p-4">
    //                   <section>
    //                     <h5 class="text-dark">${item.BuilderTitle}</h5>
    //                     <p class="text-dark my-3">${item.BuilderDescr}</p>
    //                     <h6 class="mb-0 text-muted fw-normal">
    //                       ${item.BuilderAddress}
    //                     </h6>
    //                   </section>
    //                 </div>
    //             </div>
    //         </a>
    //       </div>`;
    //   });
    // } else {
    //   resultHtml += "<p class='text-center mt-5'>找不到符合的資料，請重新搜尋。</p>"
    // }

    $('#dataList').html(resultHtml);

    setTimeout(() => {
      setTotalCount();
      $('#dataList').show();
      $('#dataSpinner').hide();
    }, 100)

    // 更新初始載入狀態
    if (isFirstLoad) {
      isFirstLoad = false;
    }
  } catch (error) {
    console.log("error", error);
  }
}

dataSearch();

// 取得全部符合筆數
async function getAllSearchCount() {
  let url = "https://m3.hhh.com.tw:18673/all_search_count";

  if (filterList.length) {
    let input;

    // 取得關鍵字
    filterList.find((item) => {
      if (item.id === "keyword") {
        input = item.value;

        if (input !== "") {
          url += `?keyword=${input}`
        }
      }
    });
  }

  try {
    const response = await axios.get(url);

    $("#caseCount").text(`(${response.data.case_count.toLocaleString()})`)
    $("#designerCount").text(`(${response.data.designer_count.toLocaleString()})`)
    $("#videoCount").text(`(${response.data.video_count.toLocaleString()})`)
    $("#columnCount").text(`(${response.data.column_count.toLocaleString()})`)
    $("#builderCount").text(`(${response.data.builder_count.toLocaleString()})`)

    // 數量加總
    let total = response.data.designer_count + response.data.column_count + response.data.case_count + response.data.builder_count + response.data.video_count;

    $('#totalCount').text(total.toLocaleString());

  } catch (error) {
    console.log("error", error);
  }
}

getAllSearchCount();

// 計算總筆數
function setTotalCount() {
  // 將各類別總筆數轉為數字
  let caseCount = parseInt($('#caseCount').text().replace(/[(),]/g, ''), 10);
  let designerCount = parseInt($('#designerCount').text().replace(/[(),]/g, ''), 10);
  let videoCount = parseInt($('#videoCount').text().replace(/[(),]/g, ''), 10);
  let columnCount = parseInt($('#columnCount').text().replace(/[(),]/g, ''), 10);
  let builderCount = parseInt($('#builderCount').text().replace(/[(),]/g, ''), 10);

  // 將各個數字相加
  let total = caseCount + designerCount + videoCount + builderCount + columnCount;
  $('#totalCount').text(total.toLocaleString());
}

// 切換 Tab
$('.search-tab-list .nav-item').click(function (e) {
  // getAllSearchCount(); // 重新取得總筆數

  let isExist = filterList.some((item) => item.id === "keyword"); // 判斷是否已存在關鍵字

  if (!isExist) {
    getAllSearchCount(); // 重新取得總筆數
  }

  // 使用 closest() 找到最近的 button 元素
  let button = $(e.target).closest('button');
  assignTab = button.attr('id');

  if (assignTab === "designerTab") {
    $('.search-btn-filter').find('.active').removeClass('active');
    $("#recommend").addClass('active');
    $("#recommendItem").show();
  } else {
    $('.search-btn-filter').find('.active').removeClass('active');
    $("#new").addClass('active');
    $("#recommendItem").hide();
  }

  // 需保留關鍵字，其餘條件全部清除
  if (isExist) {
    filterList = filterList.filter(item => item.text === "關鍵字");
    // 刪除關鍵字以外的條件
    $('.search-tab-result span.me-3').each(function () {
      if (!$(this).find('p').text().includes('關鍵字')) {
        $(this).remove();
      }
    });

  } else {
    filterList.length = 0; // 清空篩選陣列
    $('#removeResultBtn').hide(); // 隱藏全部清除按鈕
    $('.search-tab-result').empty(); // 清空篩選條件 dom
  }


  // 全部清除
  $('.keywords').val(''); // 清空搜尋欄位
  // 取消選取狀態
  $('.filter-list input[type="radio"]').prop('checked', false);
  $('.search-tab').removeClass('active');

  dataSearch(); // 篩選
});

// 次要類別選單
let subCategory = [
  {
    title: "編輯精選",
    list: ["居家趨勢", "人氣排行", "建築設計", "風格選店", "公益活動", "展演資訊"]
  },
  {
    title: "居家設計",
    list: ["小宅規劃", "老屋翻新", "風格營造", "配色佈置", "好宅特輯", "設計提案"]
  },
  {
    title: "裝修前線",
    list: ["新聞最前線", "預算分配", "施工流程", "建材知識", "裝潢撇步"]
  },
  {
    title: "生活PLUS",
    list: ["居家風水", "家事清潔", "收納技巧", "改造修繕", "退休好幸福"]
  },
  {
    title: "品牌好物",
    list: ["家具家飾", "美型家電", "推薦廚衛", "居家好物", "優質建材", "品牌新訊"]
  },
  {
    title: "房市焦點",
    list: ["房市新聞", "建案特搜", "買屋賣屋", "房貸稅務", "租房須知"]
  }
];

// 專欄文章分類
$("#pills-column #mainCategory .form-check").click(function (e) {
  let btnText = $(e.target).text().replace(/\s+/g, ''); // 取得主分類

  // 檢查陣列中是否有次分類
  let hasSubCategory = filterList.find(item => item.text === "次分類");

  if (hasSubCategory) {
    // 如果有則移除包含該 DOM 元素
    $('span.budget:contains("次分類")').closest('span.me-3').remove();
    filterList = filterList.filter(item => item.text !== "次分類");
  }

  let subHtml = [];

  subCategory.map(item => {
    if (item.title === btnText) {
      item.list.forEach(item => {
        let dom = `
          <li onclick="clickSubBtn(event, '${item}')">
            <div class="form-check">
              <input class="form-check-input" type="radio" name="sub_type">
                <label class="form-check-label">
                  ${item}
                </label>
            </div>
          </li>`;
        subHtml.push(dom);
      })

      $('#subCategory ul').html(subHtml);
    }
  })

  $("#subCategory").show();
})

function clickSubBtn(e, item) {
  let currentElement = $(e.currentTarget);

  currentElement.find('.form-check-input').prop('checked', true);

  // 取得 radio 按鈕的 label
  let radioLabel = currentElement.find('.form-check-label').text().trim().replace(/\s+/g, ' '); // 移除換行空白

  // 取上一層 search-tab 按鈕文字
  let buttonValue = currentElement.closest('.dropdown').find('.search-tab').text().trim();
  let buttonId = currentElement.closest('.dropdown').find('.search-tab').attr('id');

  updateSelectedOptions(buttonId, buttonValue, radioLabel);
}