<script setup>
import { getAssetIOTList } from "@/apis/asset";
import { ref, onMounted, inject, watch } from "vue";

const { formState } = inject("asset_table_modal_form");
const tableColumns = [
  {
    title: "編號",
    key: "index",
  },
  {
    title: "tag",
    key: "tag",
  },
  {
    title: "名稱",
    key: "full_name",
  },
  // {
  //   title: "狀態",
  //   key: "status",
  // },
  {
    title: "功能",
    key: "operation",
    width: 100,
  },
];

const modalColumns = [
  {
    title: "勾選",
    key: "check",
  },
  {
    title: "tag",
    key: "tag",
  },
  {
    title: "名稱",
    key: "full_name",
  },
];

// TODO: 抓取ＩＯＴ
const iotData = ref([]);

const getIOTData = async () => {
  const res = await getAssetIOTList();
  let data = res.data.map((d) => ({
    ...d,
    title: d.full_name,
    key: d.device_guid,
    tag: d.device_number,
    checked: formState.value.sub_device?.includes(d.device_guid),
  }));
  iotData.value = data;
  iotCheckedList.value = data.filter(({ checked }) => checked);
};
const iotCheckedList = ref([]);
const onChange = (value, checked) => {
  const d = iotData.value.find(({ device_guid }) => device_guid === value);
  let newList = [];
  if (checked) {
    newList = [...iotCheckedList.value, d];
  } else {
    newList = iotCheckedList.value.filter(
      (checked) => checked.device_guid !== d.device_guid
    );
  }
  iotCheckedList.value = newList;
  return newList;
};

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

const onOk = () => {
  formState.value.sub_device = iotCheckedList.value.map(
    ({ device_guid }) => device_guid
  );
  onCancel();
};

const onCancel = () => {
  asset_add_IoT_item.close();
};

watch(
  formState,
  () => {
    getIOTData();
  },
  {
    deep: true,
  }
);

const deleteItem = (id) => {
  console.log(formState.value.sub_device, id);
  // formState.value.device_guid = formState.value.device_guid.filter(
  //   (d) => d !== id
  // );
  const newList = onChange(id, false);
  formState.value.sub_device = newList.map(({ device_guid }) => device_guid);
};
</script>

<template>
  <!-- IoT -->
  <div class="flex flex-col mt-8 col-span-2">
    <div class="flex justify-between items-center">
      <span class="label-text-alt text-lg">設備點位</span>
      <button
        type="button"
        class="btn btn-sm btn-success"
        @click.stop.prevent="openModal"
      >
        新增感測器
      </button>
    </div>
    <Table
      :columns="tableColumns"
      :dataSource="iotCheckedList"
      :withStyle="false"
    >
      <template #bodyCell="{ record, column, index }">
        <template v-if="column.key === 'index'">{{ index + 1 }}</template
        ><template v-if="column.key === 'operation'">
          <!-- <span
            class="mr-5 text-base text-warning cursor-pointer"
            @click.stop.prevent="() => edit(record)"
          >
            <FontAwesomeIcon :icon="['fas', 'pencil-alt']"></FontAwesomeIcon>
          </span> -->
          <span
            class="text-base text-error cursor-pointer"
            @click.stop.prevent="() => deleteItem(record.device_guid)"
          >
            <FontAwesomeIcon
              :icon="['fas', 'trash-alt']"
              class="text-xl"
            /> </span></template
      ></template>
    </Table>
  </div>
  <Modal
    id="asset_add_IoT_item"
    title="關聯設備"
    :onCancel="onCancel"
    width="900"
  >
    <template #modalContent>
      <Table :columns="modalColumns" :dataSource="iotData" :withStyle="false">
        <template #bodyCell="{ record, column, index }">
          <template v-if="column.key === 'check'">
            <Checkbox
              name="device_guid"
              :value="record.device_guid"
              :onChange="onChange"
              :checked="
                iotCheckedList?.some(
                  ({ device_guid }) => device_guid === record.device_guid
                )
              "
            ></Checkbox>
          </template>
        </template>
      </Table>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="onCancel"
      >
        取消
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.prevent="onOk"
      >
        確定
      </button>
    </template></Modal
  >
</template>

<style lang="scss" scoped></style>
