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.base.area.service.ISysCnAreaService;
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.Hospital;
import com.ruoyi.info.hospital.domain.bo.HospitalBo;
import com.ruoyi.info.hospital.domain.bo.HospitalRackUpdateBo;
import com.ruoyi.info.hospital.domain.vo.HospitalVo;
import com.ruoyi.info.hospital.exception.HospitalExceptionEnum;
import com.ruoyi.info.hospital.mapper.HospitalMapper;
import com.ruoyi.info.hospital.service.IHospitalService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

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

    private final HospitalMapper baseMapper;

    private final ISysCnAreaService sysCnAreaService;


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

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

    private LambdaQueryWrapper<Hospital> buildQueryWrapper(HospitalBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Hospital> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), Hospital::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getResponsiblePerson()), Hospital::getResponsiblePerson, bo.getResponsiblePerson());
        lqw.eq(StringUtils.isNotBlank(bo.getBusinessStatus()), Hospital::getBusinessStatus, bo.getBusinessStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getRackStatus()), Hospital::getRackStatus, bo.getRackStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getLevel()), Hospital::getLevel, bo.getLevel());
        lqw.eq(bo.getProvinceId() != null, Hospital::getProvinceId, bo.getProvinceId());
        lqw.eq(bo.getCityId() != null, Hospital::getCityId, bo.getCityId());
        lqw.eq(bo.getAreaId() != null, Hospital::getAreaId, bo.getAreaId());
        lqw.ge(ObjectUtil.isNotNull(bo.getCreateTimeStart()), Hospital::getCreateTime, bo.getCreateTimeStart());
        lqw.le(ObjectUtil.isNotNull(bo.getCreateTimeEnd()), Hospital::getCreateTime, bo.getCreateTimeEnd());
        if(bo.getStartTime() != null) {
            lqw.ge(Hospital::getCreateTime, DateUtil.beginOfDay(bo.getStartTime()));
        }
        if(bo.getEndTime() != null) {
            lqw.le(Hospital::getCreateTime, DateUtil.endOfDay(bo.getEndTime()));
        }
        lqw.orderByDesc(Hospital::getSortOrder).orderByDesc(Hospital::getId);
        return lqw;
    }

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

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

    /**
     * 新增医院信息
     *
     * @param bo 医院信息
     * @return 结果
     */
    @Override
    public Boolean insertByBo(HospitalBo bo) {
        Hospital add = BeanUtil.toBean(bo, Hospital.class);
        validEntityBeforeSave(add);
        //  生成省市区
        add.setProvinceName(sysCnAreaService.getByCode(bo.getProvinceId()).getLabel());
        add.setCityName(sysCnAreaService.getByCode(bo.getCityId()).getLabel());
        add.setAreaName(sysCnAreaService.getByCode(bo.getAreaId()).getLabel());

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());

            // TODO 生成小程序二维码
        }
        return flag;
    }

    /**
     * 修改医院信息
     *
     * @param bo 医院信息
     * @return 结果
     */
    @Override
    public Boolean updateByBo(HospitalBo bo) {
        Hospital hospital = baseMapper.selectById(bo.getId());
        if (ObjectUtil.isNull(hospital)) {
            throw new ServiceException(HospitalExceptionEnum.HOSPITAL_IS_NOT_EXISTS);
        }
        Hospital update = BeanCopyUtils.copy(bo, hospital);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Hospital entity){
        // 医院名称不可重复
        LambdaQueryWrapper<Hospital> lqw = new LambdaQueryWrapper<Hospital>()
            .eq(Hospital::getName, entity.getName());
        List<Hospital> hospitalList = baseMapper.selectList(lqw);
        if (CollUtil.isNotEmpty(hospitalList)) {
            if (entity.getId() == null) {
                // 新增校验
                throw new ServiceException(HospitalExceptionEnum.HOSPITAL_NAME_ALREADY_EXISTS);
            } else {
                // 编辑校验
                if (hospitalList.stream().anyMatch(hospital -> !hospital.getId().equals(entity.getId()))) {
                    throw new ServiceException(HospitalExceptionEnum.HOSPITAL_NAME_ALREADY_EXISTS);
                }
            }

        }


    }

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

    @Override
    public void updateRackStatus(HospitalRackUpdateBo bo) {
        Hospital hospital = baseMapper.selectById(bo.getId());
        if (hospital == null) {
            throw new ServiceException(HospitalExceptionEnum.HOSPITAL_IS_NOT_EXISTS);
        }

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

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

    @Override
    public void updateQrCodeUrl(Long hospitalId, String qrCodeUrl) {
        Hospital hospital = baseMapper.selectById(hospitalId);
        hospital.setQrCodeUrl(qrCodeUrl);
        baseMapper.updateById(hospital);
    }

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

    @Override
    public Integer querySumForHome() {
        Long count = baseMapper.selectCount(new LambdaQueryWrapper<Hospital>());
        return count.intValue();
    }

    @Override
    public List<HospitalVo> queryListByIds(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return baseMapper.selectVoBatchIds(ids, HospitalVo.class);
    }

}
