<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from "vue";
import axios from "axios";

const message = ref("");

let ws;

onMounted(() => {
  // 建立 WebSocket 連接
  ws = new WebSocket("wss://cmm.ai:8075/ws");
  // ws = new WebSocket("wss://cmm.ai:8082/ws"); // 測試用

  // 當連接開啟時
  ws.onopen = () => {
    console.log("WebSocket open");
  };

  // 當接收到伺服器訊息時
  ws.onmessage = (event) => {
    console.log("WebSocket: ", event.data);
    if (event.data === "finish") {
      getKwStateList();
    }
    message.value = event.data;
  };

  // 處理錯誤
  ws.onerror = (error) => {
    console.error("WebSocket error: ", error);
  };

  // 當連接關閉時
  ws.onclose = () => {
    console.log("WebSocket close");
  };
});

// 當組件卸載時，關閉 WebSocket 連接
onBeforeUnmount(() => {
  if (ws) {
    ws.close();
  }
});

let kwVal = ref(""); // 關鍵字
let stageVal = ref(null); // 指定層級
let maxStage = ref(null); // 最大層級
let haveStage = ref(false); // 是否有層級
let searchState = ref(false); // 點擊查詢
let searchLoading = ref(false); // 載入狀態
let showStageBtn = ref(false); // 新增層級按鈕
let regionsVal = ref(null); // 地區
let languageVal = ref(null); // 語言
let searchError = ref(false); // 查詢狀態

// 取得最大層數
async function getStage() {
  if (!regionsVal.value || !languageVal.value) {
    searchError.value = true;
    return;
  } else {
    searchError.value = false;
  }

  searchLoading.value = true;
  let url = `https://cmm.ai:8075/get_stage3?kw=${kwVal.value}&region=${regionsVal.value}&language=${languageVal.value}`;

  try {
    let response = await axios.get(url);
    console.log("response", response);
    console.log(response.data.message.headers);
    searchState.value = true;
    if (response.data.message.detail === "Failed to generate stage") {
      haveStage.value = false;
    } else {
      maxStage.value = response.data.message;
      haveStage.value = true;
      getNodeNum();

      // // 層級小於四層才顯示新增按鈕
      // if (response.data.message < 4) {
      //   showStageBtn.value = true;
      // } else {
      //   showStageBtn.value = false;
      // }
    }

    console.log("response.data.message", response.data.message);

    searchLoading.value = false;
  } catch (error) {
    console.error("error", error);
  }
}

// 取得 node 層數
async function getNodeNum() {
  let url = `https://cmm.ai:8075/get_node_num3?kw=${kwVal.value}&region=${regionsVal.value}&language=${languageVal.value}&stage=${maxStage.value}`;

  try {
    let response = await axios.get(url);
    console.log("取得 node 層數", response);

    // 數量小於 120 顯示新增層級
    if (response.status === 200) {
      if (response.data.message < 120) {
        showStageBtn.value = true;
      } else {
        showStageBtn.value = false;
      }
    }
  } catch (error) {
    console.error("error", error);
  }
}

// let insertError = ref(false);
// let insertRegionsVal = ref(null); // 新增地區
// let insertLanguageVal = ref(null); // 新增語言

