<script setup>
import { defineProps, onMounted, onUnmounted, ref, nextTick, watch } from "vue";
import { getHistoryPoints, getHistoryData } from "@/apis/history";
import { getAssetSingle } from "@/apis/asset";
import { getOperationCompanyList } from "@/apis/operation";
import LineChart from "@/components/chart/LineChart.vue";
import { SECOND_CHART_COLOR } from "@/constant";
import dayjs from "dayjs";

const props = defineProps({
  meter: Object,
  floors: Array,
  companyOptions: Array,
});
const tabs = ["即時資訊", "設備資訊", "趨勢查詢"];
const activeTab = ref(tabs[0]);
const meterDetails = ref({});
const pointsList = ref([]);
const timeList = ref([
  { value: 1, name: "1小時" },
  { value: 4, name: "4小時" },
  { value: 8, name: "8小時" },
]);
const chartData = ref([]);
const forge_chart = ref(null);
const loading = ref(false);

// 預設圖表選項
const defaultChartOption = {
  tooltip: {
    trigger: "axis",
  },
  legend: {
    data: [],
    textStyle: {
      color: "#ffffff",
      fontSize: 16,
    },
  },
  grid: {
    top: "25%",
    left: "0%",
    right: "0%",
    bottom: "0%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    splitLine: { show: false },
    axisLabel: {
      color: "#ffffff",
      formatter: (value) => dayjs(value).format("HH:mm"), // 格式化為時間
    },
    data: [],
  },
  yAxis: {
    type: "value",
    splitLine: { show: false },
    axisLabel: { color: "#ffffff" },
  },
  series: [],
};
// 表單狀態
const formState = ref({
  Cumulant: 1,
  Type: 2,
  Points: [],
  Start_date: dayjs().format("YYYY-MM-DD"),
  Start_time: dayjs().format("HH:00"),
  End_date: dayjs().format("YYYY-MM-DD"),
  End_time: dayjs().format("HH:00"),
  Device_list: [],
});

const updateTimeRange = (hours) => {
  const now = dayjs();
  const startTime = now.subtract(hours, "hour");
  formState.value.Start_date = startTime.format("YYYY-MM-DD");
  formState.value.Start_time = startTime.format("HH:00");
  formState.value.End_date = now.format("YYYY-MM-DD");
  formState.value.End_time = now.format("HH:00");
};

const onSearch = async () => {
  loading.value = true;
  const res = await getHistoryData(formState.value);
  if (res.isSuccess) {
    if (res.data.items.length > 0) {
      chartData.value = res.data.items
        .map((d) => ({
          timestamp: d.timestamp,
          value: parseFloat(d.value),
        }))
        .sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));

      // 更新圖表
      await nextTick();
      if (forge_chart.value?.chart) {
        forge_chart.value.chart.setOption({
          xAxis: {
            data: chartData.value.map((d) => d.timestamp),
          },
          series: [
            {
              name: props.data?.value.full_name,
              type: "line",
              data: chartData.value.map((d) => d.value),
              showSymbol: false,
              itemStyle: {
                color: SECOND_CHART_COLOR[0], // 使用預設顏色
              },
            },
          ],
        });
      }
    } else {
      chartData.value = [];
      if (forge_chart.value?.chart) {
        forge_chart.value.chart.clear(); // 清空圖表
      }
    }
  } else {
    console.error("API Error:", res.msg);
  }
  loading.value = false;
};

const getPoint = async (Device_list, Cumulant) => {
  const res = await getHistoryPoints({ Device_list, Cumulant });
  pointsList.value = res.data.map((d, index) => ({
    ...d,
    name: d.item_name,
    key: d.points,
  }));
  if (pointsList.value.length > 0) {
    formState.value.Points = pointsList.value[0].points;
  }
};

onMounted(() => {
  getPoint(["CHY_F1_EE_E4_U1F_NA_CPM12D_N1"], 1);
  if (timeList.value.length > 0) {
    formState.value.time = timeList.value[0].value;
    updateTimeRange(timeList.value[0].value);
  }
  onSearch();
});

onUnmounted(() => {
  formState.value = {};
  chartData.value = [];
});

