//呼叫視窗內觸發動畫用
new get().init();//css class前方要帶get
// 定義師資區ICON類組
const iconGroups = {
  main: ['fa-solid fa-thumbs-up', 'fas fa-book', 'fa-solid fa-headphones', 'fa-solid fa-bag-shopping'],
  alternative: ['fa-solid fa-thumbs-up', 'fa-solid fa-headphones', 'fa-solid fa-comment']
};
// 師資區遍歷每一組 .link_item 並插入ICON
function insertIcons(linkItem) {
  const liElements = $(linkItem).find('li');
  const links = $(linkItem).find('a');
  const iconClasses = liElements.length > 3 ? iconGroups.main : iconGroups.alternative;
  liElements.each((liIndex, li) => {
    const iconClass = iconClasses[liIndex];
    const link = links[liIndex];
    if (link && iconClass) {
      // 以純粹的 JavaScript 方法插入 ICON，保留原有的 <a> 元素
      const iconElement = document.createElement('i');
      iconElement.className = iconClass;
      link.prepend(iconElement);
    }
  });
}
const nextLabel = '<i class="fas fa-chevron-right fa-2x"></i>';
const prevLabel = '<i class="fas fa-chevron-left fa-2x"></i>';
// mobile置底隨機文字連結
const realData = [
  { name: '舊生回門禮', isHidden: false, url: 'https://www.get.com.tw/event/GOHOME/' },
  { name: '題分指導', isHidden: false, url: 'https://www.get.com.tw/event/WeaknessExam/' },
  // 添加更多的數據
];
//初始化 random_text 為空陣列
const random_text = [];
let isFirstLoading = true;
realData.forEach(data => {
  random_text.push({ url: data.url, loading: isFirstLoading, isHidden: false, data: data });
  isFirstLoading = false; // 設為 false，確保之後的 loading文字 都為 false
});

