<script setup>
import { onMounted, ref, inject, computed, watch } from "vue";
import { getAssetList, postAssetElecSetting } from "@/apis/asset";
import { useI18n } from "vue-i18n";
import { twMerge } from "tailwind-merge";
import useBuildingStore from "@/stores/useBuildingStore";
import { getElecTypeList } from "@/apis/asset";

const { t } = useI18n();
const { openToast, cancelToastOpen } = inject("app_toast");
const storeBuild = useBuildingStore();
const departmentList = computed(() => storeBuild.deptList);
const floors = computed(() => storeBuild.floorList);
const elecType = ref([]);
const isEditing = ref(false);
const tableData = ref([]);
const columns = computed(() => [
  {
    title: t("assetManagement.operation"),
    key: "operation",
    width: 100,
  },
  {
    title: t("assetManagement.device_number"),
    key: "device_number",
    class: "break-all",
  },
  {
    title: t("assetManagement.device_name"),
    key: "full_name",
    filter: true,
    class: "break-all",
  },
  {
    title: t("assetManagement.floor"),
    key: "floor",
    filter: true,
    sort: true,
  },
  {
    title: t("assetManagement.department"),
    key: "department",
    filter: true,
  },
  {
    title: t("energy.electricity_classification"),
    key: "elecType",
    filter: true,
  },
]);

const getElecType = async () => {
  const res = await getElecTypeList();
  elecType.value = res.data.map((d, index) => ({
    ...d,
    key: d.id,
  }));
};

const getAssetData = async () => {
  // Electricity Meter P3
  const res = await getAssetList(465);
  if (res.isSuccess) {
    tableData.value = res.data.map((d) => ({
      ...d,
      key: d.id,
      floor: floors.value.find(({ floor_guid }) => d.floor_guid === floor_guid)
        ?.full_name,
      department: departmentList.value.find(({ id }) => d.department_id === id)
        ?.name,
      elecType: elecType.value.find(({ id }) => d.elec_type_id === id)?.name,
    }));
  }
};

const onOk = async () => {
  const formData = tableData.value.map((item) => ({
    main_id: item.main_id,
    is_demand: item.is_demand,
  }));
  const res = await postAssetElecSetting(formData);
  if (res.isSuccess) {
    onCancel();
  } else {
    openToast("error", res.msg);
  }
};

const onCancel = async () => {
  isEditing.value = false;
  await getAssetData();
};

const Check = (id) => {
  const items = tableData.value.find((d) => d.main_id === id);
  items.is_demand = items.is_demand ? 0 : 1;
};

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

watch(
  [floors, departmentList],
  () => {
    if (floors.value.length > 0 && departmentList.value.length > 0) {
      getAssetData();
    }
  },
  { immediate: true }
);
</script>

<template>
  <div class="flex justify-start items-center mt-10 mb-5">
    <h3 class="text-xl mr-5">電表</h3>
    <button
      v-if="!isEditing"
      class="btn btn-sm btn-add mr-3"
      @click.stop.prevent="isEditing = true"
    >
      <font-awesome-icon :icon="['fas', 'pencil-alt']" />{{
        $t("button.start_edit")
      }}
    </button>
    <template v-else>
      <button class="btn btn-sm btn-add mr-3" @click.prevent="onOk()">
        <font-awesome-icon :icon="['fas', 'save']" />{{ $t("button.confirm") }}
      </button>
      <button
        class="btn btn-sm btn-outline-info mr-3"
        @click.stop.prevent="onCancel()"
      >
        <font-awesome-icon :icon="['fas', 'times']" />{{ $t("button.cancel") }}
      </button>
    </template>
  </div>
  <Table :columns="columns" :dataSource="tableData" class="mt-3">
    <template #bodyCell="{ record, column, index }">
      <template v-if="column.key === 'operation'">
        <template v-if="!isEditing">
          <FontAwesomeIcon
            v-if="record.is_demand"
            :icon="['fas', 'check-circle']"
            size="lg"
            class="text-gray-300"
          />
          <FontAwesomeIcon
            v-else
            :icon="['far', 'circle']"
            size="lg"
            class="text-gray-300"
          />
        </template>
        <template v-else>
          <Checkbox
            :checked="record.is_demand"
            @click="() => Check(record.main_id)"
          ></Checkbox>
        </template>
      </template>
      <template v-else>
        {{ record[column.key] }}
      </template>
    </template>
  </Table>
</template>

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