<script setup>
import { getAssetList, postAssetSingle } from "@/apis/asset";
import { inject, defineProps, watch, ref, provide } from "vue";
import useSearchParam from "@/hooks/useSearchParam";
import AssetTableModalLeft from "./AssetTableModalLeft.vue";
import AssetTableModalRight from "./AssetTableModalRight.vue";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import * as yup from "yup";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const { openToast } = inject("app_toast");
const { searchParams, changeParams } = useSearchParam();

const props = defineProps({
  openModal: Function,
  onCancel: Function,
  getData: Function,
  editRecord: Object,
});

const form = ref(null);
const formState = ref(null); // 透過 update 更新
const scheme = ref(null); // 透過 update 更新
const { formErrorMsg, handleSubmit, handleErrorReset, updateScheme } =
  useFormErrorMessage(scheme.value);

watch(
  () => props.editRecord,
  (newValue) => {
    if (newValue) {
      formState.value = newValue;
    }
  }
);

// info, module
const current_component_key = ref("info");

const updateLeftFields = (dataScheme, data) => {
  formState.value = { ...formState.value, ...data };
  scheme.value = { ...scheme.value, ...dataScheme };
};
const updateRightFields = (dataScheme, data) => {
  formState.value = { ...formState.value, ...data };
  scheme.value = { ...scheme.value, ...dataScheme };
};
const clearFields = () => {
  formState.value = null;
};

watch(
  [current_component_key, scheme],
  ([newKey, newScheme], [oldKey, oldScheme]) => {
    if (newKey !== oldKey) {
      clearFields();
    }
    if (newScheme !== oldScheme) {
      scheme.value = newScheme;
      updateScheme(yup.object(newScheme));
    }
  }
);

provide("asset_table_modal_form", {
  updateLeftFields,
  updateRightFields,
  formErrorMsg,
  formState,
});

const onOk = async () => {
  const values = await handleSubmit(yup.object(scheme.value), formState.value);
  const res = await postAssetSingle({
    ...values,
    variable_id: searchParams.value.subSys_id,
    main_id: props.editRecord ? props.editRecord.main_id : 0,
  });
  if (res.isSuccess) {
    openToast("success", t("msg.send_successfully"), "#asset_add_table_item");
    props.getData();
    setTimeout(() => {
      closeModal();
    }, 1000);
  } else {
    openToast("error", res.msg, "#asset_add_table_item");
  }
};

const resetForm = () => {
  let resetData = {};
  for (let [key, value] of Object.entries(formState.value)) {
    if (Array.isArray(value)) {
      resetData[key] = [];
    } else {
      resetData[key] = "";
    }
  }
  formState.value = resetData;
};

const closeModal = () => {
  resetForm();
  handleErrorReset();
  props.onCancel();
};
</script>

<template>
  <button
    class="btn btn-sm btn-add mr-3"
    @click.stop.prevent="openModal"
    :disabled="!searchParams.subSys_id"
  >
    <font-awesome-icon :icon="['fas', 'plus']" />{{ $t("button.add") }}
  </button>
  <Modal
    id="asset_add_table_item"
    :title="
      editRecord?.main_id
        ? $t('assetManagement.edit_device')
        : $t('assetManagement.add_device')
    "
    :onCancel="closeModal"
    :width="1600"
  >
    <template #modalContent>
      <form ref="form" class="grid grid-cols-5 gap-5">
        <div class="grid grid-cols-2 col-span-2 items-end">
          <AssetTableModalLeft :current_component_key="current_component_key" />
        </div>
        <div class="col-span-3">
          <AssetTableModalRight
            :current_component_key="current_component_key"
          />
        </div>
      </form>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="closeModal"
      >
        {{ $t("button.cancel") }}
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.prevent="onOk"
      >
        {{ $t("button.submit") }}
      </button>
    </template>
  </Modal>
</template>

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