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.ElderlyNasalFeedingDO;
import cn.iocoder.yudao.module.system.dal.dataobject.elderly.ElderlyNasalFeedingItemDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.elderly.ElderlyNasalFeedingItemMapper;
import cn.iocoder.yudao.module.system.dal.mysql.elderly.ElderlyNasalFeedingMapper;
import cn.iocoder.yudao.module.system.service.biz.BuildService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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 ElderlyNasalFeedingServiceImpl implements ElderlyNasalFeedingService {

    @Resource
    private ElderlyNasalFeedingMapper nasalFeedingMapper;
    @Resource
    private ElderlyNasalFeedingItemMapper nasalFeedingItemMapper;
    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;
    @Resource
    private BuildService buildService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(ElderlyNasalFeedingSaveReqVO createReqVO) {
        ElderlyNasalFeedingDO nasal = BeanUtils.toBean(createReqVO, ElderlyNasalFeedingDO.class);
        if (nasal.getTenantId() == null) {
            nasal.setTenantId(TenantContextHolder.getTenantId());
        }
        nasalFeedingMapper.insert(nasal);
        saveItems(nasal.getId(), nasal.getTenantId(), createReqVO.getItems());
        return nasal.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ElderlyNasalFeedingSaveReqVO updateReqVO) {
        ElderlyNasalFeedingDO nasal = BeanUtils.toBean(updateReqVO, ElderlyNasalFeedingDO.class);
        if (nasal.getTenantId() == null) {
            nasal.setTenantId(TenantContextHolder.getTenantId());
        }
        nasalFeedingMapper.updateById(nasal);

        nasalFeedingItemMapper.deleteByNasalId(nasal.getId());
        saveItems(nasal.getId(), nasal.getTenantId(), updateReqVO.getItems());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        nasalFeedingItemMapper.deleteByNasalId(id);
        nasalFeedingMapper.deleteById(id);
    }

    @Override
    public ElderlyNasalFeedingRespVO get(Long id) {
        ElderlyNasalFeedingDO nasal = nasalFeedingMapper.selectById(id);
        if (nasal == null) {
            return null;
        }

        ElderlyNasalFeedingRespVO respVO = BeanUtils.toBean(nasal, ElderlyNasalFeedingRespVO.class);

        ElderlyInfoDO elderly = elderlyInfoMapper.selectById(nasal.getElderId());
        if (elderly != null) {
            respVO.setElderName(elderly.getElderName());
        }
        respVO.setBedName(buildService.getFullBedName(nasal.getElderId()));

        List<ElderlyNasalFeedingItemDO> items = nasalFeedingItemMapper.selectListByNasalId(id);
        respVO.setItems(BeanUtils.toBean(items, ElderlyNasalFeedingItemRespVO.class));
        return respVO;
    }

    @Override
    public PageResult<ElderlyNasalFeedingRespVO> getPage(ElderlyNasalFeedingPageReqVO 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<ElderlyNasalFeedingDO> pageResult = nasalFeedingMapper.selectPage(pageReqVO);
        List<ElderlyNasalFeedingDO> 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());
        }

        Map<Long, ElderlyInfoDO> elderMap = new HashMap<>();
        Set<Long> pageElderIds = list.stream().map(ElderlyNasalFeedingDO::getElderId)
                .filter(Objects::nonNull).collect(Collectors.toSet());
        if (CollectionUtil.isNotEmpty(pageElderIds)) {
            List<ElderlyInfoDO> elders = elderlyInfoMapper.selectBatchIds(pageElderIds);
            elderMap = elders.stream().filter(e -> e.getId() != null)
                    .collect(Collectors.toMap(ElderlyInfoDO::getId, Function.identity(), (a, b) -> a));
        }

        List<ElderlyNasalFeedingRespVO> voList = BeanUtils.toBean(list, ElderlyNasalFeedingRespVO.class);
        for (ElderlyNasalFeedingRespVO vo : voList) {
            ElderlyInfoDO elder = elderMap.get(vo.getElderId());
            if (elder != null) {
                vo.setElderName(elder.getElderName());
            }
            vo.setBedName(buildService.getFullBedName(vo.getElderId()));
        }

        return new PageResult<>(voList, pageResult.getTotal());
    }

    private void saveItems(Long nasalId, Long tenantId, List<ElderlyNasalFeedingItemSaveReqVO> itemReqList) {
        if (CollectionUtil.isEmpty(itemReqList)) {
            return;
        }
        for (ElderlyNasalFeedingItemSaveReqVO itemReq : itemReqList) {
            ElderlyNasalFeedingItemDO item = BeanUtils.toBean(itemReq, ElderlyNasalFeedingItemDO.class);
            item.setNasalId(nasalId);
            item.setTenantId(tenantId);
            nasalFeedingItemMapper.insert(item);
        }
    }
}

