<script setup>
import { onMounted, ref, inject, onBeforeMount, watch, computed } from "vue";
import EffectScatter from "@/components/chart/EffectScatter.vue";
import { getAssetFloorList, postAssetFloor } from "@/apis/asset";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import * as yup from "yup";
import { twMerge } from "tailwind-merge";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;

const { updateRightFields, formErrorMsg, formState } = inject(
  "asset_table_modal_form"
);

let schema = {
  floor_guid: yup.string().nullable(true),
  device_coordinate: yup.string().nullable(true),
};
onBeforeMount(() => {
  const data = {
    floor_guid: "",
    device_coordinate: "",
  };
  updateRightFields(schema, data);
});

const asset_floor_chart = ref(null);
const currentFloor = ref(null);
const defaultOption = (map, data = []) => ({
  tooltip: {},
  geo: {
    tooltip: {
      show: false,
    },
    map,
    roam: true, // 一定要关闭拖拽
  },
  series: {
    type: "effectScatter",
    coordinateSystem: "geo",
    geoIndex: 0,
    symbolSize: 10,
    itemStyle: {
      color: "#b02a02",
    },
    encode: {
      tooltip: 2,
    },
    data,
  },
});
watch(currentFloor, (newValue) => {
  if (newValue?.floor_map_name) {
    asset_floor_chart.value.updateSvg(
      {
        full_name: newValue?.floor_map_name,
        path: `${FILE_BASEURL}/${newValue?.floor_map_url}.svg`,
      },
      defaultOption(newValue?.floor_map_name, [
        formState.value.device_coordinate
          ? JSON.parse(formState.value.device_coordinate)
          : [],
      ])
    );
  }
});
const floors = ref([]);

const getFloors = async () => {
  const res = await getAssetFloorList();
  floors.value = res.data[0]?.floors.map((d) => ({ ...d, key: d.floor_guid }));
};

watch(
  formState,
  (newValue) => {
    if (newValue.floor_guid) {
      const floor = floors.value.find(
        ({ floor_guid }) => floor_guid === newValue.floor_guid
      );
      currentFloor.value = floor;
    } else {
      currentFloor.value = null;
    }
  },
  {
    deep: true,
  }
);

const getCoordinate = (position) => {
  formState.value.device_coordinate = JSON.stringify(position);
};

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

// modal
const openModal = () => {
  asset_add_floor.showModal();
};

const form = ref(null);
const FloorFormState = ref({
  building_tag: "F3",
  full_name: "",
  floorFile: [],
});

const floorScheme = yup.object({
  building_tag: yup.string().required(t("button.required")),
  full_name: yup.string().required(t("button.required")),
  floorFile: yup.array(),
});

const updateFileList = (files) => {
  FloorFormState.value.floorFile = files;
};

const {
  formErrorMsg: floorFormErrorMsg,
  handleSubmit,
  handleErrorReset,
  updateScheme,
} = useFormErrorMessage(floorScheme);
const onOk = async () => {
  const value = handleSubmit(floorScheme, FloorFormState.value);

  const formData = new FormData(form.value);
  formData.append("floor_guid", "");
  formData.append("initMapName", FloorFormState.value.floorFile[0].name);
  formData.append("mapFile", FloorFormState.value.floorFile[0]);
  formData.delete("floorFile");
  for (let [key, value] of formData) {
    console.log(key, value);
  }

  const res = await postAssetFloor(formData);
  if (res.isSuccess) {
    getFloors();
    onCancel();
  }
};

const onCancel = () => {
  FloorFormState.value = {
    building_tag: "F3",
    full_name: "",
    floorFile: [],
  };
  asset_add_floor.close();
};
</script>

<template>
  <!-- 平面圖 -->

  <div class="flex items-center justify-between mb-5">
    <div class="flex justify-start">
      <Select
        :value="formState"
        selectClass="border-info focus-within:border-info"
        name="floor_guid"
        Attribute="full_name"
        :options="floors"
        :isBottomLabelExist="false"
      >
        <template #topLeft>{{ t("assetManagement.floor") }}</template>
      </Select>
      <button
        type="button"
        class="btn btn-success mt-10 ml-5"
        @click="openModal"
      >
        {{ t("assetManagement.add_floor") }}
      </button>
    </div>
    <!-- <button type="button" class="btn btn-success mt-10">確認座標</button> -->
  </div>
  <div class="relative">
    <EffectScatter
      id="asset_floor_chart"
      ref="asset_floor_chart"
      :getCoordinate="getCoordinate"
      :class="
        twMerge(
          'absolute top-0 left-0',
          currentFloor?.floor_map_url ? 'opacity-1' : 'opacity-0'
        )
      "
    />
    <div
      v-if="!currentFloor?.floor_map_url"
      class="absolute top-0 left-0 flex justify-center items-center min-h-[500px] w-full border border-stone-900 shadow-lg bg-sub-success bg-opacity-25 rounded-md"
    >
      <p class="text-2xl">{{ t("assetManagement.add_floor_text") }}</p>
    </div>
  </div>
  <Modal
    id="asset_add_floor"
    :title="t('assetManagement.floor_plan')"
    :onCancel="onCancel"
    width="400"
  >
    <template #modalContent>
      <form ref="form">
        <Input :value="FloorFormState" width="270" name="full_name">
          <template #topLeft>{{ $t("assetManagement.system_name") }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ floorFormErrorMsg.full_name }}
            </span></template
          ></Input
        >
        <Upload
          name="floorFile"
          :fileList="FloorFormState.floorFile"
          :getFileList="updateFileList"
          :multiple="false"
          class="col-span-2"
        >
          <template #topLeft>{{ $t("assetManagement.oriFile") }}</template>
        </Upload>
      </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="onOk">
        {{ $t("button.submit") }}
      </button>
    </template></Modal
  >
</template>

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