<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 } from "@/api/basicInfo/elevator";
import { accessModalSchemas } from "./info.data";
import { GetLatLng } from "@/components/GetLatLng";
import {
  elevatorAccessoryAdd,
  elevatorAccessoryInfo,
  elevatorAccessoryUpdate,
} from "@/api/basicInfo/evaAccess";

defineOptions({ name: "InfoModal" });

const emit = defineEmits(["register", "reload"]);
const postList = ref<Post[]>([]);
const isUpdate = ref<number>(1);
const elevatorNum = ref<any>("");
const title = computed<string>(() => {
  return isUpdate.value === 1
    ? "编辑配件信息"
    : isUpdate.value === 2
    ? "新增配件信息"
    : "查看配件信息";
});

const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
  async (data: { record?: Recordable; elevatorInfo; update: number }) => {
    modalLoading(true);
    const { record, update, elevatorInfo } = data;
    elevatorNum.value = elevatorInfo.elevatorNum;

    isUpdate.value = update;
    if (isUpdate.value === 3) {
      setProps({ disabled: true });
    } else {
      setProps({ disabled: false });
    }
    if ((update === 1 || update === 3) && record) {
      const ret = await elevatorAccessoryInfo(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: 12 },
  schemas: accessModalSchemas,
});
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 (isUpdate.value === 1) {
      await elevatorAccessoryUpdate({ ...data, elevatorNum: elevatorNum.value });
    } else {
      await elevatorAccessoryAdd({ ...data, elevatorNum: elevatorNum.value });
    }
    emit("reload");
    closeModal();
    await resetForm();
  } catch (e) {
    console.warn(e);
  } finally {
    modalLoading(false);
  }
}
</script>

<style scoped></style>
