<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    @ok="handleSubmit"
    @cancel="resetForm"
    :width="1200"
  >
    <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,
  infoRunDataInfo,
  infoBadDataInfo,
} 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<number>(1);
const title = computed<string>(() => {
  return isUpdate.value === 1
    ? "编辑电梯故障数据详情"
    : isUpdate.value === 2
    ? "新增电梯故障数据详情"
    : "查看电梯故障数据详情";
});
const customTitle = ref<string>("选择小区");

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 infoBadDataInfo(record.id);
      await setFieldsValue(ret);
    }
    modalLoading(false);
  }
);

const [registerForm, { setFieldsValue, resetForm, validate, setProps }] = useForm({
  labelWidth: 200,
  showActionButtonGroup: false,
  baseColProps: { span: 12 },
  schemas: modalSchemas,
});
const getLatLng = (data) => {
  console.log(data, "data");
  setFieldsValue({ lat: data.lat, lng: data.lng });
};
function handleCancle() {
  closeModal();
  resetForm();
}
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>
