package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.*;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.common.config.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class PatientService {

    @Resource
    private PatientMapper patientMapper;

    @Resource
    private DoctorPatientMapper doctorPatientMapper;

    /**
     * 新增
     */
    public void add(Patient patient) {
        // 校验数据
        if (ObjectUtil.isEmpty(patient.getUsername()) || ObjectUtil.isEmpty(patient.getPassword())) {
            throw new CustomException(ResultCodeEnum.PARAM_LOST_ERROR);
        }
        
        // 检查用户名是否存在
        Patient dbPatient = selectByUsername(patient.getUsername());
        if (dbPatient != null) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        
        // 设置默认值
        if (ObjectUtil.isEmpty(patient.getName())) {
            patient.setName(patient.getUsername());
        }
        patient.setRole("patient");
        
        patientMapper.insert(patient);
    }

    /**
     * 通过ID删除
     */
    public void deleteById(Integer id) {
        patientMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            patientMapper.deleteById(id);
        }
    }

    /**
     * 更新
     */
    public void updateById(Patient patient) {
        patientMapper.updateById(patient);
    }

    /**
     * 通过ID查询
     */
    public Patient selectById(Integer id) {
        return patientMapper.selectById(id);
    }

    /**
     * 通过用户名查询
     */
    public Patient selectByUsername(String username) {
        LambdaQueryWrapper<Patient> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Patient::getUsername, username);
        return patientMapper.selectOne(queryWrapper);
    }

    /**
     * 查询所有
     */
    public List<Patient> selectAll(Patient patient) {
        LambdaQueryWrapper<Patient> queryWrapper = new LambdaQueryWrapper<>();
        return patientMapper.selectList(queryWrapper);
    }

    /**
     * 分页查询 - 按患者信息查询
     */
    public Page<Patient> selectPage(Patient patient, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Patient> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(patient.getName())) {
            queryWrapper.like(Patient::getName, patient.getName());
        }
        
        return patientMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
    }
    
    /**
     * 分页查询 - 按患者姓名查询
     */
    public Page<Patient> selectPage(Integer pageNum, Integer pageSize, String name) {
        LambdaQueryWrapper<Patient> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(name)) {
            queryWrapper.like(Patient::getName, name);
        }
        
        return patientMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
    }

    /**
     * 用户登录
     */
    public Account login(Account account) {
        LambdaQueryWrapper<Patient> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Patient::getUsername, account.getUsername());
        queryWrapper.eq(Patient::getPassword, account.getPassword());
        Patient patient = patientMapper.selectOne(queryWrapper);
        
        if (ObjectUtil.isEmpty(patient)) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        
        // 生成token
        String tokenData = patient.getId() + "-" + patient.getRole();
        String token = TokenUtils.genToken(tokenData, patient.getPassword());
        patient.setToken(token);
        
        return patient;
    }

    /**
     * 用户注册
     */
    public void register(Account account) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<Patient> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Patient::getUsername, account.getUsername());
        if (patientMapper.selectCount(queryWrapper) > 0) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        
        Patient patient = new Patient();
        patient.setUsername(account.getUsername());
        patient.setPassword(account.getPassword());
        patient.setName(account.getName());
        patient.setSex(account.getSex());
        patient.setPhone(account.getPhone());
        patient.setEmail(account.getEmail());
        patient.setRole("patient");
        add(patient);
        
        // 如果选择了医生，则建立医患关系
        if (account.getDoctorId() != null) {
            DoctorPatient doctorPatient = new DoctorPatient();
            doctorPatient.setDoctorId(account.getDoctorId());
            doctorPatient.setPatientId(patient.getId());
            doctorPatient.setRelationshipStart(new Date());
            doctorPatient.setStatus("正常");
            doctorPatient.setCreateTime(new Date());
            
            doctorPatientMapper.insert(doctorPatient);
        }
    }

    /**
     * 修改密码
     */
    public void updatePassword(Account account) {
        Patient dbPatient = selectById(account.getId());
        if (ObjectUtil.isEmpty(dbPatient)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        
        if (!account.getPassword().equals(dbPatient.getPassword())) {
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        
        Patient patient = new Patient();
        patient.setId(account.getId());
        patient.setPassword(account.getNewPassword());
        
        updateById(patient);
    }
}