const appConfig = {
  el: "#vue_app",
  data: function() {
    return {
    year: 113,NextYear:114,ADyear:2024,ADNextYear:2025,//內頁年度共用值
    activetab: 1,//控制師資頁籤
    link: 0,//控制師資內顯示隱藏連結
    nvbar:0,//控制mobile橫選單顯示隱藏
    left_nav:0,//控制mobile對象選單顯示隱藏
    adtab:1,//所有內崁廣告頁tab切換專用
    student:1,//所有內崁廣告頁tab切換專用
    isHidden1: true,//廣告頁內崁專用
    isDivVisible: true,//控制浮動廣告區顯示隱藏
    carouselData: [],//讓caoursel資料儲存為空，改由json作用   
    randomIndex: 0, // 隨機選擇的索引 
    carouselLabels: { carousel1: { nextLabel: '<i class="fas fa-chevron-right fa-2x"></i>', prevLabel: '<i class="fas fa-chevron-left fa-2x"></i>' } },
    maxCarouselCount: 0,//初始carousel數量為0
    footerPadding:  "0",//footer預設與bottom的距離
    carouselResolutions: {}, // 新增一個對象儲存carousel的解析度    
    random_text:random_text,//mobile文字廣告
    };
  },
  computed: {
    filteredCarouselData() {
      // 將當前時間轉換為 ISO 格式的台灣時間
      const currentDateTime = new Date().toLocaleString("en-US", { timeZone: "Asia/Taipei" });
      const currentDateISO = new Date(currentDateTime).toISOString();
  
      return this.carouselData.map(item => {
        let display = true;
        if (typeof item.display !== 'undefined') {
          display = item.display;
        }
        if (item.slides && item.slides.length > 0) {
          item.slides.forEach(slide => {
            if (typeof slide.display !== 'undefined' && slide.display === false) {
              display = false;
            }
          });
        }  
        // 判斷是否在時間範圍內，將 startDate 和 endDate 視為 ISO 格式
        const inDateRange = (!item.startDate || !item.endDate || 
          (new Date(item.startDate).toISOString() <= currentDateISO &&
           currentDateISO <= new Date(item.endDate).toISOString()));
        display = display && inDateRange;
  
        return { ...item, display };
      }).filter(item => item.display);
    },
  },
  watch: {
    //監控師資區的連結顯示呼叫updateLinkItemWidth
    //   link(newLink) {
    //     this.updateLinkItemWidth();
    // },
  },
  methods: { 
    //監控師資區的連結顯示，li大於4個以上寬度25%，若否則33.33%寬度
    updateLinkItemWidth() {
    const linkItems = document.querySelectorAll('.link_item');
    linkItems.forEach((item) => {
    const liElements = item.querySelectorAll('li');
    const width = liElements.length > 3 ? '25%' : '33.33%';
    //const margin = liElements.length > 3 ? 'auto': '0 0.5rem';
    // 新增條件處理 link_item 的寬度
    //item.style.width = liElements.length > 3 ? '10rem' : '10rem';    
    //item.style.margin = '0 auto';
    liElements.forEach((li) => {
      li.style.width = width;
     // li.style.margin = margin;
        });
      });
    },
    //改變解析度時重新整理網頁，排除行動裝置
    handleResize: function() {
      this.updateFooterPadding();
      if (!this.isMobile) {
       // window.location.reload();
      }
    },
    closeDiv() {
      this.isDivVisible = false;//控制浮動廣告區顯示隱藏
      this.footerPadding = "0";//按鈕關閉後觸發footer與bottom距離0
    },
    updateFooterPadding() {
      const currentURL = window.location.href;    
      // URL目錄是否包含 "/event/、/posner/，可陣列增加"
      const excludedDirectories = ["/event/", "/posner/"];
      const shouldUpdateFooter = !excludedDirectories.some(directory => currentURL.toLowerCase().includes(directory));      
      if (shouldUpdateFooter) {
          // 只有在不是被排除的目录中才更新 footerPadding
          this.footerPadding = window.innerWidth < 1024 ? "4rem" : "0";
      }
    },  
    async randomTextAd() {
      // mobile文字廣告，非同步數據顯示，替換實際邏輯
      //await new Promise(resolve => setTimeout(resolve, 1000));
      // 隨機選擇一個連結
      const randomIndex = Math.floor(Math.random() * this.random_text.length);
      const selectedLink = this.random_text[randomIndex];
      // 更新選中連結，使用相同的數據
      this.$set(selectedLink, 'name', selectedLink.data.name);
      this.$set(selectedLink, 'loading', false);
      // 隱藏其他連結
      this.random_text.forEach((link, index) => {
        if (index !== randomIndex) {
          this.$set(link, 'isHidden', true);
        }
      });      
    },
  // 手動顯示輪播項目
  showSlide(index) {
    this.$set(this.carouselData[index], 'display', true);
  },
  // 手動隱藏輪播項目
  hideSlide(index) {
    this.$set(this.carouselData[index], 'display', false);
  }
  },
  mounted() {
    // 檢查是否在首頁-內網用
    const isHomePage = window.location.pathname === '/' || window.location.pathname === '/get/lawyer/'; 
    // 檢查是否在首頁-遠端用
    // const isHomePage = window.location.pathname === '/';   

    if (isHomePage) {
        axios.get('./file/js/carouselData.json?t=' + new Date().getTime())
            .then((response) => {
                this.carouselData = response.data.carouselData;
                // 隨機選擇輪播圖片並顯示
                this.carouselData.forEach(item => {
                    if (item.slides && Array.isArray(item.slides) && item.slides.length > 0) {
                        const randomIndex = Math.floor(Math.random() * item.slides.length);
                        item.link = item.slides[randomIndex].link;
                        item.imageSrc = item.slides[randomIndex].imageSrc;
                        item.startDate = item.slides[randomIndex].startDate;
                        item.endDate = item.slides[randomIndex].endDate;
                        item.alt = item.slides[randomIndex].alt;
                    }
                  //   if (item.display !== false && item.imageSrc && !item.imageSrc.includes('?t=')) {
                  //     item.imageSrc += '?t=' + new Date().getTime();
                  // }
                  //   console.log("驗證圖片後方加上參數:", item.imageSrc);
                });
                // mounted共用邏輯
                this.updateLinkItemWidth();
                $('.link_item:not(.Link_notset)').each((index, linkItem) => {
                    insertIcons(linkItem);
                });  
            })
            .catch(error => {
                console.error('讀取 JSON 數據時發生錯誤:', error);
            });
    }
    $(document).on("click", (event) => {
      // 如果點擊的元素不是`.headerbg, header, .left_navout, .tabVuecontent, #Vuetabs`之外的元素，則執行關閉操作
      if (!$(event.target).closest(".headerbg, header, .left_navout, .tabVuecontent, #Vuetabs").length) {
          this.nvbar = this.left_nav = this.link = 0;
      }
    });
    this.randomTextAd();
},  
  created() {
    //自動抓取所有carousel數量自動遞增
    const carousels = document.getElementsByTagName("carousel");
    this.maxCarouselCount = carousels.length; // 獲取carousel的數量
    for (let i = 1; i <= this.maxCarouselCount; i++) {
      this.carouselLabels[`carousel${i}`] = {
        nextLabel,
        prevLabel
      };
    }  
    this.updateFooterPadding(); // 初始化     
    // 宣告isMobile = 行動裝置類
    this.isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    // 解析度改變時事件監聽
    window.addEventListener("resize", this.handleResize);
    // 組件銷毀時，移除監聽，避免記憶體洩漏
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener("resize", this.handleResize);
    });
  },
  components: {
    'carousel': VueCarousel.Carousel,
    'slide': VueCarousel.Slide
  }
};
const app = new Vue(appConfig);