<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';
import { resident_unitList } from '#/api/property/resident/unit';
import type { FormSchemaGetter } from '#/adapter/form';
import { rentalNotSelectList } from '#/api/property/rentalOrder';
import { getDictOptions } from '#/utils/dict';

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

const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : '添加收费';
});
const modalSchema = [
  {
    label: '主键',
    fieldName: 'id',
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
  },
  {
    label: '订单号',
    fieldName: 'orderNo',
    component: 'Input',
    dependencies: {
      show: () => isUpdate.value,
      triggerFields: [''],
    },
    disabled: true,
  },
  {
    label: '订单号',
    fieldName: 'orderId',
    component: 'ApiSelect',
    componentProps: {
      api: rentalNotSelectList,
      resultField: 'rows',
      labelField: 'orderNo',
      valueField: 'id',
      onChange: async (value: any, option: any) => {
        console.log(option);

        await formApi.setValues({
          residentUnitId: option.residentUnitId, // 假设订单数据中有 residentUnitId 字段
          // 其他需要自动填充的字段
        });
      },
    },
    rules: 'required',
    dependencies: {
      show: () => !isUpdate.value,
      triggerFields: [''],
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'residentUnitId',
    label: '租赁单位',
    componentProps: () => ({
      api: getUnitList,
      resultField: 'data',
      labelField: 'label',
      valueField: 'value',
      immediate: true,
      debounceTime: 500,
      allowClear: true,
      placeholder: '',
      filterOption: true,
    }),

    rules: 'selectRequired',
    disabled: true,
  },
  {
    label: '租赁人',
    fieldName: 'userName',
    component: 'Select',
    rules: 'selectRequired',
  },

  {
    label: '租金',
    fieldName: 'rent',
    component: 'InputNumber',
    rules: 'required',
    componentProps: {
      precision: 2,
    },
  },
  {
    label: '押金',
    fieldName: 'deposit',
    component: 'InputNumber',
    rules: 'required',
    componentProps: {
      precision: 2,
    },
  },
  {
    label: '违约金',
    fieldName: 'penalty',
    component: 'InputNumber',
    rules: 'required',
    componentProps: {
      precision: 2,
    },
  },
  // {
  //   label: '总金额',
  //   fieldName: 'totalAmount',
  //   component: 'Input',
  //   rules: 'required',
  // },
  {
    label: '开票状态',
    fieldName: 'invoiceStatus',
    component: 'Select',
    componentProps: {
      options: getDictOptions('pro_invoice_status'),
    },
    rules: 'selectRequired',
  },
  {
    label: '发票类型',
    fieldName: 'invoiceType',
    component: 'Select',
    componentProps: {
      options: getDictOptions('pro_invoice_type'),
    },
    rules: 'selectRequired',
  },
  {
    label: '收费状态',
    fieldName: 'chargeStatus',
    component: 'Select',
    componentProps: {
      options: getDictOptions('pro_charging_status'),
    },
    rules: 'selectRequired',
  },
  {
    label: '支付方式',
    fieldName: 'paymentMethod',
    component: 'Select',
    componentProps: {
      options: getDictOptions('pro_payment_method'),
    },
    rules: 'selectRequired',
  },
  {
    label: '收费日期',
    fieldName: 'chargeDate',
    component: 'DatePicker',
    componentProps: {
      showTime: true,
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
    },
    rules: 'required',
  },
];
async function getUnitList() {
  const queryParam = {
    pageNum: 1,
    pageSize: 1000,
  };
  const res = await resident_unitList(queryParam);
  const data: { value: number; label: string }[] = [];

  res.rows.forEach((r: any) => {
    data.push({
      value: r.id,
      label: r.name,
    });
  });
  return data;
}
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);
      record.chargeStatus = record.chargeStatus?.toString();
      record.paymentMethod = record.paymentMethod?.toString();
      record.invoiceType = record.invoiceType?.toString();
      record.invoiceStatus = record.invoiceStatus?.toString();
      record.orderNo = record.rentalOrder?.orderNo;
      record.residentUnitId = record.residentUnitId;
      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) {
      data.userId = userInfo.userId;
      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({
  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>
