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.ElderlySpecialServiceDO;
import cn.iocoder.yudao.module.system.dal.dataobject.elderly.ElderlySpecialServiceItemDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.elderly.ElderlySpecialServiceItemMapper;
import cn.iocoder.yudao.module.system.dal.mysql.elderly.ElderlySpecialServiceMapper;
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 ElderlySpecialServiceServiceImpl implements ElderlySpecialServiceService {

    @Resource
    private ElderlySpecialServiceMapper specialServiceMapper;
    @Resource
    private ElderlySpecialServiceItemMapper specialServiceItemMapper;
    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;
    @Resource
    private BuildService buildService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(ElderlySpecialServiceSaveReqVO createReqVO) {
        ElderlySpecialServiceDO service = BeanUtils.toBean(createReqVO, ElderlySpecialServiceDO.class);
        if (service.getTenantId() == null) {
            service.setTenantId(TenantContextHolder.getTenantId());
        }
        specialServiceMapper.insert(service);
        saveItems(service.getId(), service.getTenantId(), createReqVO.getItems());
        return service.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ElderlySpecialServiceSaveReqVO updateReqVO) {
        ElderlySpecialServiceDO service = BeanUtils.toBean(updateReqVO, ElderlySpecialServiceDO.class);
        if (service.getTenantId() == null) {
            service.setTenantId(TenantContextHolder.getTenantId());
        }
        specialServiceMapper.updateById(service);

        specialServiceItemMapper.deleteBySpecialServiceId(service.getId());
        saveItems(service.getId(), service.getTenantId(), updateReqVO.getItems());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        specialServiceItemMapper.deleteBySpecialServiceId(id);
        specialServiceMapper.deleteById(id);
    }

    @Override
    public ElderlySpecialServiceRespVO get(Long id) {
        ElderlySpecialServiceDO service = specialServiceMapper.selectById(id);
        if (service == null) {
            return null;
        }

        ElderlySpecialServiceRespVO respVO = BeanUtils.toBean(service, ElderlySpecialServiceRespVO.class);

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

        List<ElderlySpecialServiceItemDO> items = specialServiceItemMapper.selectListBySpecialServiceId(id);
        respVO.setItems(BeanUtils.toBean(items, ElderlySpecialServiceItemRespVO.class));
        return respVO;
    }

    @Override
    public PageResult<ElderlySpecialServiceRespVO> getPage(ElderlySpecialServicePageReqVO 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<ElderlySpecialServiceDO> pageResult = specialServiceMapper.selectPage(pageReqVO);
        List<ElderlySpecialServiceDO> 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(ElderlySpecialServiceDO::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<ElderlySpecialServiceRespVO> voList = BeanUtils.toBean(list, ElderlySpecialServiceRespVO.class);
        for (ElderlySpecialServiceRespVO 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 specialServiceId, Long tenantId, List<ElderlySpecialServiceItemSaveReqVO> itemReqList) {
        if (CollectionUtil.isEmpty(itemReqList)) {
            return;
        }
        for (ElderlySpecialServiceItemSaveReqVO itemReq : itemReqList) {
            ElderlySpecialServiceItemDO item = BeanUtils.toBean(itemReq, ElderlySpecialServiceItemDO.class);
            item.setSpecialServiceId(specialServiceId);
            item.setTenantId(tenantId);
            specialServiceItemMapper.insert(item);
        }
    }
}

