<template>
  <div class="dashboard">
    <el-card shadow="never" class="welcome-card">
      <h2>欢迎使用调压通管理后台</h2>
      <p>当前角色：{{ getRoleLabel(userStore.role) || '未登录' }}</p>
    </el-card>

    <el-card v-if="isSystemAdmin" shadow="never" class="filter-card">
      <el-form inline>
        <el-form-item label="患者统计医院">
          <el-select
            v-model="selectedHospitalId"
            placeholder="请选择医院"
            style="width: 280px"
            @change="fetchDashboardData"
          >
            <el-option
              v-for="hospital in hospitals"
              :key="hospital.id"
              :label="hospital.name"
              :value="hospital.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="16" v-loading="loading">
      <el-col
        :xs="24"
        :sm="12"
        :lg="6"
        v-for="item in statCards"
        :key="item.key"
      >
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">{{ item.title }}</div>
          <div class="stat-value">{{ item.value }}</div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never" class="tips-card">
      <template #header>
        <span>接口接入说明</span>
      </template>
      <el-alert
        type="info"
        :closable="false"
        title="患者页负责发布调压任务并指定接收人，任务页只查看调压记录；工程师完成任务后会自动回写当前压力。"
      />
    </el-card>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import { useUserStore } from '../store/user';
import { getHospitals, getDepartments, getGroups } from '../api/organization';
import { getUsers } from '../api/users';
import { getPatients } from '../api/patients';
import { getRoleLabel } from '../constants/role-labels';

const userStore = useUserStore();
const loading = ref(false);
const hospitals = ref([]);
const selectedHospitalId = ref(null);

const stats = ref({
  hospitals: '-',
  departments: '-',
  groups: '-',
  users: '-',
  patients: '-',
});

const isSystemAdmin = computed(() => userStore.role === 'SYSTEM_ADMIN');
const canViewOrg = computed(() =>
  ['SYSTEM_ADMIN', 'HOSPITAL_ADMIN'].includes(userStore.role),
);
const canViewUsers = computed(() =>
  ['SYSTEM_ADMIN', 'HOSPITAL_ADMIN'].includes(userStore.role),
);
const canViewPatients = computed(() =>
  ['SYSTEM_ADMIN', 'HOSPITAL_ADMIN', 'DIRECTOR', 'LEADER', 'DOCTOR'].includes(
    userStore.role,
  ),
);

const statCards = computed(() => {
  const cards = [];

  if (canViewOrg.value) {
    cards.push(
      { key: 'hospitals', title: '医院总数', value: stats.value.hospitals },
      { key: 'departments', title: '科室总数', value: stats.value.departments },
      { key: 'groups', title: '小组总数', value: stats.value.groups },
    );
  }

  if (canViewUsers.value) {
    cards.push({
      key: 'users',
      title: '用户总数',
      value: stats.value.users,
    });
  }

  if (canViewPatients.value) {
    cards.push({
      key: 'patients',
      title: '可见患者数',
      value: stats.value.patients,
    });
  }

  return cards;
});

const fetchHospitalsForFilter = async () => {
  if (!isSystemAdmin.value) {
    return;
  }
  const res = await getHospitals({ page: 1, pageSize: 100 });
  hospitals.value = res.list || [];
  if (!selectedHospitalId.value && hospitals.value.length > 0) {
    selectedHospitalId.value = hospitals.value[0].id;
  }
};

const fetchDashboardData = async () => {
  loading.value = true;
  try {
    if (canViewOrg.value) {
      const [hospitalRes, departmentRes, groupRes] = await Promise.all([
        getHospitals({ page: 1, pageSize: 1 }),
        getDepartments({ page: 1, pageSize: 1 }),
        getGroups({ page: 1, pageSize: 1 }),
      ]);

      stats.value.hospitals = hospitalRes.total ?? 0;
      stats.value.departments = departmentRes.total ?? 0;
      stats.value.groups = groupRes.total ?? 0;
    }

    if (canViewUsers.value) {
      const usersRes = await getUsers({
        page: 1,
        pageSize: 1,
      });
      stats.value.users = usersRes.total ?? 0;
    }

    if (canViewPatients.value) {
      const params = {};
      if (isSystemAdmin.value && selectedHospitalId.value) {
        params.hospitalId = selectedHospitalId.value;
      }
      if (isSystemAdmin.value && !selectedHospitalId.value) {
        stats.value.patients = 0;
      } else {
        const patientRes = await getPatients({
          page: 1,
          pageSize: 1,
          ...params,
        });
        stats.value.patients = Number(
          patientRes?.total ??
            (Array.isArray(patientRes)
              ? patientRes.length
              : patientRes?.list?.length ?? 0),
        );
      }
    }
  } finally {
    loading.value = false;
  }
};

onMounted(async () => {
  await fetchHospitalsForFilter();
  await fetchDashboardData();
});
</script>

<style scoped>
.dashboard {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.welcome-card h2 {
  margin: 0 0 10px;
}

.welcome-card p {
  margin: 0;
}

.stat-card {
  min-height: 120px;
}

.stat-title {
  color: #909399;
  margin-bottom: 12px;
}

.stat-value {
  font-size: 32px;
  font-weight: 600;
  color: #303133;
}
</style>
