<template>
  <el-dialog :model-value="visible" class="account-edit-dialog" top="6vh" width="640px" destroy-on-close
    :close-on-click-modal="false" @update:model-value="(v) => !v && close()">
    <div class="body-wrap">
      <div class="body-header">
        <span class="body-title">
          {{ isEdit ? $t('modal.editAccount') : $t('modal.addAccount') }}
        </span>
        <img src="@/assets/image/close-btn.svg" alt="" class="close-btn" @click="close" />
      </div>

      <div class="account-edit" v-loading="loading">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="right">
          <!-- 医院账号字段：编辑时 医院名称/账号(只读)/姓名/性别；新增时 医院名称/账号/密码/姓名/性别 -->
          <template v-if="props.userType === 'Hospital'">
            <!-- 新增模式 -->
            <template v-if="!isEdit">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :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-col>
                <el-col :span="12">
                  <el-form-item :label="$t('table.account')" prop="username">
                    <el-input v-model="form.username" :placeholder="$t('placeholder.account')" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="$t('label.password')" prop="password">
                    <el-input v-model="form.password" :type="showPwd ? 'text' : 'password'" autocomplete="new-password"
                      :placeholder="$t('placeholder.password')">
                      <template #suffix>
                        <el-icon class="pwd-toggle-icon" @click="showPwd = !showPwd">
                          <View v-if="showPwd" />
                          <Hide v-else />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('table.name')" prop="name">
                    <el-input v-model="form.name" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="$t('table.gender')">
                    <el-select v-model="form.gender" style="width: 100%">
                      <el-option label="男" value="男" />
                      <el-option label="女" value="女" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            <!-- 编辑模式：一行两个 -->
            <template v-else>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="$t('table.hospital')" prop="hospitalId">
                    <el-select :key="`hospital-${hospitalOptions.length}`" 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-col>
                <el-col :span="12">
                  <el-form-item :label="$t('table.account')" prop="username">
                    <el-input v-model="form.username" disabled :placeholder="$t('placeholder.account')" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="$t('table.name')" prop="name">
                    <el-input v-model="form.name" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('table.gender')">
                    <el-select v-model="form.gender" style="width: 100%">
                      <el-option label="男" value="男" />
                      <el-option label="女" value="女" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </template>

          <!-- 管理员账号字段：编辑时 账号(只读)/姓名/性别/角色；新增时 账号/密码/姓名/性别/角色 -->
          <template v-else>
            <!-- 新增模式 -->
            <template v-if="!isEdit">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="$t('table.account')" prop="username">
                    <el-input v-model="form.username" :placeholder="$t('placeholder.account')" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('label.password')" prop="password">
                    <el-input v-model="form.password" :type="showPwd ? 'text' : 'password'" autocomplete="new-password"
                      :placeholder="$t('placeholder.password')">
                      <template #suffix>
                        <el-icon class="pwd-toggle-icon" @click="showPwd = !showPwd">
                          <View v-if="showPwd" />
                          <Hide v-else />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="$t('table.name')" prop="name">
                    <el-input v-model="form.name" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('table.gender')">
                    <el-select v-model="form.gender" style="width: 100%">
                      <el-option label="男" value="男" />
                      <el-option label="女" value="女" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :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-col>
              </el-row>
            </template>
            <!-- 编辑模式：一行两个 -->
            <template v-else>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="$t('table.account')" prop="username">
                    <el-input v-model="form.username" disabled :placeholder="$t('placeholder.account')" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('table.name')" prop="name">
                    <el-input v-model="form.name" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="$t('table.gender')">
                    <el-select v-model="form.gender" style="width: 100%">
                      <el-option label="男" value="男" />
                      <el-option label="女" value="女" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :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-col>
              </el-row>
            </template>
          </template>
        </el-form>
      </div>
    </div>

    <div class="body-footer">
      <el-button @click="close">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" :loading="submitting" @click="submit">
        {{ isEdit ? $t('common.save') : $t('common.add') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { computed, reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { View, Hide } from "@element-plus/icons-vue";
import { useI18n } from "vue-i18n";
import {
  createAdminAccount,
  updateAdminAccount,
  getAdminHospitals,
} from "@/service/modular/admin";

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

const props = defineProps({
  visible: { type: Boolean, default: false },
  accountId: { type: [String, Number], default: "" },
  // 当前点击的表格行数据；编辑时直接从行取数，避免再调一次列表接口
  accountData: { type: Object, default: () => ({}) },
  userType: { type: String, default: "Hospital" },
});

const emit = defineEmits(["update:visible", "success"]);

const loading = ref(false);
const submitting = ref(false);
const formRef = ref();
const isEdit = computed(() => !!props.accountId);
// 自控制密码框可见性，避免 el-input show-password 后缀动态布局导致输入框抖动
const showPwd = ref(false);

const hospitalOptions = ref([]);
const hospitalsLoaded = ref(false);

const buildForm = () => ({
  username: "",
  password: "",
  name: "",
  gender: "男",
  userType: props.userType,
  hospitalId: undefined,
  role: "",
});

const form = reactive(buildForm());

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" },
  ],
  hospitalId: [
    {
      validator: (_, value, cb) => {
        if (props.userType === 'Hospital' && !value) {
          return cb(new Error($t('msg.pleaseSelectHospital')));
        }
        cb();
      },
      trigger: "change",
    },
  ],
  role: [
    {
      validator: (_, value, cb) => {
        if (props.userType === 'Admin' && !value) {
          return cb(new Error($t('table.role')));
        }
        cb();
      },
      trigger: "change",
    },
  ],
};

const resetForm = () => {
  Object.assign(form, buildForm());
  formRef.value?.clearValidate();
};

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

const fillFormFromRow = async () => {
  loading.value = true;
  try {
    // 医院端需先加载医院选项，否则 el-select 找不到对应 option 无法回显
    if (props.userType === 'Hospital') {
      await loadHospitals();
    }
    const row = props.accountData || {};
    // 当前行的医院姓名字段为 hospitalName，在医院下拉选项中按 name 反查 id
    const matched = hospitalOptions.value.find((h) => h.name === row.hospitalName);
    Object.assign(form, {
      username: row.username || "",
      name: row.name,
      gender: row.gender || "男",
      userType: row.userType || props.userType,
      hospitalId: matched?.id,
      role: row.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(props.accountId, {
          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: props.userType,
          hospitalId: form.hospitalId,
          role: form.role,
        });
        ElMessage.success($t('msg.accountAddSuccess'));
      }
      emit("success");
      emit("update:visible", false);
    } finally {
      submitting.value = false;
    }
  });
};

