package org.dromara.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.web.domain.bo.ConsultPatientEditBo;
import org.dromara.web.domain.bo.ConsultPatientInitiateBo;
import org.dromara.web.domain.vo.TreatmentUserVo;
import org.dromara.web.mapper.TreatmentUserMapper;
import org.springframework.stereotype.Service;
import org.dromara.web.domain.bo.ConsultPatientBo;
import org.dromara.web.domain.vo.ConsultPatientVo;
import org.dromara.web.domain.ConsultPatient;
import org.dromara.web.mapper.ConsultPatientMapper;
import org.dromara.web.service.IConsultPatientService;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 会诊患者Service业务层处理
 *
 * @author Huanyi
 * @date 2025-08-12
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ConsultPatientServiceImpl implements IConsultPatientService {

    private final ConsultPatientMapper baseMapper;
    private final TreatmentUserMapper treatmentUserMapper;

    /**
     * 查询会诊患者
     *
     * @param id 主键
     * @return 会诊患者
     */
    @Override
    public ConsultPatientVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询会诊患者列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 会诊患者分页列表
     */
    @Override
    public TableDataInfo<ConsultPatientVo> queryPageList(ConsultPatientBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ConsultPatient> lqw = buildQueryWrapper(bo);
        Page<ConsultPatientVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的会诊患者列表
     *
     * @param bo 查询条件
     * @return 会诊患者列表
     */
    @Override
    public List<ConsultPatientVo> queryList(ConsultPatientBo bo) {
        LambdaQueryWrapper<ConsultPatient> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ConsultPatient> buildQueryWrapper(ConsultPatientBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ConsultPatient> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(ConsultPatient::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getVisitType()), ConsultPatient::getVisitType, bo.getVisitType());
        lqw.eq(StringUtils.isNotBlank(bo.getConsultNum()), ConsultPatient::getConsultNum, bo.getConsultNum());
        lqw.eq(StringUtils.isNotBlank(bo.getOutpatientNo()), ConsultPatient::getOutpatientNo, bo.getOutpatientNo());
        lqw.eq(bo.getDoorId() != null, ConsultPatient::getDoorId, bo.getDoorId());
        lqw.like(StringUtils.isNotBlank(bo.getConsultName()), ConsultPatient::getConsultName, bo.getConsultName());
        lqw.eq(StringUtils.isNotBlank(bo.getBirthday()), ConsultPatient::getBirthday, bo.getBirthday());
        lqw.eq(StringUtils.isNotBlank(bo.getPhoneNum()), ConsultPatient::getPhoneNum, bo.getPhoneNum());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), ConsultPatient::getSex, bo.getSex());
        lqw.eq(StringUtils.isNotBlank(bo.getIdCard()), ConsultPatient::getIdCard, bo.getIdCard());
        lqw.eq(StringUtils.isNotBlank(bo.getAge()), ConsultPatient::getAge, bo.getAge());
        lqw.eq(StringUtils.isNotBlank(bo.getHeight()), ConsultPatient::getHeight, bo.getHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getAllergyFood()), ConsultPatient::getAllergyFood, bo.getAllergyFood());
        lqw.eq(StringUtils.isNotBlank(bo.getAllergyDrug()), ConsultPatient::getAllergyDrug, bo.getAllergyDrug());
        lqw.eq(StringUtils.isNotBlank(bo.getActivity()), ConsultPatient::getActivity, bo.getActivity());
        lqw.eq(StringUtils.isNotBlank(bo.getBedNo()), ConsultPatient::getBedNo, bo.getBedNo());
        lqw.eq(bo.getWardId() != null, ConsultPatient::getWardId, bo.getWardId());
        lqw.eq(bo.getAdmissionDate() != null, ConsultPatient::getAdmissionDate, bo.getAdmissionDate());
        lqw.eq(StringUtils.isNotBlank(bo.getMedicalType()), ConsultPatient::getMedicalType, bo.getMedicalType());
        lqw.eq(StringUtils.isNotBlank(bo.getConsultPatientStatus()), ConsultPatient::getConsultPatientStatus, bo.getConsultPatientStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getEvaluationStatus()), ConsultPatient::getEvaluationStatus, bo.getEvaluationStatus());
        lqw.like(StringUtils.isNotBlank(bo.getWardName()), ConsultPatient::getWardName, bo.getWardName());
        lqw.eq(bo.getBmi() != null, ConsultPatient::getBmi, bo.getBmi());
//        lqw.ne(ConsultPatient::getStatus, 2);
        return lqw;
    }

    /**
     * 新增会诊患者
     *
     * @param bo 会诊患者
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ConsultPatientBo bo) {
        ConsultPatient add = MapstructUtils.convert(bo, ConsultPatient.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改会诊患者
     *
     * @param bo 会诊患者
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ConsultPatientBo bo) {
        ConsultPatient update = MapstructUtils.convert(bo, ConsultPatient.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ConsultPatient entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除会诊患者信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R initiateConsultation(ConsultPatientInitiateBo bo) {

        TreatmentUserVo vo = treatmentUserMapper.selectVoById(bo.getId());
        ConsultPatient patient = new ConsultPatient();
        patient.setVisitType(vo.getType());
        patient.setConsultNum(vo.getTreatNum());
        patient.setOutpatientNo(vo.getOutpatientNo());
        patient.setDoorId(vo.getDoorId());
        patient.setConsultName(vo.getTreatName());
        patient.setBirthday(vo.getBirthday());
        patient.setPhoneNum(vo.getPhoneNum());
        patient.setSex(vo.getSex());
        patient.setIdCard(vo.getIdCard());
        patient.setAge(vo.getAge());
        patient.setHeight(vo.getHeight());
        patient.setAllergyFood(vo.getAllergyFoot());
        patient.setAllergyDrug(vo.getAllergyDrug());
        patient.setActivity(vo.getActivity());
        patient.setBedNo(vo.getBedNo());
        patient.setWardId(vo.getWardId());
        patient.setAdmissionDate(vo.getAdmissionDate());
        patient.setMedicalType(vo.getMedicalType());
        patient.setConsultPatientStatus(vo.getTreatmentUserStatus());
        patient.setEvaluationStatus(vo.getEvaluationStatus());
        patient.setWardName(vo.getWardName());
        patient.setRequirements(bo.getRequirements());
        patient.setPurpose(bo.getPurpose());

        int flag = baseMapper.insert(patient);
        if (flag <= 0) {
            throw new RuntimeException("申请会诊失败!");
        }

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R edit(ConsultPatientEditBo bo) {

        LambdaQueryWrapper<ConsultPatient> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ConsultPatient::getId, bo.getId());
        ConsultPatient patient = baseMapper.selectOne(queryWrapper);
        LambdaUpdateWrapper<ConsultPatient> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ConsultPatient::getId, bo.getId())
            .set(ConsultPatient::getStatus, patient.getStatus() == 0 ? 1 : 2)
            .set(ConsultPatient::getScore, bo.getScore())
            .set(ConsultPatient::getResult, bo.getResult());
        int flag = baseMapper.update(wrapper);
        if (flag <= 0) {
            throw new RuntimeException("结束会诊失败");
        }

        return R.ok();
    }
}
