<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    @ok="handleSubmit"
    @cancel="resetForm"
    :width="1200"
  >
    <BasicForm @register="registerForm">
      <template #getLatLng="{ model, field }"
        ><GetLatLng @getLatLng="getLatLng"></GetLatLng>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script setup lang="ts">
import { BasicModal, useModalInner } from "@/components/Modal";
import { BasicForm, useForm } from "@/components/Form";
import { computed, reactive, ref, unref } from "vue";
import { infoInfo, infoAdd, infoUpdate } from "@/api/basicInfo/elevator";
import { modalSchemas } from "./info.data";
import { GetLatLng } from "@/components/GetLatLng";
defineOptions({ name: "InfoModal" });

const emit = defineEmits(["register", "reload"]);

const isUpdate = ref<boolean>(false);
const title = computed<string>(() => {
  return isUpdate.value ? "编辑电梯基础信息;" : "新增电梯基础信息;";
});
const customTitle = ref<string>("选择小区");

const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
  async (data: { record?: Recordable; update: boolean }) => {
    modalLoading(true);
    const { record, update } = data;
    isUpdate.value = update;
    if (update && record) {
      const ret = await infoInfo(record.id);
      await setFieldsValue(ret);
    }
    modalLoading(false);
  }
);

const [registerForm, { setFieldsValue, resetForm, validate }] = useForm({
  labelWidth: 200,
  showActionButtonGroup: false,
  baseColProps: { span: 12 },
  schemas: modalSchemas,
});
const getLatLng = (data) => {
  console.log(data, "data");
  setFieldsValue({ lat: data.lat, lng: data.lng });
};
async function handleSubmit() {
  try {
    modalLoading(true);
    const data = await validate();
    if (unref(isUpdate)) {
      await infoUpdate(data);
    } else {
      await infoAdd(data);
    }
    emit("reload");
    closeModal();
    await resetForm();
  } catch (e) {
    console.warn(e);
  } finally {
    modalLoading(false);
  }
}
</script>

<style scoped></style>
