<script setup>
import { ref, onMounted, watch, defineProps, inject } from "vue";
import { postIOTSchema } from "@/apis/asset";
import MQTTCheckboxTree from "./MQTTCheckboxTree.vue";
import generateSchema from "json-schema-generator";
import { useI18n } from "vue-i18n";
const { openToast } = inject("app_toast");
const props = defineProps({
  getData: Function,
  pointsData: Object,
  variable_id: Number,
});
const { t } = useI18n();
// 新增：將 jsonInput 與結構資料初始化
const jsonInput = ref("");
const treeData = ref(null);
const checkedNodes = ref([]);

const form = ref(null);
const schemaName = ref("");
const formStates = ref([]);

// JSON Schema 轉換
const customGenerateSchema = (json) => {
  if (typeof json !== "object" || json === null) return {};

  const schema = { type: "object", properties: {} };
  Object.entries(json).forEach(([key, value]) => {
    if (typeof value === "object" && value !== null) {
      schema.properties[key] = customGenerateSchema(value);
    } else {
      schema.properties[key] = { type: typeof value };
    }
  });

  return schema;
};

// 將提取的架構轉換為 Tree 結構
const transformToTree = (schema, parentPath = "") => {
  if (typeof schema !== "object" || schema === null) return [];

  return Object.entries(schema)
    .map(([key, value]) => {
      const currentPath = parentPath ? `${parentPath}_${key}` : key;
      const isObject = typeof value === "object" && value !== null;

      if (isObject && value.properties) {
        return {
          label: key,
          value: currentPath,
          expanded: true,
          children: transformToTree(value.properties, currentPath),
        };
      }

      return {
        label: key,
        value: currentPath,
        expanded: true,
        children: [],
      };
    })
    .filter((item) => item !== null); // 過濾掉 null 值
};

// 解析 JSON 並生成樹狀結構
const parseJson = () => {
  try {
    const json = JSON.parse(jsonInput.value);

    // 解析 JSON 結構
    const schema = customGenerateSchema(json);
    console.log("JSON Schema:", schema);

    // 進行結構轉換並顯示
    treeData.value = transformToTree(schema.properties);
    console.log("轉換後的樹狀結構:", treeData.value);
  } catch (error) {
    console.error("JSON 格式不正確:", error);
    alert("請檢查 JSON 格式，確保它是有效的！");
  }
};

const clearAll = () => {
  jsonInput.value = ""; // 清空輸入的 JSON
  treeData.value = null; // 清除生成的樹狀結構
  checkedNodes.value = []; // 清空已勾選的節點
};

watch(
  () => checkedNodes.value,
  (newCheckedNodes) => {
    // 為每個 node 創建一個 formState
    formStates.value = newCheckedNodes.map((node) => ({
      PointOrg: node,
      PointSys: "",
      item_id: null,
    }));
  },
  { immediate: true }
);

const onOk = async () => {
  if (!schemaName.value) {
    openToast("error", t("msg.schema_name_required"), "#MQTT_Parse_item");
    return;
  }
  const points = formStates.value.map((state) => ({
    PointOrg: state.PointOrg,
    PointSys: props.pointsData.find((point) => point.id === state.item_id)
      .points,
    item_id: state.item_id,
  }));
  const apiData = {
    name: schemaName.value,
    variable_id: props.variable_id,
    points: points,
  };
  const res = await postIOTSchema(apiData);
  if (res.isSuccess) {
    props.getData(props.variable_id);
    onCancel();
  } else {
    openToast("error", res.msg, "#MQTT_Parse_item");
  }
};

const openModal = () => {
  MQTT_Parse_item.showModal();
};

const onCancel = () => {
  MQTT_Parse_item.close();
  clearAll();
};
</script>

<template>
  <button class="btn btn-sm btn-add mr-3" @click.stop.prevent="openModal">
    <font-awesome-icon :icon="['fas', 'plus']" />{{ $t("button.add") }}
  </button>
  <Modal
    id="MQTT_Parse_item"
    :title="t('setting.MQTT_parse')"
    :onCancel="onCancel"
    :width="1600"
  >
    <template #modalContent>
      <div class="flex w-full gap-4 mt-5">
        <div class="w-full">
          <textarea
            v-model="jsonInput"
            :placeholder="t('setting.json_format_text')"
            class="w-full h-[500px] p-4 border rounded-lg font-mono text-white"
          ></textarea>
        </div>
        <div class="my-auto">
          <button @click="parseJson" class="btn-success btn w-28 mb-4">
            {{ $t("button.convert")
            }}<font-awesome-icon :icon="['fas', 'chevron-right']" />
          </button>
          <button @click="clearAll" class="bg-error btn w-28">
            {{ $t("button.delete")
            }}<font-awesome-icon :icon="['fas', 'trash-alt']" />
          </button>
        </div>
        <div class="w-full p-4 rounded-lg border overflow-y-scroll h-[500px]">
          <MQTTCheckboxTree
            v-if="treeData"
            :data="treeData"
            v-model:checked-nodes="checkedNodes"
          />
          <div v-else class="text-white">
            {{ $t("setting.json_click_text") }}
          </div>
        </div>
      </div>
      <form ref="form" class="" v-if="checkedNodes.length">
        <div class="flex items-center mt-5">
          <h2 class="text-lg font-bold whitespace-nowrap me-2">
            {{ $t("setting.schema_name") }}:
          </h2>
          <input
            type="text"
            v-model.text="schemaName"
            class="input border-info focus-within:border-info"
            required
          />
        </div>
        <table class="table w-1/2 mt-2">
          <thead>
            <tr>
              <th>{{ $t("setting.IoT_point_structure") }}</th>
              <th>{{ $t("setting.system_point_name") }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(node, index) in checkedNodes" :key="node">
              <td>
                <Input
                  :value="formStates[index]"
                  name="PointOrg"
                  :readonly="true"
                  class="mx-auto"
                />
              </td>
              <td>
                <Select
                  :value="formStates[index]"
                  class="my-2 mx-auto"
                  selectClass="border-info focus-within:border-info "
                  name="item_id"
                  Attribute="full_name"
                  :options="props.pointsData"
                >
                </Select>
              </td>
            </tr>
          </tbody>
        </table>
      </form>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="onCancel"
      >
        {{ $t("button.cancel") }}
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.stop.prevent="onOk"
      >
        {{ $t("button.submit") }}
      </button>
    </template>
  </Modal>
</template>

<style lang="scss" scoped>
.table th {
  @apply bg-cyan-600 bg-opacity-30 border border-white text-lg font-semibold text-white text-center px-2 py-3;
}

.table td {
  @apply border border-white text-lg font-semibold text-white text-center px-2 py-3;
}
</style>
