<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.name" prefix-icon="Search" style="width: 240px; margin-right: 10px; margin-bottom: 3px" placeholder="请输入患者姓名"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin-right: 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd" v-if="data.user && data.user.role === 'admin'">新增</el-button>
      <span v-if="data.user && data.user.role === 'doctor'" class="role-tip">您正在查看您的患者</span>
    </div>

    <div class="card" style="margin-bottom: 5px;">
      <el-table :data="data.tableData" stripe>
        <el-table-column label="ID" prop="id" width="80"></el-table-column>
        <el-table-column label="头像" width="80">
          <template v-slot="scope">
            <el-avatar :size="40" :src="scope.row.avatar" @error="handleAvatarError">
              {{ scope.row.name ? scope.row.name.charAt(0) : '用户' }}
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="账号" prop="username"></el-table-column>
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="性别" prop="sex"></el-table-column>
        <el-table-column label="手机号" prop="phone"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" plain @click="handleDelete(scope.row.id)" v-if="data.user && data.user.role === 'admin'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination 
        @current-change="load" 
        background 
        layout="total, prev, pager, next" 
        :page-size="10" 
        v-model:current-page="data.pageNum" 
        :total="data.total"/>
    </div>

    <el-dialog :title="data.dialogTitle" v-model="data.dialogVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" label-width="100px" style="padding: 20px 30px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="data.form.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="data.isAdd">
          <el-input v-model="data.form.password" show-password placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="data.form.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="data.form.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="data.form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="data.form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted } from "vue";
import { Search, Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue';
import request from "@/utils/request";
import { ElMessage } from "element-plus";

const data = reactive({
  name: "",
  tableData: [],
  total: 0,
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  dialogTitle: "",
  isAdd: false,
  form: {},
  user: null, // 存储当前登录用户信息
  search: {}
});

// 获取当前登录用户信息
const getCurrentUser = () => {
  const userStr = localStorage.getItem("xm-user");
  if (userStr) {
    try {
      data.user = JSON.parse(userStr);
    } catch (e) {
      console.error("解析用户信息失败", e);
    }
  }
};

// 处理头像加载错误
const handleAvatarError = () => {
  return true; // 忽略错误，使用默认文字头像
};

// 加载数据
const load = () => {
  data.search.pageNum = data.pageNum;
  data.search.pageSize = 10;
  data.search.name = data.name;
  
  request
    .get("/patient/selectPage", {
      params: data.search
    })
    .then((res) => {
      if (res.code === "200") {
        data.tableData = res.data.list || [];
        data.total = res.data.total;
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(err => {
      console.error("加载患者数据失败", err);
      ElMessage.error("加载患者数据失败");
    });
};

// 重置查询条件
const reset = () => {
  data.name = "";
  load();
};

// 打开新增对话框
const handleAdd = () => {
  data.dialogVisible = true;
  data.dialogTitle = "新增患者";
  data.form = { sex: "男" };
  data.isAdd = true;
};

// 打开编辑对话框
const handleEdit = (row) => {
  data.dialogVisible = true;
  data.dialogTitle = "编辑患者";
  data.form = JSON.parse(JSON.stringify(row));
  data.isAdd = false;
};

// 删除
const handleDelete = (id) => {
  // 只允许管理员删除
  if (data.user && data.user.role !== 'admin') {
    ElMessage.warning("您没有删除权限");
    return;
  }
  
  request.delete("/patient/" + id).then((res) => {
    if (res.code === "200") {
      ElMessage.success("删除成功");
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 保存
const save = () => {
  if (!data.form.username || (data.isAdd && !data.form.password) || !data.form.name) {
    ElMessage.warning("请填写完整信息");
    return;
  }

  let url = "/patient";
  let method = data.isAdd ? "post" : "put";

  // 确保表单中包含角色信息
  data.form.role = "patient";

  request[method](url, data.form).then((res) => {
    if (res.code === "200") {
      ElMessage.success("保存成功");
      data.dialogVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const handleCurrentChange = (current) => {
  data.pageNum = current;
  load();
};

onMounted(() => {
  getCurrentUser();
  load();
});
</script>

<style scoped>
.card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
  background-color: #fff;
  color: #303133;
  margin: 10px 0;
  padding: 10px;
  border-radius: 6px;
}

.role-tip {
  color: #909399;
  font-size: 14px;
}
</style> 