// 新增關鍵字
async function insertKw(type = "") {
  if (!regionsVal.value || !languageVal.value) {
    alert("請選擇要新增的地區及語言");
    return;
  }

  let email = localStorage.getItem("email");
  let url;

  // 新增層級
  if (type === "stage") {
    url = `https://cmm.ai:8075/insert_kw3_2?kw=${kwVal.value}&region=${regionsVal.value}&language=${languageVal.value}&email=${email}`;
  } else {
    url = `https://cmm.ai:8075/insert_kw3?kw=${kwVal.value}&region=${regionsVal.value}&language=${languageVal.value}&email=${email}`;
  }

  try {
    let response = await axios.put(url);
    console.log("新增關鍵字", response);

    if (response.status === 200) {
      alert("關鍵字已加入排程");

      // 清空地區及語言
      // insertRegionsVal.value = null;
      // insertLanguageVal.value = null;

      // 關閉查詢結果
      // searchState.value = false;
    }

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

// let insertDialog = ref(false);
// let insertState = ref(false); // 新增層級
let graphContent = ref(""); // html code

// 取得 html
async function getHtml() {
  console.log("getHtml");

  let url = `https://cmm.ai:8075/get_html3?kw=${kwVal.value}&region=${regionsVal.value}&language=${languageVal.value}&stage=${stageVal.value}`;

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

    graphContent.value = response.data.data;

    // 生成 html 並另開分頁
    const newWindow = window.open();
    if (newWindow) {
      newWindow.document.open();
      newWindow.document.write(graphContent.value);
      newWindow.document.close();
    } else {
      alert("無法打開新頁面，請允許瀏覽器的彈出窗口。");
    }
  } catch (error) {
    console.error("操作失敗", error);
    alert("操作失敗，請重新操作。");
  }
}

// 地區
const regionsList = reactive([
  { region: "台灣", code: "tw" },
  { region: "馬來西亞", code: "my" },
  { region: "美國", code: "us" },
  { region: "中國", code: "cn" },
  { region: "日本", code: "jp" },
  { region: "韓國", code: "kr" },
  { region: "法國", code: "fr" },
  { region: "印度", code: "in" },
]);

// 語言
const languageList = [
  { language: "繁體中文", code: "zh-TW" },
  { language: "英文", code: "en" },
  { language: "簡體中文", code: "zh" },
  { language: "法語", code: "fr" },
  { language: "日語", code: "ja" },
  { language: "韓語", code: "ko" },
  { language: "印地語", code: "hi" },
];

let stateList = reactive([]);

// 取得關鍵字狀態
async function getKwStateList() {
  let email = localStorage.getItem("email");

  let url = `https://cmm.ai:8075/get_user_kw_state3?email=${email}`;

  try {
    let response = await axios.get(url);
    console.log("response", response.data.message);

    let list = response.data.message;

    if (list.status_code === 204) {
      alert("新增失敗，請重新輸入");
      return;
    }

    if (list.length) {
      stateList.length = 0;
      list.map((item) => {
        stateList.push(item);
      });
      console.log("stateList", stateList);
    }

    // 判斷所有關鍵字狀態
    // const allCompleted = stateList.every((item) => item.state === "已完成");
    // console.log("allCompleted", allCompleted);

    // if (allCompleted) {
    //   console.log("所有狀態都是 '已完成'，停止 setInterval");
    //   clearInterval(intervalId); // 停止定時器
    // } else {
    //   console.log("還有未完成的狀態");
    //   startInterval();
    // }
  } catch (error) {
    console.error("error", error);
  }
}

getKwStateList();

// let intervalId;

// // 每分鐘更新狀態
// function startInterval() {
//   intervalId = setInterval(getKwStateList, 60000);
//   console.log("setInterval 已啟動");
// }

// startInterval();

const headers = [
  {
    title: "關鍵字",
    sortable: true,
    key: "kw",
    align: "left",
  },
  {
    title: "狀態",
    sortable: true,
    key: "state",
    align: "left",
  },
  {
    title: "等待時間 (分)",
    sortable: true,
    key: "waiting_time",
  },
  {
    title: "訊息",
    sortable: true,
    key: "message",
  },
];

// 計算下拉選單層級數
const filteredStage = computed(() => {
  let arr = Array.from({ length: maxStage.value }, (_, i) =>
    (i + 1).toString()
  );
  arr = arr.filter((stage) => stage !== "1"); // 移除第一層
  return arr;
});

// 插入資料
// function insertData(kw) {
//   let url = `https://cmm.ai:8084/insert_data3?kw=${kwVal.value}`;

//   axios.put(url).then(function (response) {
//     const message = response.data.message; // 假設 API 返回一個帶有消息的 JSON
//     alert(message);
//   });
// }

// // 將所有流程包進來
// async function processData() {
//   console.log("processData", kwVal.value, stageVal.value);

//   const url = `https://cmm.ai:8084/check_kw_in_data3?kw=${kwVal.value}&stage=${stageVal.value}`;

//   try {
//     let response = await axios.get(url);
//     const message = response.data.message;

//     console.log("response", response);

//     if (message === "已查詢到關鍵字, 立即為您產圖.") {
//       var confirmNextStep = confirm(
//         "已查詢到關鍵字，立即為您產圖。" +
//           "\n是否要執行下一步操作？（點確定後將另開分頁）"
//       );

//       if (confirmNextStep) {
//         getHtml();
//       } else {
//         alert("取消操作");
//       }
//     }
//   } catch (error) {
//     console.error("操作失敗", error);
//     alert("操作失敗，請重新操作。");
//   }
// }
</script>

<template>
  <v-container fluid class="knowledge-graph">
    <v-card class="mt-10 ma-3 pa-sm-5">
      <v-card-title primary-title>
        <h3 class="card-title mb-3">GEN SEO</h3>
      </v-card-title>
      <v-card-text class="card-content">
        <div class="d-flex flex-column">
          <v-text-field
            v-model="kwVal"
            label="關鍵字"
            density="compact"
            prepend-inner-icon="search"
            variant="solo"
            hide-details
            class="mr-5 search-field"
          ></v-text-field>

          <div class="d-flex align-center mt-5">
            <v-select
              v-model="regionsVal"
              label="地區"
              density="compact"
              :items="regionsList"
              item-title="region"
              item-value="code"
              variant="solo"
              hide-details
              :rules="[(value) => !!value || '尚未選擇地區']"
            ></v-select>

            <v-select
              v-model="languageVal"
              label="語言"
              density="compact"
              :items="languageList"
              item-title="language"
              item-value="code"
              variant="solo"
              hide-details
              class="mx-5"
              :rules="[(value) => !!value || '尚未選擇語言']"
            ></v-select>

            <!-- <v-select
              v-model="stageVal"
              label="層級"
              density="compact"
              :items="['1', '2', '3', '4', '5']"
              variant="solo"
              hide-details
              class="my-7 my-md-0 mx-md-5"
            ></v-select> -->

            <button @click="getStage()" class="search-btn">
              <v-progress-circular
                v-if="searchLoading"
                :width="3"
                :size="20"
                color="white"
                class="pb-1"
                indeterminate
              ></v-progress-circular>
              <p v-else>查詢</p>
            </button>
          </div>

          <p v-if="searchError" class="text-error mt-3 ml-3">
            請選擇查詢地區及語言
          </p>
        </div>
      </v-card-text>
    </v-card>

    <v-card v-if="searchState" class="mt-10 ma-3 pa-sm-5">
      <v-card-title primary-title>
        <h3 class="card-title mb-3">查詢結果</h3>
      </v-card-title>
      <v-card-text class="card-content">
        <div v-if="haveStage" class="d-flex flex-column">
          <span class="d-flex align-center">
            <p class="pt-1 mr-5">目前最大層級：{{ maxStage }}</p>

            <v-btn
              v-if="showStageBtn"
              @click="insertKw('stage')"
              variant="outlined"
              color="primary"
              size="small"
            >
              新增層級
            </v-btn>

            <!-- <v-btn
              v-if="showStageBtn"
              @click="
                insertDialog = true;
                insertState = true;
              "
              variant="outlined"
              color="primary"
              size="small"
            >
              新增層級
            </v-btn>

            <v-dialog v-model="insertDialog" width="auto">
              <v-card width="400" title="新增層級">
                <v-card-text class="d-flex mt-5">
                  <v-select
                    v-model="insertRegionsVal"
                    label="地區"
                    density="compact"
                    :items="regionsList"
                    item-title="region"
                    item-value="code"
                    variant="solo"
                    hide-details
                    :rules="[(value) => !!value || '尚未選擇地區']"
                  ></v-select>

                  <v-select
                    v-model="insertLanguageVal"
                    label="語言"
                    density="compact"
                    :items="languageList"
                    item-title="language"
                    item-value="code"
                    variant="solo"
                    hide-details
                    class="mx-5"
                    :rules="[(value) => !!value || '尚未選擇語言']"
                  ></v-select>

                  <p v-if="insertError" class="text-error">請選擇地區及語言</p>

                  <v-btn @click="insertKw()" color="primary" class="mt-1"
                    >送出</v-btn
                  >
                </v-card-text>

                <v-card-actions>
                  <v-btn class="ms-auto mr-4" @click="insertDialog = false">
                    關閉
                  </v-btn>
                </v-card-actions>
              </v-card>
            </v-dialog> -->

            <!-- <button @click="getStage()" class="insert-btn">新增層級</button> -->
          </span>

          <span class="d-flex align-center mt-7">
            <v-select
              v-model="stageVal"
              label="請選擇層級"
              density="compact"
              :items="filteredStage"
              variant="solo"
              hide-details
            ></v-select>

            <button @click="getHtml()" class="search-btn ml-3">查看結果</button>
          </span>
        </div>

        <div v-else>
          <p>未查詢到符合的關鍵字</p>

          <v-btn
            @click="insertKw()"
            variant="outlined"
            color="primary"
            class="mt-3"
          >
            新增關鍵字
          </v-btn>

          <!-- <p>未查詢到關鍵字，請選擇要搜尋的地區及語言：</p>

          <span class="d-flex mt-5">
            <v-select
              v-model="insertRegionsVal"
              label="地區"
              density="compact"
              :items="regionsList"
              item-title="region"
              item-value="code"
              variant="solo"
              hide-details
              :rules="[(value) => !!value || '尚未選擇地區']"
            ></v-select>

            <v-select
              v-model="insertLanguageVal"
              label="語言"
              density="compact"
              :items="languageList"
              item-title="language"
              item-value="code"
              variant="solo"
              hide-details
              class="mx-5"
              :rules="[(value) => !!value || '尚未選擇語言']"
            ></v-select>

            <p v-if="insertError" class="text-error">請選擇地區及語言</p>

            <button @click="insertKw()" class="search-btn">送出</button>
          </span> -->
        </div>
      </v-card-text>
    </v-card>

    <!-- 關鍵字狀態清單 -->
    <v-data-table
      v-if="stateList.length"
      class="pa-5"
      :headers="headers"
      :items="stateList"
    >
      <template v-slot:item.state="{ item }">
        <span v-if="item.raw.state === '已完成'">
          <v-icon icon="check_circle" color="success" />
          已完成
        </span>
        <span v-else-if="item.raw.state === '等待中'">
          <v-icon icon="pending" color="warning" />
          等待中
        </span>
        <span v-else-if="item.raw.state === '運行中'">
          <v-progress-circular
            indeterminate
            color="info"
            style="width: 20px"
          ></v-progress-circular>
          運行中
        </span>
        <!-- <span v-else>
          <v-icon icon="warning" color="error" />
          失敗
        </span> -->
      </template>
    </v-data-table>
  </v-container>
</template>

<style lang="scss">
.knowledge-graph {
  .v-select {
    max-width: 10rem;
  }

  .v-data-table-footer {
    margin-top: 1rem;
  }

  .search-field {
    max-width: 21rem;
  }

  .search-btn {
    padding: 13px 30px 10px;
    color: #fff;
    font-weight: 500;
    letter-spacing: 2px;
    border-radius: 100px;
    background-image: linear-gradient(
      -225deg,
      rgb(234, 84, 19) 35%,
      rgb(178, 69, 146) 100%
    );
  }

  .card-content {
    max-width: 800px;
  }

  .v-text-field .v-field {
    border-radius: 100px;
  }

  .v-input {
    @media (max-width: 960px) {
      width: 100%;
    }
  }
}
</style>
