import { defineStore, } from 'pinia';
import axios from "axios";

export const useMainStore = defineStore('mainStore', {
  state: () => ({
    apiUrl: import.meta.env.VITE_API_URL,
    imgUrl: import.meta.env.VITE_API_IMG_URL,
    count: 0,
    token: "",
    authToken: "", // 藝文中心 Token
    loginState: false, // 登入狀態
    loginDialog: false, // 登入視窗
    profile: {}, // 使用者資訊
    mocProfile: {}, // 藝文中心使用者資訊
    mapLocation: { // 地圖經緯度
      lat: "",
      lng: ""
    },
    favoritesList: [],
    userInfo: {}
  }),
  getters: {
    isMobile: () => {
      // 判斷是否為手機裝置
      return /Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
        window.navigator.userAgent
      );
    },
  },
  actions: {
    // 檢查登入狀態
    // checkToken() {
    //   const token = localStorage.getItem('token');
    //   console.log('checkToken', token);
    //   if (token) {
    //     this.token = token;
    //     this.loginState = true;
    //   } else {
    //     this.token = null;
    //     this.loginState = false;
    //   }

    //   return this.loginState;
    // },
    // 檢查登入狀態
    checkToken() {
      console.log('檢查登入狀態');
      const token = sessionStorage.getItem("token");
      const authToken = sessionStorage.getItem("AuthToken");

      if (token && authToken) {
        this.token = token;
        this.authToken = authToken;
        this.loginState = true;
      } else {
        console.log('沒有通過');
        this.token = null;
        this.authToken = null;
        this.loginState = false;
        this.handleAuthToken();
      }
      return this.loginState;
    },
    // 判斷網址是否有 AuthCode 參數
    async handleAuthToken() {
      console.log('handleAuthToken');
      const queryParams = this.getURLParams();
      const authToken = sessionStorage.getItem("AuthToken");
      console.log('判斷網址是否有 AuthCode 參數', queryParams.AuthCode);
      if (queryParams.AuthCode) {
        console.log('authToken', authToken);
        // 帶 AuthCode 取 AuthToken
        if (authToken === null || authToken === "undefined" || !authToken) {
          await this.getAuthToken(queryParams.AuthCode);
        }
      } else {
        console.log('沒有 AuthCode');
        return;
      }

      if (authToken !== null || authToken !== "undefined") {
        // this.loginState = true;
        console.log('取藝文中心會員資料');
        this.getMocProfile(); // 取藝文中心會員資料
      }
    },
    async getAuthToken(authCode) {
      console.log('getAuthToken 測試');
      // let url = `https://craftsplatform.ntcri.gov.tw/api/get_authtoken?authCode=${authCode}`;
      let url = `${this.apiUrl}/api/get_authtoken?authCode=${authCode}`;

      try {
        const response = await axios.post(url);
        console.log('取得 AuthToken', response);
        if (response.data.authToken) {
          console.log('有 AuthToken');
          this.loginState = true;
          this.authToken = response.data.authToken;
          sessionStorage.setItem("AuthToken", response.data.authToken);
          console.log('this.authToken', this.authToken);
        }
      } catch (error) {
        console.error(error);
      }
    },
    // 取得藝文中心會員資料
    async getMocProfile() {
      console.log('getMocProfile');
      console.log('this.authToken', this.authToken);
      const authToken = sessionStorage.getItem("AuthToken");
      console.log('authToken', authToken);

      let url = `${this.apiUrl}/api/get_user_data_from_MOC?AuthToken=${authToken}`;

      try {
        const response = await axios.post(url);
        console.log('取得藝文中心會員資料', response);
        console.log('response.data.code', response.data.code);

        if (response.data.code === 500) {
          console.log('取會員資料失敗');
          this.logout();
        } else {
          this.mocProfile = JSON.parse(response.data.data);
          console.log('JSON.parse', JSON.parse(response.data.data));
          this.getToken(); // 收到 Email 後取 choozmoToken
        }
        // this.mocProfile = JSON.parse(response.data.data);
        // this.getToken(); // 收到 Email 後取 choozmoToken
      } catch (error) {
        console.error(error);
      }
    },
    async getToken() {
      const authToken = sessionStorage.getItem("AuthToken");

      let url = `${this.apiUrl}/api/get_token?authToken=${authToken}&email=${this.mocProfile.EMAIL}`;

      try {
        const response = await axios.get(url);
        console.log('get Choozmo Token', response);
        console.log('Token：', response.data.token);
        if (response.data.token) {
          this.token = response.data.token;
          sessionStorage.setItem("token", response.data.token);
          // this.getUserInfo();
          // return true;
        } else {
          // return false;
        }
        // localStorage.setItem("AuthToken", response.data.authToken);
      } catch (error) {
        console.error(error);
      }
    },
    // 取得網址參數
    getURLParams() {
      const urlParams = new URLSearchParams(window.location.search);
      const params = {};

      urlParams.forEach((value, key) => {
        params[key] = value;
      });

      return params;
    },
    logout() {
      this.loginState = false;
      sessionStorage.removeItem("token");
      sessionStorage.removeItem("AuthToken");
      // return this.router.push("/");
    },
    mocLogout() {
      window.location.href =
        "https://member.moc.gov.tw/MOCMC/M0003/ottLogout?SYS_ID=CRAFT_NTCRI&urlRedirectTo=https://craftsplatform.ntcri.gov.tw/";
    },
    getImageUrl(name) {
      return new URL(`/src/assets/img/${name}`, import.meta.url).href;
    },
    getTotalPages(totalRecords, recordsPerPage) { // 計算頁數
      return Math.ceil(totalRecords / recordsPerPage);
    },
    // setProfile(data) {
    //   this.profile = data;
    // },
    // async getProfile() {
    //   try {
    //     const response = await axios.get(
    //       `${this.apiUrl}/api/information?token=${this.token}`
    //     );
    //     console.log('getProfile', response);
    //     if (response.data.msg === "no access" || !response.data.msg) {
    //       console.log('getProfile logout');
    //       this.logout();
    //       return;
    //     } else {
    //       this.setProfile(response.data.msg);
    //     }
    //   } catch (error) {
    //     console.error(error);
    //   }
    // },
    async getUserInfo() {
      let token = sessionStorage.getItem("token");
      console.log('是否已有資料', Object.keys(this.userInfo).length);
      // 判斷 token & userInfo 是否已存在
      if (token && !Object.keys(this.userInfo).length) {
        try {
          const response = await axios.get(
            `${this.apiUrl}/api/get_user_information?access_token=${token}`
          );

          this.userInfo = response.data.user_inform[0];
          console.log('getUserInfo userInfo', this.userInfo);

          // return response;
        } catch (error) {
          console.error(error);
        }
      }
    },
    // 將日期格式轉成純字串
    formatDate(date) {
      const isTimestamp = !isNaN(date) && Number(date) >= 0; // 判斷是否為時間戳記
      if (!date) return ""; // 若選取的日期為空，回傳空字串
      if (!isTimestamp) {
        return date;
      } else {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        // 組成 YYYY-MM-DD
        return `${year}-${month}-${day}`;
      }
    },
    // DatePicker
    datePickerFormat(date) {
      console.log('date', date);
      const day = date.getDate();
      const month = date.getMonth() + 1;
      const year = date.getFullYear();
      console.log(' `${year}-${month}-${day}`', `${year}-${month}-${day}`);
      return `${year}-${month}-${day}`;
    },
    // 處理時間格式(日期+時間)
    mergeAndFormatDateTime(dateString, timeInfo) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = date.getMonth() + 1; // 月份是從 0 開始計算的，所以要加 1
      const day = date.getDate();

      return `${year}-${month}-${day}T${timeInfo.hours < 10 ? '0' : ''}${timeInfo.hours}:${timeInfo.minutes < 10 ? '0' : ''}${timeInfo.minutes}:00.000Z`;
      // return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.000Z`;
    },
    // 將 UTC 時間轉換為台灣時間
    convertUTCtoTaiwanTime(utcTimeString) {
      const utcTime = new Date(utcTimeString);
      const localTime = new Date(utcTime.getTime() + utcTime.getTimezoneOffset() * 60 * 1000);
      console.log('轉台灣時間', localTime);
      return localTime;
    },
    // 判斷兩組日期是否相同
    isSameDay(date1, date2) {
      const year1 = date1.getFullYear();
      const month1 = date1.getMonth() + 1;
      const day1 = date1.getDate();

      const year2 = date2.getFullYear();
      const month2 = date2.getMonth() + 1;
      const day2 = date2.getDate();

      return `${year1}${month1}${day1}` === `${year2}${month2}${day2}`;
    },
    getPDF(name) {
      return `${this.imgUrl}/pdf/${name}.pdf`;
    },
    // 過濾圖片標籤
    removeHtmlImages(value) {
      return value.replace(/<img\b[^>]*>/gi, "");
    },
    // 開啟登入視窗
    openLoginDialog() {
      this.loginDialog = true;
      console.log('this.loginDialog', this.loginDialog);
    },
    // 調整字串
    formatString(content) {
      const parser = new DOMParser();
      const decodedText = parser.parseFromString(content, "text/html").body.textContent;

      return decodedText;

      // if (content) {
      //   content = content.replace(/&lt;/g, "<");
      //   content = content.replace(/&gt;/g, ">");
      //   content = content.replace(/&amp;nbsp;/g, " ");
      //   content = content.replace(/&amp;times;/g, "×");
      //   content = content.replace(/&amp;#39;/g, "'");
      //   content = content.replace(/&middot;/g, "·");

      //   return content;
      // }
    },
    // 返回課程圖片網址
    getImageSrc(data) {
      const regex = /http/; // 檢查字串中是否包含 http

      if (data.group_id === 9) {
        return this.getImageUrl("cfa-default.jpg");
      } else if (data.special_class_list_name === "one_day_class") {
        return this.getImageUrl("default.webp");
      } else if (regex.test(data.cover_img)) {
        return data.cover_img;
      } else {
        return `${this.imgUrl}/${data.cover_img}`;
      }
    },
    setAlert(title) {
      alert(`${title}！點擊確認後將重新整理頁面。`);
      window.location.reload();
    },
    // 取得收藏課程
    async getFavoriteClass() {
      console.log("store 取得收藏課程", this.token);
      if (this.token) {
        try {
          const response = await axios.get(
            `${this.apiUrl}/api/get_favorite_class?access_token=${this.token}`
          );
          this.favoritesList = response.data.favorite_courses;
          console.log('store.favoritesList', this.favoritesList);
        } catch (error) {
          console.error(error);
        }
      }
    },
    checkTokenExpiration() {
      if (this.token) {
        // 解碼 JWT
        const base64Url = this.token.split(".")[1]; // 取得 JWT 的 payload
        const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/"); // 處理 URL 安全的 Base64 字串
        const decodedPayload = atob(base64); // Base64 解碼

        // 將解碼後的 payload 轉換為 JSON 物件
        const payload = JSON.parse(decodedPayload);

        // 獲取過期時間(exp)
        const expirationTime = payload.exp; // 過期時間的 UNIX 時間戳

        // 創建 Date 物件並設定時間戳
        const expirationDate = new Date(expirationTime * 1000); // JS 時間戳以毫秒為單位故乘以 1000

        // 取得日期和時間的字串表示
        const formattedExpiration = expirationDate.toLocaleString();

        console.log("JWT 過期時間：", formattedExpiration);

        // 取得當前時間戳
        const currentTimestamp = Math.floor(Date.now() / 1000);

        let isTokenExpired;

        // 判斷 Token 是否已過期
        if (currentTimestamp > expirationTime) {
          isTokenExpired = true;
        } else {
          isTokenExpired = false;
        }
        return isTokenExpired;
      }
    }
  },
})