<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";

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) {
    props.getData();
    closeModal();
  } 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')
    "
    :open="open"
    :onCancel="closeModal"
    width="1600"
  >
    <template #modalContent>
      <form ref="form" class="grid grid-cols-4 gap-5">
        <div class="col-span-4 lg:col-span-2">
          <div class="lg:grid lg:grid-cols-2 items-end gap-2">
            <AssetTableModalLeft
              :current_component_key="current_component_key"
            />
          </div>
        </div>
        <div class="col-span-4 lg:col-span-2">
          <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>