watch(
  () => props.meter?.main_id,
  async (main_id, prev_main_id) => {
    if (!main_id) {
      meterDetails.value = {};
      return;
    }
    // 如果 main_id 沒有變化則不呼叫 API
    if (main_id === prev_main_id) return;
    const res = await getAssetSingle(main_id);
    if (res.isSuccess) {
      meterDetails.value = {
        ...res.data,
        key: res.data.main_id,
        floor:
          props.floors.find(
            ({ floor_guid }) => res.data.floor_guid === floor_guid
          )?.full_name || "",
        company:
          props.companyOptions.find(({ id }) => res.data.operation_id === id)
            ?.name || "",
        contact_person:
          props.companyOptions.find(({ id }) => res.data.operation_id === id)
            ?.contact_person || "",
        buying_date: res.data.buying_date
          ? dayjs(res.data.buying_date).format("YYYY-MM-DD")
          : "",
        created_at: res.data.created_at
          ? dayjs(res.data.created_at).format("YYYY-MM-DD")
          : "",
      };

      formState.value.Device_list = res.data.device_number || [];
    }
  },
  { immediate: true }
);
</script>
<template>
  <div class="card bg-slate-200 text-accent-content rounded-md w-96">
    <div class="card-body p-3">
      <h2 class="card-title">{{ meter.name }}</h2>
      <div
        role="tablist"
        class="tabs tabs-boxed tabs-sm bg-opacity-50 shadow-inner shadow-slate-600"
      >
        <a
          v-for="tab in tabs"
          :key="tab"
          role="tab"
          class="tab"
          :class="{
            'tab-active !bg-green-500 !text-white shadow-sm shadow-slate-800':
              activeTab === tab,
          }"
          @click.prevent="activeTab = tab"
        >
          {{ tab }}
        </a>
      </div>
      <div class="p-0">
        <div v-if="activeTab === '即時資訊'">
          <ul class="leading-7 tracking-wider text-slate-700 px-2">
            <li><b>電流:</b> {{ meter.current }}</li>
            <li><b>電壓:</b> {{ meter.voltage }}</li>
            <li><b>功率:</b> {{ meter.power }}</li>
            <li><b>用電量:</b> {{ meter.energyConsumption }}</li>
          </ul>
        </div>
        <div v-else-if="activeTab === '設備資訊'">
          <table class="table table-sm w-full text-slate-600">
            <tbody>
              <tr>
                <td class="font-bold">設備編號</td>
                <td>{{ meterDetails?.device_number || "—" }}</td>
              </tr>
              <tr>
                <td class="font-bold">設備名稱</td>
                <td>
                  {{ meterDetails?.full_name || meter.name || "—" }}
                </td>
              </tr>
              <tr>
                <td class="font-bold">資產編號</td>
                <td>{{ meterDetails?.asset_number || "—" }}</td>
              </tr>
              <tr>
                <td class="font-bold">設備位置</td>
                <td>{{ meterDetails?.floor || "—" }}</td>
              </tr>
              <tr>
                <td class="font-bold">圖面標識</td>
                <td>{{ meterDetails?.device_coordinate || "—" }}</td>
              </tr>
              <tr>
                <td class="font-bold">品牌 / 型號</td>
                <td>
                  {{ meterDetails?.brand || "—" }} /
                  {{ meterDetails?.device_model || "—" }}
                </td>
              </tr>
              <tr>
                <td class="font-bold">廠商 / 聯絡人</td>
                <td>
                  {{ meterDetails?.company || "—" }} /
                  {{ meterDetails?.contact_person || "—" }}
                </td>
              </tr>
              <tr>
                <td class="font-bold">購買日期</td>
                <td>{{ meterDetails?.buying_date || "—" }}</td>
              </tr>
              <tr>
                <td class="font-bold">建立時間</td>
                <td>{{ meterDetails?.created_at || "—" }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div v-else-if="activeTab === '趨勢查詢'">
          <div class="flex items-center gap-4">
            <Select
              :value="formState"
              class=""
              selectClass="select-sm text-sm text-white bg-gray-500/80 shadow-inner shadow-slate-500 border-info focus-within:border-info"
              name="Points"
              Attribute="name"
              :options="pointsList"
            ></Select>
            <Select
              :value="formState"
              class=""
              selectClass="select-sm text-sm text-white bg-gray-500/80 shadow-inner shadow-slate-500 border-info focus-within:border-info"
              name="time"
              Attribute="name"
              :options="timeList"
              @change="(value) => updateTimeRange(value)"
            ></Select>
            <button
              class="btn btn-sm btn-success"
              @click.stop.prevent="onSearch"
            >
              <font-awesome-icon :icon="['fas', 'search']" class="" />搜尋
            </button>
          </div>
          <div class="min-h-[300px] relative">
            <span
              v-if="loading"
              className="loading loading-spinner loading-lg text-info absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-20"
            ></span>
            <LineChart
              v-if="chartData.length > 0"
              id="forge_chart"
              class="min-h-[300px] max-h-fit"
              :option="defaultChartOption"
              ref="forge_chart"
            />
            <p
              class="text-center text-base text-gray-500 pt-16"
              v-if="!loading && chartData.length === 0"
            >
              沒有資料
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
