<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    width="900px"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { dataFormSchema } from './data';

  import { sysUserAdd, sysUserEdit, sysUserDetail } from '/@/api/sys/sysUserApi';
  import { sysConfigCurrent } from '/@/api/sys/sysConfigApi';

  const emit = defineEmits(['success', 'register']);

  const getTitle = computed(() => (!unref(isUpdate) ? '新增用户' : '编辑用户'));
  const isUpdate = ref(false);
  const rowId = ref();

  const { createMessage } = useMessage();
  const [registerForm, { setFieldsValue, resetFields, validate, updateSchema, getFieldsValue }] =
    useForm({
      labelWidth: 100,
      schemas: dataFormSchema,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 23,
      },
      baseColProps: { lg: 12, md: 24 },
    });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      const resData = await sysUserDetail(data.record.id);
      resData.sex = String(resData.sex || '3');
      resData.orgId = String(resData.orgId);
      await updateSchema([
        {
          field: 'username',
          componentProps: {
            disabled: true,
          },
          dynamicRules: false,
        },
      ]);
      await setFieldsValue({
        ...resData,
      });
    } else {
      let sysInitPassword = '123456';
      await sysConfigCurrent().then(data => {
        if (data && data.defaultPsw) {
          sysInitPassword = data.defaultPsw;
        }
      });
      await setFieldsValue({
        password: sysInitPassword,
      });
    }
    await updateSchema([
      {
        field: 'password',
        ifShow: !unref(isUpdate),
      },
    ]);
    const fildValue = getFieldsValue();
    console.log('fildValue', fildValue);
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      console.log('values', values);
      console.log('values::::::::', values);
      !unref(isUpdate)
        ? await sysUserAdd({ ...values })
        : await sysUserEdit({ ...values, id: rowId.value });
      !unref(isUpdate) ? createMessage.success('新增成功！') : createMessage.success('编辑成功！');
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