const close = () => emit("update:visible", false);

watch(
  () => [props.visible, props.accountId, props.userType],
  ([vis, id]) => {
    if (vis) {
      showPwd.value = false;
      resetForm();
      if (id) { fillFormFromRow() }
      else {
        if (props.userType === 'Hospital') {
          loadHospitals();
        }
      }
    }
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
.account-edit {
  max-height: 60vh;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 4px;
}

.pwd-toggle-icon {
  cursor: pointer;
  color: #909399;
  display: inline-flex;
  align-items: center;
  height: 100%;
  font-size: 16px;
}
</style>

<style lang="scss">
.account-edit-dialog {
  min-width: 520px;
  max-width: 90vw;

  .body-header {
    margin-bottom: 18px;
  }

  // 固定密码框后缀区域宽度 + 右侧内边距，避免切换可见图标时输入框伸长导致布局抖动
  .el-input.is-show-password .el-input__suffix,
  .el-input.is-show-password .el-input__suffix-inner {
    width: 30px !important;
    min-width: 30px !important;
  }

  .el-input.is-show-password .el-input__inner {
    padding-right: 50px !important;
    box-sizing: border-box;
  }

  // 去掉密码框自身的过渡动画，避免后缀区出现/隐藏时插值产生的轻微位移
  .el-input.is-show-password,
  .el-input.is-show-password .el-input__inner,
  .el-input.is-show-password .el-input__suffix {
    transition: none !important;
  }
}
</style>
