<script setup lang="ts">
import {computed, reactive, 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 { orderChargeAdd, orderChargeInfo, orderChargeUpdate } from '#/api/property/chargeManagement';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { modalSchema } from './data';
import QueryUserList from "#/views/property/greenPlantRentalManagement/chargeManagement/query-user-list.vue";

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

const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : '添加收费';
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    formItemClass: 'col-span-1',
    labelWidth: 80,
    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-[60%]',
  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 orderChargeInfo(id);
      await formApi.setValues(record);
    }
    await markInitialized();
    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    if (userInfo) {
      console.log(userInfo);
      data.userId = userInfo.value
      data.userName = userInfo.userName
    }
    await (isUpdate.value ? orderChargeUpdate(data) : orderChargeAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}
let userInfo = reactive({
  value:'',
  userId: '',
  userName: '',
});
const userName = ref<number | string>('');
function getUserInfo(user: any) {
  userInfo = user;
}
async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title">
    <BasicForm>
      <template #userName="slotProps">
        <QueryUserList @update:userInfo="getUserInfo" v-bind="slotProps" :isUpdate="isUpdate" :userName="userName"/>
      </template>
    </BasicForm>
  </BasicModal>
</template>

