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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
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.hospital.domain.HospitalDepartment;
import com.ruoyi.info.hospital.domain.bo.HospitalDepartmentBo;
import com.ruoyi.info.hospital.domain.bo.HospitalDepartmentRackUpdateBo;
import com.ruoyi.info.hospital.domain.vo.HospitalDepartmentVo;
import com.ruoyi.info.hospital.exception.HospitalDepartmentExceptionEnum;
import com.ruoyi.info.hospital.exception.HospitalExceptionEnum;
import com.ruoyi.info.hospital.mapper.HospitalDepartmentMapper;
import com.ruoyi.info.hospital.service.IHospitalDepartmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 医院科室信息Service业务层处理
 *
 * @author baifc
 * @date 2025-09-20
 */
@RequiredArgsConstructor
@Service
public class HospitalDepartmentServiceImpl implements IHospitalDepartmentService {

    private final HospitalDepartmentMapper baseMapper;

    /**
     * 查询医院科室信息分页
     *
     * @param bo 医院科室信息
     * @return 医院科室信息
     */
    @Override
    public TableDataInfo<HospitalDepartmentVo> queryPageList(HospitalDepartmentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HospitalDepartment> lqw = buildQueryWrapper(bo);
        Page<HospitalDepartmentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询医院科室信息列表
     *
     * @param bo 医院科室信息
     * @return 医院科室信息
     */
    @Override
    public List<HospitalDepartmentVo> queryList(HospitalDepartmentBo bo) {
        LambdaQueryWrapper<HospitalDepartment> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HospitalDepartment> buildQueryWrapper(HospitalDepartmentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HospitalDepartment> lqw = Wrappers.lambdaQuery();
        lqw.eq(ObjectUtil.isNotNull(bo.getHospitalId()), HospitalDepartment::getHospitalId, bo.getHospitalId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), HospitalDepartment::getName, bo.getName());
        if(bo.getCreateTimeStart() != null) {
            lqw.ge(HospitalDepartment::getCreateTime, DateUtil.beginOfDay(bo.getCreateTimeStart()));
        }
        if(bo.getCreateTimeEnd() != null) {
            lqw.le(HospitalDepartment::getCreateTime, DateUtil.endOfDay(bo.getCreateTimeEnd()));
        }
        lqw.eq(StringUtils.isNotBlank(bo.getRackStatus()), HospitalDepartment::getRackStatus, bo.getRackStatus());
        lqw.orderByDesc(HospitalDepartment::getSortOrder).orderByDesc(HospitalDepartment::getId);
        return lqw;
    }

    /**
     * 查询医院科室信息
     *
     * @param id 医院科室信息主键
     * @return 医院科室信息
     */
    @Override
    public HospitalDepartmentVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 详情医院科室信息
     *
     * @param id 医院科室信息主键
     * @return 医院科室信息
     */
    @Override
    public HospitalDepartment loadById(Long id, Boolean tw){
        HospitalDepartment info = this.baseMapper.selectById(id);
        if(ObjectUtil.isEmpty(info) && tw){
            throw new ServiceException(HospitalDepartmentExceptionEnum.HOSPITAL_DEPARTMENT_IS_NOT_EXISTS);
        }
        return info;
    }

    /**
     * 新增医院科室信息
     *
     * @param bo 医院科室信息
     * @return 结果
     */
    @Override
    public Boolean insertByBo(HospitalDepartmentBo bo) {
        HospitalDepartment add = BeanUtil.toBean(bo, HospitalDepartment.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改医院科室信息
     *
     * @param bo 医院科室信息
     * @return 结果
     */
    @Override
    public Boolean updateByBo(HospitalDepartmentBo bo) {
        HospitalDepartment hospitalDepartment = baseMapper.selectById(bo.getId());
        //  医院id不可变更
        if (!ObjectUtil.equals(bo.getHospitalId(), hospitalDepartment.getHospitalId())) {
            throw new ServiceException(HospitalDepartmentExceptionEnum.HOSPITAL_ID_CANNOT_CHANGE);
        }
        HospitalDepartment update = BeanCopyUtils.copy(bo, hospitalDepartment);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(HospitalDepartment entity){
        // 医院名称不可重复
        LambdaQueryWrapper<HospitalDepartment> lqw = new LambdaQueryWrapper<HospitalDepartment>()
            .eq(HospitalDepartment::getName, entity.getName())
            .eq(HospitalDepartment::getHospitalId, entity.getHospitalId());

        List<HospitalDepartment> hospitalList = baseMapper.selectList(lqw);
        if (CollUtil.isNotEmpty(hospitalList)) {
            if (entity.getId() == null) {
                // 新增校验
                throw new ServiceException(HospitalDepartmentExceptionEnum.HOSPITAL_DEPARTMENT_NAME_ALREADY_EXISTS);
            } else {
                // 编辑校验
                if (hospitalList.stream().anyMatch(hospital -> !hospital.getId().equals(entity.getId()))) {
                    throw new ServiceException(HospitalDepartmentExceptionEnum.HOSPITAL_DEPARTMENT_NAME_ALREADY_EXISTS);
                }
            }

        }
    }

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

    /**
     * 修改科室上下架状态
     *
     * @param bo
     */
    @Override
    public void updateRackStatus(HospitalDepartmentRackUpdateBo bo) {
        HospitalDepartment hospitalDepartment = baseMapper.selectById(bo.getId());
        if (hospitalDepartment == null) {
            throw new ServiceException(HospitalExceptionEnum.HOSPITAL_IS_NOT_EXISTS);
        }

        if (hospitalDepartment.getRackStatus().equals(bo.getRackStatus())) {
            return;
        }
        hospitalDepartment.setRackStatus(bo.getRackStatus());
        baseMapper.updateById(hospitalDepartment);
    }

    /**
     * 根据医院id查询科室信息列表
     *
     * @param bo 医院科室信息
     * @return
     */
    @Override
    public List<HospitalDepartmentVo> queryByHospitalId(HospitalDepartmentBo bo) {
        // 医院名称不可重复
        LambdaQueryWrapper<HospitalDepartment> lqw = new LambdaQueryWrapper<HospitalDepartment>()
            .eq(HospitalDepartment::getHospitalId, bo.getHospitalId());
        lqw.eq(StringUtils.isNotBlank(bo.getRackStatus()), HospitalDepartment::getRackStatus, bo.getRackStatus());
        lqw.orderByDesc(HospitalDepartment::getSortOrder).orderByDesc(HospitalDepartment::getId);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public String queryNameById(Long id) {
        return baseMapper.queryNameById(id);
    }

}
