<template>
  <div>
    <a-modal
      v-model:visible="visible"
      width="auto"
      :title="$t('searchTable.form.add')"
      @cancel="() => handleCancel()"
      @before-ok="handleBeforeOk"
    >
      <a-form :model="form" ref="formRef">
        <a-row :gutter="8">
          <a-col :span="12">
            <a-form-item
              field="name"
              :label="t('manage.form.name')"
              :rules="getRules(t).required"
            >
              <a-input v-model="form.name" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="password"
              :label="t('manage.form.password')"
              :rules="getRules(t).required"
            >
              <a-input v-model="form.password" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="desc" :label="t('manage.form.desc')">
              <a-input v-model="form.desc" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="privilege"
              :label="t('manage.form.permission')"
              :rules="getRules(t).required"
            >
              <a-select
                v-model="form.privilege"
                allow-clear
                @clear="form.privilege = null"
              >
                <a-option
                  v-for="item of privilegeList"
                  :value="item.value"
                  :label="item.label"
                />
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts" name="EditDialog">
import { reactive, ref, shallowRef, watch, getCurrentInstance } from 'vue';
import { fetchSaveUser, getUserInfo } from '@/api/user';
import type { UserData } from '@/api/user';
import { privilegeList } from '@/utils/const';
import { useI18n } from 'vue-i18n';
import { getRules } from '@/utils/const';
const formRef = ref();
const { t } = useI18n();

const this_ = getCurrentInstance()?.appContext.config.globalProperties;

interface EditDialogProps {
  modelValue: boolean;
  id: number | null;
}
interface EditDialogEmits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'update-list'): void;
}
const props = withDefaults(defineProps<EditDialogProps>(), {
  modelValue: false,
  id: null,
});
const emit = defineEmits<EditDialogEmits>();
const visible = shallowRef<boolean>(false);

watch(
  () => props.modelValue,
  value => {
    visible.value = value;
    if (value && props.id) {
      getUserInfo({ id: props.id }).then(res => {
        form.value = res.data;
      });
    }
  }
);
const formModel = () => {
  return {
    id: 0,
    name: '',
    password: '',
  } as UserData['data'];
};
const form = ref<UserData['data']>(formModel());

const handleBeforeOk = (done: (closed: boolean) => void) => {
  formRef.value.validate().then((data: UserData['data']) => {
    if (!data) {
      fetchSaveUser(form.value)
        .then(res => {
          this_?.$message.success('操作成功');
          done(true); // 关闭模态框
          handleCancel();
        })
        .catch(() => {
          done(false); // 不关闭模态框（例如提交失败时）
        });
    } else {
      done(false); // 不关闭模态框（例如提交失败时）
    }
  });
};
const handleCancel = () => {
  form.value = formModel();
  visible.value = false;
  emit('update:modelValue', false);
  emit('update-list');
};
</script>
