package cn.iocoder.yudao.module.system.service.elderly;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.system.controller.admin.elderly.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlyInfoDO;
import cn.iocoder.yudao.module.system.dal.dataobject.elderly.ElderlyNursingLogDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.elderly.ElderlyNursingLogMapper;
import cn.iocoder.yudao.module.system.service.biz.BuildService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Validated
public class ElderlyNursingLogServiceImpl implements ElderlyNursingLogService {

    @Resource
    private ElderlyNursingLogMapper nursingLogMapper;
    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;
    @Resource
    private BuildService buildService;

    @Override
    public Long create(ElderlyNursingLogSaveReqVO createReqVO) {
        ElderlyNursingLogDO nursingLog = BeanUtils.toBean(createReqVO, ElderlyNursingLogDO.class);
        if (nursingLog.getTenantId() == null) {
            nursingLog.setTenantId(TenantContextHolder.getTenantId());
        }
        nursingLogMapper.insert(nursingLog);
        return nursingLog.getId();
    }

    @Override
    public void update(ElderlyNursingLogSaveReqVO updateReqVO) {
        ElderlyNursingLogDO nursingLog = BeanUtils.toBean(updateReqVO, ElderlyNursingLogDO.class);
        if (nursingLog.getTenantId() == null) {
            nursingLog.setTenantId(TenantContextHolder.getTenantId());
        }
        nursingLogMapper.updateById(nursingLog);
    }

    @Override
    public void delete(Long id) {
        nursingLogMapper.deleteById(id);
    }

    @Override
    public ElderlyNursingLogRespVO get(Long id) {
        ElderlyNursingLogDO nursingLog = nursingLogMapper.selectById(id);
        if (nursingLog == null) {
            return null;
        }
        ElderlyNursingLogRespVO respVO = BeanUtils.toBean(nursingLog, ElderlyNursingLogRespVO.class);
        fillElderInfo(Collections.singletonList(respVO));
        return respVO;
    }

    @Override
    public PageResult<ElderlyNursingLogRespVO> getPage(ElderlyNursingLogPageReqVO pageReqVO) {
        if (pageReqVO.getTenantIds() == null || pageReqVO.getTenantIds().length == 0) {
            pageReqVO.setTenantIds(new Long[]{TenantContextHolder.getTenantId()});
        }

        List<Long> elderIds;
        if (pageReqVO.getElderName() != null && !pageReqVO.getElderName().trim().isEmpty()) {
            List<ElderlyInfoDO> elders = elderlyInfoMapper.selectList(new LambdaQueryWrapperX<ElderlyInfoDO>()
                    .inIfPresent(ElderlyInfoDO::getTenantId, pageReqVO.getTenantIds())
                    .like(ElderlyInfoDO::getElderName, pageReqVO.getElderName()));
            elderIds = elders.stream().map(ElderlyInfoDO::getId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            if (elderIds.isEmpty()) {
                return PageResult.empty();
            }
        } else {
            elderIds = null;
        }

        PageResult<ElderlyNursingLogDO> pageResult = nursingLogMapper.selectPage(pageReqVO);
        List<ElderlyNursingLogDO> list = pageResult.getList();

        if (elderIds != null) {
            list = list.stream().filter(r -> elderIds.contains(r.getElderId())).collect(Collectors.toList());
            pageResult.setList(list);
            pageResult.setTotal((long) list.size());
        }

        List<ElderlyNursingLogRespVO> voList = BeanUtils.toBean(list, ElderlyNursingLogRespVO.class);
        fillElderInfo(voList);
        return new PageResult<>(voList, pageResult.getTotal());
    }

    @Override
    public ElderlyNursingLogDetailRespVO getDetailByElderId(Long elderId) {
        if (elderId == null) {
            return null;
        }
        ElderlyInfoDO elder = elderlyInfoMapper.selectById(elderId);
        if (elder == null) {
            return null;
        }
        List<ElderlyNursingLogDO> logs = nursingLogMapper.selectByElderId(elderId);
        List<ElderlyNursingLogRespVO> records = BeanUtils.toBean(logs, ElderlyNursingLogRespVO.class);

        ElderlyNursingLogDetailRespVO detailRespVO = new ElderlyNursingLogDetailRespVO();
        ElderlyNursingLogDetailRespVO.Header header = new ElderlyNursingLogDetailRespVO.Header();
        header.setElderName(elder.getElderName());
        header.setBedName(buildService.getFullBedName(elderId));
        header.setNurseLevelName(elder.getNurseLevelName());
        detailRespVO.setHeader(header);

        for (ElderlyNursingLogRespVO record : records) {
            record.setElderName(elder.getElderName());
            record.setBedName(header.getBedName());
            record.setNurseLevelName(elder.getNurseLevelName());
        }
        detailRespVO.setRecords(records);
        return detailRespVO;
    }

    private void fillElderInfo(List<ElderlyNursingLogRespVO> list) {
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        Set<Long> elderIds = list.stream().map(ElderlyNursingLogRespVO::getElderId)
                .filter(Objects::nonNull).collect(Collectors.toSet());
        if (CollectionUtil.isEmpty(elderIds)) {
            return;
        }
        List<ElderlyInfoDO> elders = elderlyInfoMapper.selectBatchIds(elderIds);
        Map<Long, ElderlyInfoDO> elderMap = elders.stream().filter(e -> e.getId() != null)
                .collect(Collectors.toMap(ElderlyInfoDO::getId, Function.identity(), (a, b) -> a));

        for (ElderlyNursingLogRespVO vo : list) {
            ElderlyInfoDO elder = elderMap.get(vo.getElderId());
            if (elder != null) {
                vo.setElderName(elder.getElderName());
                vo.setNurseLevelName(elder.getNurseLevelName());
            }
            vo.setBedName(buildService.getFullBedName(vo.getElderId()));
        }
    }
}
