<script setup lang="ts">
import {computed, ref} from 'vue';

import {useVbenModal} from '@vben/common-ui';
import {$t} from '@vben/locales';
import {cloneDeep} from '@vben/utils';

import {useVbenForm} from '#/adapter/form';
import {
  resident_unitAdd,
  resident_unitInfo,
  resident_unitUpdate,
} from '#/api/property/resident/unit';
import {defaultFormValueGetter, useBeforeCloseDiff} from '#/utils/popup';

import {modalSchema} from './data';
import RoomTree from "./components/room-tree.vue";
import {message} from "ant-design-vue";

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认label宽度 px
    labelWidth: 100,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: modalSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const {onBeforeClose, markInitialized, resetInitialized} = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  // 在这里更改宽度
  class: 'w-[70%]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const {id} = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;
    if (isUpdate.value && id) {
      const record = await resident_unitInfo(id);
      let roomIds = record.location.split(',')
      await formApi.setValues({
        ...record,
        authTime: [record.authBegDate, record.authEndDate],
      });
      checkedRoomId.value = roomIds
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const {valid} = await formApi.validate();
    if (!checkedRoomId.value.length) {
      message.error('请选择入驻位置');
      return;
    }
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());

    data.authBegDate = data.authTime[0];
    data.authEndDate = data.authTime[1];
    data.location = checkedRoomId.value.join(',')
    await (isUpdate.value ? resident_unitUpdate(data) : resident_unitAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

const checkedRoomId = ref<string[]>([]);
</script>

<template>
  <BasicModal :title="title">
    <div class="flex  gap-[8px]">
      <div class="w-[260px]">
        <RoomTree
          :checkable="true"
          class="max-h-[calc(100vh-45vh)]"
          v-model:checked-room-id="checkedRoomId"
        />
      </div>
      <BasicForm class="flex-1"></BasicForm>
    </div>
  </BasicModal>
</template>
