package com.ruoyi.info.patient.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.info.patient.domain.Patient;
import com.ruoyi.info.patient.domain.bo.PatientBo;
import com.ruoyi.info.patient.domain.vo.PatientVo;
import com.ruoyi.info.patient.exception.PatientExceptionEnum;
import com.ruoyi.info.patient.mapper.PatientMapper;
import com.ruoyi.info.patient.service.IPatientService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 就诊人Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-20
 */
@RequiredArgsConstructor
@Service
public class PatientServiceImpl implements IPatientService {

    private final PatientMapper baseMapper;

    /**
     * 查询就诊人分页
     *
     * @param bo 就诊人
     * @return 就诊人
     */
    @Override
    public TableDataInfo<PatientVo> queryPageList(PatientBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Patient> lqw = buildQueryWrapper(bo);
        Page<PatientVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询就诊人列表
     *
     * @param bo 就诊人
     * @return 就诊人
     */
    @Override
    public List<PatientVo> queryList(PatientBo bo) {
        LambdaQueryWrapper<Patient> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Patient> buildQueryWrapper(PatientBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Patient> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, Patient::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), Patient::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getMobile()), Patient::getMobile, bo.getMobile());
        lqw.eq(bo.getGender() != null, Patient::getGender, bo.getGender());
        lqw.eq(bo.getAge() != null, Patient::getAge, bo.getAge());
        lqw.eq(StringUtils.isNotBlank(bo.getRelationship()), Patient::getRelationship, bo.getRelationship());
        lqw.eq(bo.getDefaulted() != null, Patient::getDefaulted, bo.getDefaulted());
        lqw.orderByDesc(Patient::getDefaulted).orderByDesc(Patient::getCreateTime);
        return lqw;
    }

    /**
     * 查询就诊人
     *
     * @param id 就诊人主键
     * @return 就诊人
     */
    @Override
    public PatientVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 详情就诊人
     *
     * @param id 就诊人主键
     * @return 就诊人
     */
    @Override
    public Patient loadById(Long id, Boolean tw){
        Patient info = this.baseMapper.selectById(id);
        if(ObjectUtil.isEmpty(info) && tw){
            throw new ServiceException(PatientExceptionEnum.Patient_IS_NOT_EXISTS);
        }
        return info;
    }

    /**
     * 新增就诊人
     *
     * @param bo 就诊人
     * @return 结果
     */
    @Override
    public Boolean insertByBo(PatientBo bo) {
        Patient add = BeanUtil.toBean(bo, Patient.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改就诊人
     *
     * @param bo 就诊人
     * @return 结果
     */
    @Override
    public Boolean updateByBo(PatientBo bo) {
        Patient patient = baseMapper.selectById(bo.getId());
        Patient update = BeanCopyUtils.copy(bo, patient);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Patient entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除就诊人
     *
     * @param ids 需要删除的就诊人主键
     * @return 结果
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void setDefaulted(Long userId, Long patientId) {
        Patient patient = loadById(patientId, true);
        if (!patient.getUserId().equals(userId)) {
            throw new ServiceException(PatientExceptionEnum.OPTION_USER_PATIENT_IS_EXISTS);
        }
        // 如果当前患者已经是默认患者，直接返回
        if (patient.getDefaulted() != null && patient.getDefaulted()) {
            return;
        }
        // 取消原有默认患者的默认状态
        Patient defaultObj = this.loadDefaulted(userId);
        if (ObjectUtil.isNotNull(defaultObj) && !patient.getId().equals(defaultObj.getId())) {
            defaultObj.setDefaulted(false);
            this.baseMapper.updateById(defaultObj);
        }
        // 设置当前患者为默认患者
        patient.setDefaulted(true);
        this.baseMapper.updateById(patient);
    }

    @Override
    public PatientVo getDefaulted(Long userId) {
        return this.baseMapper.selectVoOne(new LambdaQueryWrapper<Patient>().eq(Patient::getUserId, userId).eq(Patient::getDefaulted, true).last("limit 1"));
    }

    @Override
    public PatientVo queryDelById(Long id) {
        return this.baseMapper.queryDelById(id);
    }

    public Patient loadDefaulted(Long userId) {
        return this.baseMapper.selectOne(new LambdaQueryWrapper<Patient>().eq(Patient::getUserId, userId).eq(Patient::getDefaulted, true).last("limit 1"));
    }
}
