<!--
 * @Author: Mm
 * @Date: 2025-05-06 16:20:51
 * @LastEditors: hcc
 * @LastEditTime: 2025-06-09 10:00:59
 * 不写bug的程序员不是一个好程序员!
-->
<script setup lang="ts">
import { computed, 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 { userAdd, userInfo, userBan } from '#/api/im/user';

import { modalBanSchema } from './data';
import { renderText } from '#/utils/render';

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',
    },
  },
  layout: 'vertical',
  schema: modalBanSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const [BasicModal, modalApi] = useVbenModal({
  // 在这里更改宽度
  class: 'w-[850px]',
  fullscreenButton: true,
  // 点击遮罩是否关闭
  closeOnClickModal: false,
  // showConfirmButton: false,
  // showCancelButton: false,
  onCancel: handleCancel,
  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 userInfo(id);
      record.sex = record.sex ? renderText(record.sex, 'sys_user_sex') : ''; //直接回显文字
      record.isBanned = record.isBanned
        ? renderText(record.isBanned, 'im_bool')
        : ''; //直接回显文字

      await formApi.setValues(record);
    }

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

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? userBan(data) : userAdd(data));
    emit('reload');
    await handleCancel();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleCancel() {
  modalApi.close();
  await formApi.resetForm();
}
</script>

<template>
  <BasicModal title="封禁">
    <BasicForm />
  </BasicModal>
</template>
