<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    @ok="handleSubmit"
    @cancel="resetForm"
    :width="500"
    :height="100"
  >
    <template #footer>
      <div v-if="isUpdate !== 3">
        <a-button type="default" @click="handleCancle">取消</a-button>
        <a-button type="primary" @click="handleSubmit">确认</a-button>
      </div>
    </template>
    <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 { energyModalSchemas } from "./info.data";
import { GetLatLng } from "@/components/GetLatLng";

defineOptions({ name: "InfoModal" });

const emit = defineEmits(["register", "reload"]);
const postList = ref<Post[]>([]);
const isUpdate = ref<number>(1);
const title = computed<string>(() => {
  return "节能电梯设置";
});

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

function handleCancle() {
  closeModal();
  resetForm();
}
const [
  registerForm,
  { setFieldsValue, resetForm, validate, updateSchema, setProps },
] = useForm({
  labelWidth: 200,
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
  schemas: energyModalSchemas,
});
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>
