<script setup lang="ts">
import axios, { AxiosResponse } from 'axios';
import { onMounted, ref } from 'vue';

interface Device {
  ID: number
  UUID: string
  Name: string
  Expert: string
  ExpertName: string
  State: string
  Note: string
}

interface Expert {
  ID: number
  UID: string
  SecUID: string
  ShortID: string
  RealName: string
  NickName: string
  State: string
  Since: number
  Focus: number
  Total: number
  Voice: string
  Hello: string
}


const devices = ref<Device[]>([]);

const experts = ref<Expert[]>([]);

// use axios get /experts onMount
const loadExperts = function () {
  axios.get<Expert[]>('/api/experts').then((resp: AxiosResponse) => {
    experts.value = resp.data;
  });
}


// use axios get /experts onMount
const loadDevices = function () {
  axios.get<Device[]>('/api/devices').then((resp: AxiosResponse) => {
    devices.value = resp.data;
  });
}

onMounted(() => {
  loadDevices()
});

setInterval(loadDevices, 30 * 1000);

const currentDevice = ref<Device | null>(null);
const showDeviceUpdateModal = (id: number) => {
  loadExperts();

  currentDevice.value = devices.value.find((device) => device.ID === id) || null;

  selectExpert.value = currentDevice.value?.Expert
  deviceName.value = currentDevice.value?.Name

  const dialog = document.getElementById("show_device_update_modal") as HTMLDialogElement;
  dialog.showModal();
};

const resetStateNormal = (id: number) => {
  currentDevice.value = devices.value.find((device) => device.ID === id) || null;
  if (!currentDevice.value) {
    return;
  }

  // alert to confirm
  if (!confirm(`确定要恢复 ${currentDevice.value.UUID} 的自动关注吗？`)) {
    return;
  }

  const data = { state: "" };
  axios.patch(`/api/devices/${currentDevice.value?.UUID}/state`, data).then((resp: AxiosResponse) => {
    console.log(resp.data)
    loadDevices();
  });
};

const setStateStop = (id: number) => {
  currentDevice.value = devices.value.find((device) => device.ID === id) || null;
  if (!currentDevice.value) {
    return;
  }

  // alert to confirm
  if (!confirm(`确定要停止 ${currentDevice.value.UUID} 的自动关注吗？`)) {
    return;
  }

  const data = { state: "stop" };
  axios.patch(`/api/devices/${currentDevice.value?.UUID}/state`, data).then((resp: AxiosResponse) => {
    console.log(resp.data)
    loadDevices();
  });
};

const closeModal = function () {
  const dialog = document.getElementById("show_device_update_modal") as HTMLDialogElement;
  dialog.close();
}

const deviceName = ref<String | null>();
const selectExpert = ref<String | null>();
const saveDate = () => {
  const data = {
    name: deviceName.value,
  };
  console.log(data)
  axios.patch(`/api/devices/${currentDevice.value?.UUID}/experts/${selectExpert.value}`, data).then((resp: AxiosResponse) => {
    console.log(resp.data)
    loadDevices();
    setTimeout(closeModal, 500)
  });
};

</script>

<template>
  <dialog id="show_device_update_modal" class="modal">
    <div class="modal-box">
      <form method="dialog">
        <button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
      </form>

      <h3 class="font-bold text-lg">{{ currentDevice?.UUID }}</h3>
      <div class="py-5">
        <label class="form-control w-full max-w-xs">
          <div class="label">
            <span class="label-text">设备名称</span>
          </div>
          <input type="text" placeholder="设备名称" class="input input-bordered w-full max-w-xs" v-model="deviceName"/>
        </label>

        <label class="form-control w-full">
          <div class="label">
            <span class="label-text">选择专家</span>
          </div>
          <select class="select select-bordered w-full max-w-xs" v-model="selectExpert">
            <option v-for="expert in experts" :key="expert.ID" :value="expert.UID">{{ expert.RealName }}</option>
          </select>
        </label>
      </div>
      <div class="flex justify-end gap-3">
        <button class="btn btn-wide btn-primary" @click="saveDate">保存</button>
      </div>
    </div>
  </dialog>

  <div className="overflow-x-auto">
    <div v-if="devices.length == 0">
      <h1 class="text-lg text-center">还没有设备</h1>
    </div>

    <table className="table" v-else>
      <thead>
        <tr>
          <th>设备号</th>
          <th>名称</th>
          <th>专家</th>
          <th>停止关注</th>
          <th>备注</th>
        </tr>
      </thead>
      <tbody>

        <tr :class='idx % 2 == 1 ? "bg-slate-50" : ""' v-for="(item, idx) in devices" :key="item.ID">
          <td class="flex flex-col">
            <div class="text-lg font-semibold">{{ item.UUID }}</div>
          </td>
          <td>{{ item.Name }}</td>
          <td>
            <button class="btn btn-sm" @click="showDeviceUpdateModal(item.ID)">{{ item.ExpertName }}</button>
          </td>
          <td>
            <button v-if="item.State == 'stop'" class="btn btn-warning btn-sm"
              @click="resetStateNormal(item.ID)">恢复</button>
            <button v-else class="btn btn-error btn-sm text-white" @click="setStateStop(item.ID)">停止</button>
          </td>
          <td>{{ item.Note }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>