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

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

import { useVbenForm } from '#/adapter/form';
import {
  meetAdd,
  meetInfo,
  meetUpdate,
} from '#/api/property/roomBooking/conferenceSettings';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { modalSchema } from './data';
import { TimeRangePicker } from 'ant-design-vue';
import { renderDictValue } from '#/utils/render';
import { personList } from '#/api/property/resident/person';
import { communityTree } from '#/api/property/community';
import dayjs from 'dayjs';
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: 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-[70%]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);
    await formApi.setValues({
      expenseType: '1',
      isCheck: '0',
    });
    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;
    await queryPerson();
    await initLocationOptions();
    if (isUpdate.value && id) {
      const record = await meetInfo(id);
      record.expenseType = record.expenseType.toString();
      record.isCheck = record.isCheck.toString();
      let hour = record.openHours.split('-');
      if (hour.length > 1) {
        record.openHours = [dayjs(hour[0], 'HH:mm'), dayjs(hour[1], 'HH:mm')];
      }
      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.openHours) {
      data.openHours =
        data.openHours[0]?.format('HH:mm') +
        '-' +
        data.openHours[1]?.format('HH:mm');
    }
    await (isUpdate.value ? meetUpdate(data) : meetAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

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

async function queryPerson() {
  let params = {
    pageSize: 1000,
    pageNum: 1,
  };
  const res = await personList(params);
  const options = res.rows.map((user) => ({
    label:
      user.userName +
      '-' +
      renderDictValue(user.gender, 'sys_user_sex') +
      '-' +
      user.phone,
    value: user.id,
  }));
  formApi.updateSchema([
    {
      componentProps: () => ({
        options: options,
        filterOption: filterOption,
        showSearch: true,
      }),
      fieldName: 'principals',
    },
  ]);
}

const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

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

<template>
  <BasicModal :title="title">
    <BasicForm>
      <template #openHours="slotProps">
        <TimeRangePicker v-bind="slotProps" format="HH:mm"></TimeRangePicker>
      </template>
    </BasicForm>
  </BasicModal>
</template>
