<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" :label-width="formLabelWidth">
        <el-form-item :label="t('modules.auth.username')" prop="account">
          <el-input v-model="form.model.account" :placeholder="t('modules.auth.usernameRequired')"></el-input>
        </el-form-item>
        <el-form-item :label="t('modules.auth.adminRole')" prop="roleIds">
          <el-select v-model="form.model.roleIds" :placeholder="t('modules.auth.roleRequired')" multiple clearable
            style="width: 100%">
            <el-option v-for="item in role.list" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="modal.params.type === 'add'" :label="t('modules.auth.password')" prop="pwd">
          <el-input v-model="form.model.pwd" type="password" :placeholder="t('modules.auth.passwordRequired')"
            show-password></el-input>
        </el-form-item>
        <el-form-item v-if="modal.params.type === 'add'" :label="t('modules.auth.confirmPassword')"
          prop="confirmPassword">
          <el-input v-model="form.model.confirmPassword" type="password"
            :placeholder="t('modules.auth.confirmPasswordRequired')" show-password></el-input>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button v-if="modal.params.type == 'add'" type="primary" @click="confirm">{{ t('common.save') }}</el-button>
      <el-button v-if="modal.params.type == 'edit'" type="primary" @click="confirm">{{ t('common.update') }}</el-button>
    </el-footer>
  </el-container>
</template>
<script setup>
import { onMounted, reactive, ref, unref } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useFormConfig } from '@/hooks/useFormConfig';
import admin from '@/app/admin/api';

const { t } = useI18n();

// 使用表单配置hooks
const { formLabelWidth } = useFormConfig({ enWidth: '150px' });

const emit = defineEmits(['modalCallBack']);
const props = defineProps({
  modal: {
    type: Object,
  },
});

// 添加 编辑 form
let formRef = ref(null);
const form = reactive({
  model: {
    id: null,
    account: '',
    roleIds: [],
    pwd: '',
    confirmPassword: '',
  },
  rules: {
    account: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    roleIds: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
    pwd: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    ],
    confirmPassword: [
      { required: true, message: '请再次输入密码', trigger: 'blur' },
      {
        validator: (_, value, callback) => {
          if (value !== form.model.pwd) {
            callback(new Error('两次输入的密码不一致'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
  },
});
const loading = ref(false);

// 角色列表
const role = reactive({
  list: [],
});

// 获取角色列表
async function getRoleList() {
  try {
    const { code, data } = await admin.auth.role.roleList({
      page: 1,
      size: 100, // 获取所有角色
    });
    if (code == 200) {
      role.list = data.list || [];
    }
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error(t('message.fetchRoleListFailed'));
  }
}

// 获取详情
async function getDetail(id) {
  loading.value = true;
  try {
    const { code, data } = await admin.auth.user.detail(id);
    if (code == 200) {
      form.model.id = data.id;
      form.model.account = data.account || data.name;
      // 处理角色数据：从userRoles数组中提取roleId
      if (data.userRoles && Array.isArray(data.userRoles)) {
        form.model.roleIds = data.userRoles.map((item) => item.roleId);
      } else if (data.roleIds) {
        // 兼容旧的roleIds字段格式
        form.model.roleIds =
          typeof data.roleIds === 'string'
            ? data.roleIds.split(',').map((id) => parseInt(id))
            : data.roleIds;
      } else {
        form.model.roleIds = [];
      }
    }
  } catch (error) {
    console.error('获取详情失败:', error);
    ElMessage.error(t('message.fetchDetailFailed'));
  }
  loading.value = false;
}

// 表单关闭时提交
function confirm() {
  // 表单验证
  unref(formRef).validate(async (valid) => {
    if (!valid) return;

    try {
      let submitData = {};

      const isAdd = props.modal.params.type === 'add';

      // 构建提交数据
      submitData = {
        account: form.model.account,
        roleIds: form.model.roleIds.join(','),
        ...(isAdd && { pwd: form.model.pwd }), // 新增时才包含密码
        id: isAdd ? '' : props.modal.params.id, // 新增时id为空字符串，编辑时传递id
      };

      // 调用对应接口
      const { code } = isAdd
        ? await admin.auth.user.add(submitData)
        : await admin.auth.user.edit(submitData);

      if (code == 200) {
        ElMessage.success(isAdd ? t('message.createSuccess') : t('message.updateSuccess'));
        emit('modalCallBack', { event: 'confirm' });
      }
    } catch (error) {
      console.error('提交失败:', error);
      ElMessage.error(t('message.submitFailed'));
    }
  });
}

async function init() {
  await getRoleList(); // 获取角色列表
  if (props.modal.params.id) {
    await getDetail(props.modal.params.id);
  }
}

onMounted(() => {
  init();
});
</script>
