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

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

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

import {modalSchema} from './data';
import {communityTree} from "#/api/property/community";
import {costItemSettingList} from "#/api/property/costManagement/costItemSetting";
import type {CostItemSettingVO} from "#/api/property/costManagement/costItemSetting/model";
import {getDictOptions} from "#/utils/dict";

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

const isUpdate = ref(false);
const costItemOptions = ref<CostItemSettingVO[]>([]);
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: 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-[550px]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);
    await initRoomOptions()
    await queryCostItemOptions()
    await initCostTypeOptions()
    const {id} = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await houseChargeInfo(id);
      record.chargeTime = [record.startTime, record.endTime]
      await formApi.setValues(record);
    }
    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());
    if (data.chargeTime && data.chargeTime.length) {
      data.startTime = data.chargeTime[0]
      data.endTime = data.chargeTime[1]
    }
    await (isUpdate.value ? houseChargeUpdate(data) : houseChargeAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

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

/**
 * 房间数据
 */
async function initRoomOptions() {
  const roomList = await communityTree(5);
  const splitStr = '/';
  handleNode(roomList, 'label', splitStr, function (node: any) {
    if (node.level != 5) {
      node.disabled = true;
    }
  });
  formApi.updateSchema([
    {
      componentProps: () => ({
        class: 'w-full',
        fieldNames: {
          key: 'id',
          label: 'label',
          value: 'code',
          children: 'children',
        },
        placeholder: '请选择房间',
        showSearch: true,
        treeData: roomList,
        treeDefaultExpandAll: true,
        treeLine: {showLeafIcon: false},
        // 筛选的字段
        treeNodeFilterProp: 'label',
        // 选中后显示在输入框的值
        treeNodeLabelProp: 'fullName',
      }),
      fieldName: 'roomId',
    },
  ]);
}

/**
 * 查询费用项设置
 */
async function queryCostItemOptions(costType:string) {
  let params = {
    pageSize: 1000,
    pageNum: 1,
    costType
  }
  const res = await costItemSettingList(params)
  costItemOptions.value = res.rows
  formApi.updateSchema([{
    componentProps: {
      options: costItemOptions.value,
      fieldNames: {label: 'chargeItem', value: 'id'},
      showSearch: true,
      optionFilterProp: 'chargeItem',
      onChange: async (value: string) => {
        if (value) {
         const costItem = costItemOptions.value.find(item => item.id == value)
          if(costItem){
            await formApi.setFieldValue('remark', `单价：${costItem.unitPrice} 附加费：${costItem.surcharge}`);
          }
        }
      }
    },
    fieldName: 'costItemsId'
  }])
}

/**
 * 初始化费用类型
 */
async function initCostTypeOptions(){
  formApi.updateSchema([{
    componentProps: {
      options: getDictOptions('pro_expense_type'),
      onChange: async (value: string) => {
        if (value) {
          await queryCostItemOptions(value)
          await formApi.setFieldValue('costItemsId', null)
        }
      }
    },
    fieldName: 'costType'
  }])
}
</script>

<template>
  <BasicModal :title="title">
    <BasicForm/>
  </BasicModal>
</template>

