package com.example.controller;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.Result;
import com.example.common.config.TokenUtils;
import com.example.entity.Account;
import com.example.entity.Doctor;
import com.example.entity.DoctorPatient;
import com.example.entity.Patient;
import com.example.service.DoctorPatientService;
import com.example.service.PatientService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 患者控制器
 */
@RestController
@RequestMapping("/patient")
public class PatientController {

    @Resource
    private PatientService patientService;
    
    @Resource
    private DoctorPatientService doctorPatientService;

    /**
     * 新增
     */
    @PostMapping
    public Result add(@RequestBody Patient patient) {
        patientService.add(patient);
        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        patientService.deleteById(id);
        return Result.success();
    }

    /**
     * 更新
     */
    @PutMapping
    public Result update(@RequestBody Patient patient) {
        patientService.updateById(patient);
        return Result.success();
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Patient patient = patientService.selectById(id);
        return Result.success(patient);
    }

    /**
     * 查询全部
     */
    @GetMapping
    public Result findAll() {
        Account currentUser = TokenUtils.getCurrentUser();
        List<Patient> patients = new ArrayList<>();
        
        // 管理员可以查看所有患者
        if (currentUser != null && "admin".equals(currentUser.getRole())) {
            patients = patientService.selectAll(null);
        }
        // 医生只能查看自己的患者
        else if (currentUser != null && "doctor".equals(currentUser.getRole())) {
            List<DoctorPatient> doctorPatients = doctorPatientService.selectByDoctorId(currentUser.getId(), null);
            if (!doctorPatients.isEmpty()) {
                // 提取患者信息
                patients = doctorPatients.stream()
                        .map(DoctorPatient::getPatient)
                        .filter(p -> p != null)
                        .collect(Collectors.toList());
            }
        }
        // 患者只能查看自己的信息
        else if (currentUser != null && "patient".equals(currentUser.getRole())) {
            Patient patient = patientService.selectById(currentUser.getId());
            if (patient != null) {
                patients.add(patient);
            }
        }
        
        return Result.success(patients);
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "10") Integer pageSize,
                           @RequestParam(required = false) String name) {
        Account currentUser = TokenUtils.getCurrentUser();
        
        // 管理员可以查看所有患者
        if (currentUser != null && "admin".equals(currentUser.getRole())) {
            return Result.success(patientService.selectPage(pageNum, pageSize, name));
        }
        // 医生只能查看自己的患者
        else if (currentUser != null && "doctor".equals(currentUser.getRole())) {
            List<DoctorPatient> doctorPatients = doctorPatientService.selectByDoctorId(currentUser.getId(), name);
            
            if (!doctorPatients.isEmpty()) {
                // 提取患者信息
                List<Patient> patients = doctorPatients.stream()
                        .map(DoctorPatient::getPatient)
                        .filter(p -> p != null)
                        .collect(Collectors.toList());
                
                // 手动进行分页
                int total = patients.size();
                int fromIndex = (pageNum - 1) * pageSize;
                int toIndex = Math.min(fromIndex + pageSize, total);
                
                if (fromIndex >= total) {
                    patients = new ArrayList<>();
                } else {
                    patients = patients.subList(fromIndex, toIndex);
                }
                
                return Result.success(patients);
            } else {
                return Result.success(new ArrayList<>());
            }
        }
        // 患者只能查看自己的信息
        else if (currentUser != null && "patient".equals(currentUser.getRole())) {
            Patient patient = patientService.selectById(currentUser.getId());
            List<Patient> list = new ArrayList<>();
            if (patient != null) {
                list.add(patient);
            }
            return Result.success(list);
        }
        
        return Result.error("401", "无权限");
    }
    
    /**
     * 分页查询（与Admin页面保持一致的接口）
     */
    @GetMapping("/selectPage")
    public Result selectPage(
            Patient patient,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Account currentUser = TokenUtils.getCurrentUser();
        
        // 管理员可以查看所有患者
        if (currentUser != null && "admin".equals(currentUser.getRole())) {
            // 使用PageHelper手动创建PageInfo
            PageHelper.startPage(pageNum, pageSize);
            List<Patient> patients = patientService.selectAll(patient);
            PageInfo<Patient> pageInfo = new PageInfo<>(patients);
            return Result.success(pageInfo);
        }
        // 医生只能查看自己的患者
        else if (currentUser != null && "doctor".equals(currentUser.getRole())) {
            List<DoctorPatient> doctorPatients = doctorPatientService.selectByDoctorId(currentUser.getId(), patient.getName());
            
            if (!doctorPatients.isEmpty()) {
                // 提取患者信息
                List<Patient> patients = doctorPatients.stream()
                        .map(DoctorPatient::getPatient)
                        .filter(p -> p != null)
                        .collect(Collectors.toList());
                
                // 手动进行分页
                int total = patients.size();
                int fromIndex = (pageNum - 1) * pageSize;
                int toIndex = Math.min(fromIndex + pageSize, total);
                
                if (fromIndex >= total) {
                    patients = new ArrayList<>();
                } else {
                    patients = patients.subList(fromIndex, toIndex);
                }
                
                // 创建PageInfo对象
                PageInfo<Patient> pageInfo = new PageInfo<>();
                pageInfo.setList(patients);
                pageInfo.setTotal(total);
                pageInfo.setPageNum(pageNum);
                pageInfo.setPageSize(pageSize);
                pageInfo.setPages((total + pageSize - 1) / pageSize);
                
                return Result.success(pageInfo);
            } else {
                PageInfo<Patient> pageInfo = new PageInfo<>();
                pageInfo.setList(new ArrayList<>());
                pageInfo.setTotal(0);
                return Result.success(pageInfo);
            }
        }
        // 患者只能查看自己的信息
        else if (currentUser != null && "patient".equals(currentUser.getRole())) {
            Patient currentPatient = patientService.selectById(currentUser.getId());
            List<Patient> list = new ArrayList<>();
            if (currentPatient != null) {
                list.add(currentPatient);
            }
            
            // 创建PageInfo对象
            PageInfo<Patient> pageInfo = new PageInfo<>();
            pageInfo.setList(list);
            pageInfo.setTotal(list.size());
            pageInfo.setPageNum(1);
            pageInfo.setPageSize(pageSize);
            pageInfo.setPages(1);
            
            return Result.success(pageInfo);
        }
        
        return Result.error("401", "无权限");
    }

    /**
     * 更新患者个人资料
     */
    @PutMapping("/update")
    public Result updateProfile(@RequestBody Patient patient) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null || !"patient".equals(currentUser.getRole())) {
            return Result.error("401", "无权限");
        }
        
        // 确保只能更新自己的信息
        if (!currentUser.getId().equals(patient.getId())) {
            return Result.error("403", "只能更新自己的信息");
        }
        
        // 更新个人资料
        patientService.updateById(patient);
        
        return Result.success();
    }
} 