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

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

import {useVbenForm} from '#/adapter/form';
import {
  houseChargeAdd,
  houseChargeInfo,
  houseChargeUpdate
} from '#/api/property/costManagement/houseCharge';
import {defaultFormValueGetter, useBeforeCloseDiff} from '#/utils/popup';

import {modalSchemaUpdate} from './data';
import {renderDict} from "#/utils/render";
import {Descriptions, DescriptionsItem, Divider} from "ant-design-vue";
import type {HouseChargeVO} from "#/api/property/costManagement/houseCharge/model";
import type {RoomVO} from "#/api/property/room/model";
import type {CostItemSettingVO} from "#/api/property/costManagement/costItemSetting/model";

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

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

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

const [BasicModal, modalApi] = useVbenModal({
  // 在这里更改宽度
  class: 'w-[550px]',
  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;
    record.value = await houseChargeInfo(id);
    if (record.value) {
      room.value = record.value.roomVo
      costItem.value = record.value.costItemsVo
    }
    await formApi.setValues(record.value);
    await markInitialized();

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

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const {valid} = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());
    record.value.payType = data.payType
    record.value.chargeCycle = data.chargeCycle
    record.value.chargeStatus = '4'
    await houseChargeUpdate(record.value);
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

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

</script>

<template>
  <BasicModal title="缴费">
    <Descriptions v-if="record" size="small" :column="2"
                  :labelStyle="{width:'80px'}">
      <DescriptionsItem label="费用编号">
        {{ costItem?.id }}
      </DescriptionsItem>
      <DescriptionsItem label="费用项目">
        {{ costItem?.chargeItem }}
      </DescriptionsItem>
      <DescriptionsItem label="费用类型">
        <component
          v-if="costItem"
          :is="renderDict(costItem?.costType,'pro_expense_type')"
        />
      </DescriptionsItem>
      <DescriptionsItem label="计费起始">
        {{ record.startTime }}
      </DescriptionsItem>
      <DescriptionsItem label="房间">
        {{ room?.roomNumber }}
      </DescriptionsItem>
      <DescriptionsItem label="面积(㎡)">
        {{ `${room?.area} （套内面积：${room?.insideInArea}）` }}
      </DescriptionsItem>
      <DescriptionsItem label="单价">
        {{ costItem?.unitPrice }}
      </DescriptionsItem>
      <DescriptionsItem label="附加费">
        {{ costItem?.surcharge }}
      </DescriptionsItem>
      <DescriptionsItem label="缴费金额" :span="2">
        <span style="font-size: 16px;font-weight: 600;color: red" v-if="record.amountReceivable">
         ￥ {{ record.amountReceivable }}
        </span>
      </DescriptionsItem>
    </Descriptions>
    <Divider/>
    <BasicForm/>
  </BasicModal>
</template>

