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.ElderlyTurnOverDO;
import cn.iocoder.yudao.module.system.dal.dataobject.elderly.ElderlyTurnOverItemDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.elderly.ElderlyTurnOverItemMapper;
import cn.iocoder.yudao.module.system.dal.mysql.elderly.ElderlyTurnOverMapper;
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 ElderlyTurnOverServiceImpl implements ElderlyTurnOverService {

    @Resource
    private ElderlyTurnOverMapper turnOverMapper;
    @Resource
    private ElderlyTurnOverItemMapper turnOverItemMapper;
    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;
    @Resource
    private BuildService buildService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(ElderlyTurnOverSaveReqVO createReqVO) {
        ElderlyTurnOverDO turnOver = BeanUtils.toBean(createReqVO, ElderlyTurnOverDO.class);
        if (turnOver.getTenantId() == null) {
            turnOver.setTenantId(TenantContextHolder.getTenantId());
        }
        turnOverMapper.insert(turnOver);
        saveItems(turnOver.getId(), turnOver.getTenantId(), createReqVO.getItems());
        return turnOver.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ElderlyTurnOverSaveReqVO updateReqVO) {
        ElderlyTurnOverDO turnOver = BeanUtils.toBean(updateReqVO, ElderlyTurnOverDO.class);
        if (turnOver.getTenantId() == null) {
            turnOver.setTenantId(TenantContextHolder.getTenantId());
        }
        turnOverMapper.updateById(turnOver);

        turnOverItemMapper.deleteByTurnOverId(turnOver.getId());
        saveItems(turnOver.getId(), turnOver.getTenantId(), updateReqVO.getItems());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        turnOverItemMapper.deleteByTurnOverId(id);
        turnOverMapper.deleteById(id);
    }

    @Override
    public ElderlyTurnOverRespVO get(Long id) {
        ElderlyTurnOverDO turnOver = turnOverMapper.selectById(id);
        if (turnOver == null) {
            return null;
        }

        ElderlyTurnOverRespVO respVO = BeanUtils.toBean(turnOver, ElderlyTurnOverRespVO.class);

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

        List<ElderlyTurnOverItemDO> items = turnOverItemMapper.selectListByTurnOverId(id);
        respVO.setItems(BeanUtils.toBean(items, ElderlyTurnOverItemRespVO.class));
        return respVO;
    }

    @Override
    public PageResult<ElderlyTurnOverRespVO> getPage(ElderlyTurnOverPageReqVO pageReqVO) {
        Long[] tenantIds = pageReqVO.getTenantIds();
        if (tenantIds == null || tenantIds.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<ElderlyTurnOverDO> pageResult = turnOverMapper.selectPage(pageReqVO);
        List<ElderlyTurnOverDO> 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(ElderlyTurnOverDO::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<ElderlyTurnOverRespVO> voList = BeanUtils.toBean(list, ElderlyTurnOverRespVO.class);
        for (ElderlyTurnOverRespVO 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 turnOverId, Long tenantId, List<ElderlyTurnOverItemSaveReqVO> itemReqList) {
        if (CollectionUtil.isEmpty(itemReqList)) {
            return;
        }
        for (ElderlyTurnOverItemSaveReqVO itemReq : itemReqList) {
            ElderlyTurnOverItemDO item = BeanUtils.toBean(itemReq, ElderlyTurnOverItemDO.class);
            item.setTurnOverId(turnOverId);
            item.setTenantId(tenantId);
            turnOverItemMapper.insert(item);
        }
    }
}

