<template>
  <div class="groups-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span
            >小组管理
            {{
              currentDepartmentName ? `(${currentDepartmentName})` : ''
            }}</span
          >
          <el-button
            v-if="currentDepartmentIdFromQuery"
            @click="clearDepartmentFilter"
            type="info"
            size="small"
            >清除科室筛选</el-button
          >
        </div>
      </template>

      <!-- Header / Actions -->
      <div class="header-actions">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item
            label="所属医院"
            v-if="
              userStore.role === 'SYSTEM_ADMIN' && !currentDepartmentIdFromQuery
            "
          >
            <el-select
              v-model="searchForm.hospitalId"
              placeholder="请选择医院"
              clearable
              @change="handleSearchHospitalChange"
            >
              <el-option
                v-for="h in hospitals"
                :key="h.id"
                :label="h.name"
                :value="h.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属科室" v-if="!currentDepartmentIdFromQuery">
            <el-select
              v-model="searchForm.departmentId"
              placeholder="请选择科室"
              clearable
              @change="fetchData"
              :disabled="
                userStore.role === 'SYSTEM_ADMIN' && !searchForm.hospitalId
              "
            >
              <el-option
                v-for="d in searchDepartments"
                :key="d.id"
                :label="d.name"
                :value="d.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="小组名称">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入关键词"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchData" icon="Search"
              >查询</el-button
            >
            <el-button @click="resetSearch" icon="Refresh">重置</el-button>
            <el-button
              v-if="canCreateGroup"
              type="success"
              @click="openCreateDialog"
              icon="Plus"
              >新增小组</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <!-- Table -->
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="小组名称" min-width="150" />
        <el-table-column
          prop="department.name"
          label="所属科室"
          min-width="150"
        />
        <el-table-column
          prop="department.hospital.name"
          label="所属医院"
          min-width="150"
          v-if="userStore.role === 'SYSTEM_ADMIN'"
        />
        <el-table-column label="小组组长" min-width="180">
          <template #default="{ row }">
            {{ getLeaderDisplay(row.id) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ new Date(row.createdAt).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              v-if="canEditGroup"
              size="small"
              type="primary"
              @click="openEditDialog(row)"
              >编辑</el-button
            >
            <el-button
              v-if="canDeleteGroup"
              size="small"
              type="danger"
              @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchData"
          @current-change="fetchData"
        />
      </div>
    </el-card>

    <!-- Dialog for Create / Edit -->
    <el-dialog
      :title="isEdit ? '编辑小组' : '新增小组'"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item
          label="所属医院"
          prop="hospitalId"
          v-if="userStore.role === 'SYSTEM_ADMIN'"
        >
          <el-select
            v-model="form.hospitalId"
            placeholder="请选择所属医院"
            style="width: 100%"
            @change="handleFormHospitalChange"
          >
            <el-option
              v-for="h in hospitals"
              :key="h.id"
              :label="h.name"
              :value="h.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属科室" prop="departmentId">
          <el-select
            v-model="form.departmentId"
            placeholder="请选择所属科室"
            style="width: 100%"
            :disabled="userStore.role === 'SYSTEM_ADMIN' && !form.hospitalId"
          >
            <el-option
              v-for="d in formDepartments"
              :key="d.id"
              :label="d.name"
              :value="d.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="小组名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入小组名称" />
        </el-form-item>
        <el-form-item label="小组组长" v-if="canAssignLeaderInDialog">
          <el-select
            v-model="form.leaderUserId"
            placeholder="可选：选择后将任命为小组组长"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in leaderOptions"
              :key="user.id"
              :label="`${user.name}（${user.phone} / ${getRoleName(user.role)}）`"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitLoading"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getGroups,
  createGroup,
  updateGroup,
  deleteGroup,
  getHospitals,
  getDepartments,
} from '../../api/organization';
import { getUsers, updateUser } from '../../api/users';
import { useUserStore } from '../../store/user';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// --- State ---
const loading = ref(false);
const tableData = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const hospitals = ref([]);
const leaderNameMap = ref({});
const leaderOptions = ref([]);

const roleMap = {
  LEADER: '小组组长',
  DOCTOR: '医生',
};

const getRoleName = (role) => roleMap[role] || role;

const searchDepartments = ref([]);
const formDepartments = ref([]);

const currentDepartmentIdFromQuery = computed(() => {
  return route.query.departmentId ? parseInt(route.query.departmentId) : null;
});

const currentHospitalIdFromQuery = computed(() => {
  return route.query.hospitalId ? parseInt(route.query.hospitalId) : null;
});

const currentDepartmentName = computed(() => {
  return route.query.departmentName || '';
});

const searchForm = reactive({
  keyword: '',
  hospitalId: null,
  departmentId: null,
});

// Dialog State
const dialogVisible = ref(false);
const isEdit = ref(false);
const submitLoading = ref(false);
const formRef = ref(null);
const currentId = ref(null);

const form = reactive({
  hospitalId: null,
  departmentId: null,
  name: '',
  leaderUserId: null,
});

const rules = computed(() => ({
  hospitalId:
    userStore.role === 'SYSTEM_ADMIN'
      ? [{ required: true, message: '请选择所属医院', trigger: 'change' }]
      : [],
  departmentId: [
    { required: true, message: '请选择所属科室', trigger: 'change' },
  ],
  name: [{ required: true, message: '请输入小组名称', trigger: 'blur' }],
}));
const canCreateGroup = computed(() =>
  ['SYSTEM_ADMIN', 'HOSPITAL_ADMIN', 'DIRECTOR'].includes(userStore.role),
);
const canEditGroup = computed(() =>
  ['SYSTEM_ADMIN', 'HOSPITAL_ADMIN', 'DIRECTOR', 'LEADER'].includes(
    userStore.role,
  ),
);
const canDeleteGroup = computed(() =>
  ['SYSTEM_ADMIN', 'HOSPITAL_ADMIN', 'DIRECTOR'].includes(userStore.role),
);
const canAssignLeaderInDialog = computed(() =>
  ['SYSTEM_ADMIN', 'HOSPITAL_ADMIN'].includes(userStore.role),
);

// --- Methods ---
const fetchHospitals = async () => {
  try {
    const res = await getHospitals({ pageSize: 100 });
    hospitals.value = res.list || [];
  } catch (error) {
    console.error('Failed to fetch hospitals', error);
  }
};

const handleSearchHospitalChange = async (hospitalId) => {
  searchForm.departmentId = null;
  searchDepartments.value = [];
  if (hospitalId) {
    try {
      const res = await getDepartments({ hospitalId, pageSize: 100 });
      searchDepartments.value = res.list || [];
    } catch (error) {}
  }
  fetchData();
};

const handleFormHospitalChange = async (hospitalId) => {
  form.departmentId = null;
  form.leaderUserId = null;
  formDepartments.value = [];
  if (hospitalId) {
    try {
      const res = await getDepartments({ hospitalId, pageSize: 100 });
      formDepartments.value = res.list || [];
    } catch (error) {}
  }
};

const loadLeaderOptions = async (hospitalId, departmentId, groupId) => {
  if (!canAssignLeaderInDialog.value || !hospitalId || !departmentId) {
    leaderOptions.value = [];
    return;
  }

  const userRes = await getUsers();
  const users = Array.isArray(userRes?.list) ? userRes.list : [];
  leaderOptions.value = users.filter((user) => {
    if (user.role !== 'LEADER') {
      return false;
    }
    if (user.hospitalId !== hospitalId || user.departmentId !== departmentId) {
      return false;
    }
    if (groupId == null) {
      return true;
    }
    return user.groupId == null || user.groupId === groupId;
  });
};

const fetchData = async () => {
  loading.value = true;
  try {
    const activeDepartmentId =
      currentDepartmentIdFromQuery.value || searchForm.departmentId;
    const activeHospitalId =
      currentHospitalIdFromQuery.value || searchForm.hospitalId;
    const [groupRes, leaderRes] = await Promise.all([
      getGroups({
        page: page.value,
        pageSize: pageSize.value,
        keyword: searchForm.keyword || undefined,
        departmentId: activeDepartmentId || undefined,
        hospitalId: activeHospitalId || undefined,
      }),
      getUsers({ role: 'LEADER' }),
    ]);

    const leaderMap = {};
    (leaderRes.list || []).forEach((user) => {
      if (!user.groupId) {
        return;
      }
      if (!leaderMap[user.groupId]) {
        leaderMap[user.groupId] = [];
      }
      leaderMap[user.groupId].push(user.name);
    });
    leaderNameMap.value = leaderMap;

    tableData.value = groupRes.list || [];
    total.value = groupRes.total || 0;
  } catch (error) {
    console.error('Failed to fetch groups', error);
  } finally {
    loading.value = false;
  }
};

const getLeaderDisplay = (groupId) => {
  const leaders = leaderNameMap.value[groupId] || [];
  return leaders.length > 0 ? leaders.join('、') : '未设置';
};

const resetSearch = () => {
  searchForm.keyword = '';
  if (!currentDepartmentIdFromQuery.value) {
    searchForm.hospitalId = null;
    searchForm.departmentId = null;
    searchDepartments.value = [];
  }
  page.value = 1;
  fetchData();
};

const clearDepartmentFilter = () => {
  router.replace({ path: '/organization/groups' });
};

const openCreateDialog = async () => {
  isEdit.value = false;
  currentId.value = null;
  form.hospitalId =
    userStore.role === 'SYSTEM_ADMIN'
      ? currentHospitalIdFromQuery.value || searchForm.hospitalId || null
      : userStore.userInfo?.hospitalId;
  if (userStore.role === 'SYSTEM_ADMIN' && form.hospitalId) {
    await handleFormHospitalChange(form.hospitalId);
  }
  form.departmentId =
    currentDepartmentIdFromQuery.value || searchForm.departmentId || null;
  form.leaderUserId = null;
  await loadLeaderOptions(form.hospitalId, form.departmentId, null);
  dialogVisible.value = true;
};

const openEditDialog = async (row) => {
  isEdit.value = true;
  currentId.value = row.id;
  form.name = row.name;

  // Try to find the hospital ID from the nested relation, assuming row.department.hospitalId exists
  // if not, we can rely on row.department?.hospital?.id
  const hospitalId = row.department?.hospitalId || row.department?.hospital?.id;
  form.hospitalId = hospitalId;

  if (hospitalId) {
    await handleFormHospitalChange(hospitalId);
  }
  form.departmentId = row.departmentId;
  form.leaderUserId = null;
  await loadLeaderOptions(form.hospitalId, form.departmentId, row.id);

  dialogVisible.value = true;
};

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.name = '';
  form.hospitalId = null;
  form.departmentId = null;
  form.leaderUserId = null;
  formDepartments.value = [];
  leaderOptions.value = [];
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true;
      try {
        let targetGroupId = null;
        let targetDepartmentId = form.departmentId;
        let targetHospitalId = form.hospitalId;
        if (isEdit.value) {
          // Backend patch dto might just accept name. Sending departmentId may not be allowed or needed.
          const updated = await updateGroup(currentId.value, {
            name: form.name,
          });
          targetGroupId = updated?.id ?? currentId.value;
          targetDepartmentId = updated?.departmentId ?? form.departmentId;
          targetHospitalId = updated?.department?.hospitalId ?? form.hospitalId;
          ElMessage.success('更新成功');
        } else {
          const created = await createGroup({
            name: form.name,
            departmentId: form.departmentId,
          });
          targetGroupId = created?.id;
          targetDepartmentId = created?.departmentId ?? form.departmentId;
          ElMessage.success('创建成功');
        }

        if (
          canAssignLeaderInDialog.value &&
          form.leaderUserId &&
          targetGroupId &&
          targetDepartmentId &&
          targetHospitalId
        ) {
          await updateUser(form.leaderUserId, {
            role: 'LEADER',
            hospitalId: targetHospitalId,
            departmentId: targetDepartmentId,
            groupId: targetGroupId,
          });
          ElMessage.success('小组组长已设置');
        }

        dialogVisible.value = false;
        fetchData();
      } catch (error) {
        console.error('Submit failed', error);
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除小组 "${row.name}" 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await deleteGroup(row.id);
        ElMessage.success('删除成功');
        fetchData();
      } catch (error) {
        console.error('Delete failed', error);
      }
    })
    .catch(() => {});
};

// --- Lifecycle ---
onMounted(async () => {
  if (userStore.role === 'SYSTEM_ADMIN') {
    await fetchHospitals();
  } else {
    // For non-admin, just fetch the departments they have access to
    try {
      const res = await getDepartments({ pageSize: 100 });
      searchDepartments.value = res.list || [];
      formDepartments.value = res.list || [];
    } catch (e) {}
  }
  fetchData();
});

watch(
  () => route.query,
  () => {
    page.value = 1;
    fetchData();
  },
);

watch(
  () => [form.hospitalId, form.departmentId],
  async ([hospitalId, departmentId]) => {
    if (!dialogVisible.value) {
      return;
    }
    await loadLeaderOptions(
      hospitalId,
      departmentId,
      isEdit.value ? currentId.value : null,
    );
  },
);
</script>

<style scoped>
.groups-container {
  padding: 0;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-actions {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
