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.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.ElderlyRestraintDO;
import cn.iocoder.yudao.module.system.dal.dataobject.elderly.ElderlyRestraintItemDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.elderly.ElderlyRestraintItemMapper;
import cn.iocoder.yudao.module.system.dal.mysql.elderly.ElderlyRestraintMapper;
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 ElderlyRestraintServiceImpl implements ElderlyRestraintService {

    @Resource
    private ElderlyRestraintMapper restraintMapper;
    @Resource
    private ElderlyRestraintItemMapper restraintItemMapper;
    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;
    @Resource
    private BuildService buildService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(ElderlyRestraintSaveReqVO createReqVO) {
        ElderlyRestraintDO restraint = BeanUtils.toBean(createReqVO, ElderlyRestraintDO.class);
        if (restraint.getTenantId() == null) {
            restraint.setTenantId(TenantContextHolder.getTenantId());
        }
        restraintMapper.insert(restraint);

        saveItems(restraint.getId(), restraint.getTenantId(), createReqVO.getItems());
        return restraint.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ElderlyRestraintSaveReqVO updateReqVO) {
        ElderlyRestraintDO restraint = BeanUtils.toBean(updateReqVO, ElderlyRestraintDO.class);
        if (restraint.getTenantId() == null) {
            restraint.setTenantId(TenantContextHolder.getTenantId());
        }
        restraintMapper.updateById(restraint);

        restraintItemMapper.deleteByRestraintId(restraint.getId());
        saveItems(restraint.getId(), restraint.getTenantId(), updateReqVO.getItems());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        restraintItemMapper.deleteByRestraintId(id);
        restraintMapper.deleteById(id);
    }

    @Override
    public ElderlyRestraintRespVO get(Long id) {
        ElderlyRestraintDO restraint = restraintMapper.selectById(id);
        if (restraint == null) {
            return null;
        }

        ElderlyRestraintRespVO respVO = BeanUtils.toBean(restraint, ElderlyRestraintRespVO.class);

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

        List<ElderlyRestraintItemDO> items = restraintItemMapper.selectListByRestraintId(id);
        respVO.setItems(BeanUtils.toBean(items, ElderlyRestraintItemRespVO.class));
        return respVO;
    }

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

        // elderName -> elderIds
        List<Long> elderIds;
        if (pageReqVO.getElderName() != null && !pageReqVO.getElderName().trim().isEmpty()) {
            List<ElderlyInfoDO> elders = elderlyInfoMapper.selectList(new cn.iocoder.yudao.framework.mybatis.core.query.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<ElderlyRestraintDO> pageResult = restraintMapper.selectPage(pageReqVO);
        List<ElderlyRestraintDO> 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(ElderlyRestraintDO::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<ElderlyRestraintRespVO> voList = BeanUtils.toBean(list, ElderlyRestraintRespVO.class);
        for (ElderlyRestraintRespVO 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 restraintId, Long tenantId, List<ElderlyRestraintItemSaveReqVO> itemReqList) {
        if (CollectionUtil.isEmpty(itemReqList)) {
            return;
        }
        for (ElderlyRestraintItemSaveReqVO itemReq : itemReqList) {
            ElderlyRestraintItemDO item = BeanUtils.toBean(itemReq, ElderlyRestraintItemDO.class);
            item.setRestraintId(restraintId);
            item.setTenantId(tenantId);
            restraintItemMapper.insert(item);
        }
    }
}

