<script setup lang="ts">
import { reactive, ref } from "vue";
import { addAdminUser, modifyAdminUser, getAdminUserDetail, getAdminRoleList, updateUserRole } from "@/api/admin";
import { ElMessage } from "element-plus";

const emit = defineEmits(["refresh"]);

const formRef = ref();
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const loading = ref(false);

const state = reactive({
  ruleForm: {
    id: null as number | null,
    username: "",
    nickname: "",
    mobilePhone: "",
    password: "",
    avatar: "",
    status: 1,
    stationIdList: [] as string[]
  },
  rules: {
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
    mobilePhone: [
      { required: true, message: "请输入手机号", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
    ],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }]
  },
  roleList: [] as any[],
  checkRoleIdList: [] as number[]
});

const resetForm = () => {
  state.ruleForm = {
    id: null,
    username: "",
    nickname: "",
    mobilePhone: "",
    password: "",
    avatar: "",
    status: 1,
    stationIdList: []
  };
  state.checkRoleIdList = [];
  formRef.value?.resetFields();
};

const getTitle = () => {
  return dialogType.value === "add" ? "新增运维账户" : "编辑运维账户";
};

const isEdit = () => dialogType.value === "edit";

const open = async (type: "add" | "edit", row?: any) => {
  dialogType.value = type;
  resetForm();

  // 加载角色列表
  try {
    const roles = await getAdminRoleList();
    state.roleList = roles || [];
    if (type === "add" && state.roleList.length > 0) {
      state.checkRoleIdList = [state.roleList[0].id];
    }
  } catch (e) {
    // ignore
  }

  if (type === "edit" && row) {
    loading.value = true;
    try {
      const res = await getAdminUserDetail(row.id);
      const { adminUser, roles: userRoles } = res || {};
      Object.assign(state.ruleForm, adminUser || {});
      if (userRoles) {
        state.checkRoleIdList = userRoles.map((k: any) => k.roleId);
      }
    } catch (e) {
      ElMessage.error("获取详情失败");
    } finally {
      loading.value = false;
    }
  }
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;

  loading.value = true;
  try {
    if (dialogType.value === "add") {
      const res = await addAdminUser(state.ruleForm);
      if (res?.id) {
        state.ruleForm.id = res.id;
      }
    } else {
      await modifyAdminUser(state.ruleForm);
    }

    // 更新角色
    if (state.ruleForm.id) {
      await updateUserRole({
        userId: state.ruleForm.id,
        roleIdList: state.checkRoleIdList
      });
    }

    ElMessage.success("操作成功");
    handleClose();
    emit("refresh");
  } catch (e) {
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};

defineExpose({ open });
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="getTitle()"
    width="650px"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="state.ruleForm" :rules="state.rules" label-width="120px" :disabled="loading">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="state.ruleForm.username" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="state.ruleForm.nickname" placeholder="请输入昵称" clearable />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!isEdit()">
        <el-input
          v-model="state.ruleForm.password"
          type="password"
          placeholder="请输入密码"
          show-password
          clearable
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobilePhone">
        <el-input v-model="state.ruleForm.mobilePhone" placeholder="请输入手机号" clearable />
      </el-form-item>
      <el-form-item label="角色">
        <el-checkbox-group v-model="state.checkRoleIdList">
          <el-checkbox v-for="role in state.roleList" :key="role.id" :label="role.id">
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button :loading="loading" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
