<template>
  <div class="account-edit" v-loading="loading">
    <el-page-header :icon="ArrowLeft" :content="$t('common.back')" @back="goBack" class="page-header">
      <template #content>
        <span class="page-title">{{ isEdit ? $t('modal.editAccount') : $t('modal.addAccount') }}</span>
      </template>
    </el-page-header>

    <el-card shadow="never">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        style="max-width: 600px"
      >
        <el-form-item v-if="!isEdit" :label="$t('table.account')" prop="username">
          <el-input v-model="form.username" :placeholder="$t('placeholder.account')" />
        </el-form-item>
        <el-form-item v-if="!isEdit" :label="$t('label.password')" prop="password">
          <el-input v-model="form.password" type="password" show-password :placeholder="$t('placeholder.password')" />
        </el-form-item>
        <el-form-item :label="$t('table.name')" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item :label="$t('table.gender')">
          <el-radio-group v-model="form.gender">
            <el-radio-button label="男">男</el-radio-button>
            <el-radio-button label="女">女</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('label.accountType')" prop="userType">
          <el-radio-group v-model="form.userType">
            <el-radio-button label="Admin">管理员</el-radio-button>
            <el-radio-button label="Hospital">医院端</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.userType === 'Hospital'" :label="$t('table.hospital')" prop="hospitalId">
          <el-select
            v-model="form.hospitalId"
            :placeholder="$t('msg.pleaseSelectHospital')"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in hospitalOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.userType === 'Admin'" :label="$t('table.role')" prop="role">
          <el-select v-model="form.role" :placeholder="$t('table.role')" style="width: 100%">
            <el-option label="超级管理员" value="超级管理员" />
            <el-option label="客户经理" value="客户经理" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="submit">
            {{ isEdit ? $t('common.save') : $t('common.add') }}
          </el-button>
          <el-button @click="goBack">{{ $t('common.cancel') }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import { useI18n } from "vue-i18n";
import {
  getAdminAccounts,
  createAdminAccount,
  updateAdminAccount,
  getAdminHospitals,
} from "@/service/modular/admin";

const { t: $t } = useI18n();

const hospitalOptions = ref([]);

const loadHospitals = async () => {
  try {
    const res = await getAdminHospitals();
    hospitalOptions.value = res?.list || [];
  } catch (e) {
    // request 层已统一提示错误
  }
};

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const submitting = ref(false);
const formRef = ref();
const isEdit = computed(() => !!route.params.id);

const form = reactive({
  username: "",
  password: "",
  name: "",
  gender: "男",
  userType: "Admin",
  hospitalId: undefined,
  role: "",
});

const rules = {
  username: [{ required: true, message: () => $t('placeholder.account'), trigger: "blur" }],
  password: [{ required: true, message: () => $t('placeholder.password'), trigger: "blur" }],
  name: [{ required: true, message: () => $t('account.pleaseInputName'), trigger: "blur" }],
  userType: [{ required: true, message: () => $t('label.accountType'), trigger: "change" }],
};

const loadDetail = async () => {
  if (!isEdit.value) return;
  loading.value = true;
  try {
    const res = await getAdminAccounts({ page: 1, pageSize: 1000 });
    const found = (res?.list || []).find((it) => String(it.id) === String(route.params.id));
    if (found) {
      Object.assign(form, {
        name: found.name,
        gender: found.gender || "男",
        userType: found.userType || "Admin",
        hospitalId: found.hospitalId,
        role: found.role,
      });
    }
  } finally {
    loading.value = false;
  }
};

const submit = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    submitting.value = true;
    try {
      if (isEdit.value) {
        await updateAdminAccount(route.params.id, {
          name: form.name,
          gender: form.gender,
          hospitalId: form.hospitalId,
          role: form.role,
        });
        ElMessage.success($t('msg.accountEditSuccess'));
      } else {
        await createAdminAccount({
          username: form.username,
          password: form.password,
          name: form.name,
          gender: form.gender,
          userType: form.userType,
          hospitalId: form.hospitalId,
          role: form.role,
        });
        ElMessage.success($t('msg.accountAddSuccess'));
      }
      router.replace("/admin/accounts");
    } finally {
      submitting.value = false;
    }
  });
};

const goBack = () => router.back();

onMounted(() => {
  loadHospitals();
  loadDetail();
});
</script>

<style scoped lang="scss">
.page-header {
  margin-bottom: 12px;
  .page-title {
    font-size: 16px;
    font-weight: 600;
  }
}
</style>
