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

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.nursing.vo.ElderlySpecialNursingLogListReqVO;
import cn.iocoder.yudao.module.system.controller.admin.nursing.vo.ElderlySpecialNursingLogPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.nursing.vo.ElderlySpecialNursingLogRespVO;
import cn.iocoder.yudao.module.system.controller.admin.nursing.vo.ElderlySpecialNursingLogSimpleRespVO;
import cn.iocoder.yudao.module.system.controller.admin.nursing.vo.SpecialNursingPlanCancelReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlyInfoDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlySpecialNursingLogDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlySpecialNursingPlanItemDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlySpecialNursingLogMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.SpecialNursingPlanItemMapper;
import cn.iocoder.yudao.module.system.service.biz.BuildService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.COMMON_NOT_FOUND;

@Service
@Validated
public class ElderlySpecialNursingLogServiceImpl implements ElderlySpecialNursingLogService {

    @Resource
    private ElderlySpecialNursingLogMapper elderlySpecialNursingLogMapper;
    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;
    @Resource
    private SpecialNursingPlanItemMapper specialNursingPlanItemMapper;

    @Autowired
    private BuildService buildService;

    @Override
    public PageResult<ElderlySpecialNursingLogSimpleRespVO> getPage(ElderlySpecialNursingLogPageReqVO pageReqVO) {

        Page<ElderlySpecialNursingLogSimpleRespVO> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        List<ElderlySpecialNursingLogSimpleRespVO> records = elderlySpecialNursingLogMapper
                .selectPageWithElderInfo(page, pageReqVO);
        for (ElderlySpecialNursingLogSimpleRespVO record : records) {
            if (record.getBedId() != null) {
                record.setBedName(buildService.getFullBedNameByBedId(record.getBedId()));
            }
        }
        page.setRecords(records);
        return new PageResult<>(records, page.getTotal());
    }

    @Override
    public List<ElderlySpecialNursingLogRespVO> getListByElderIdAndFinishTime(ElderlySpecialNursingLogListReqVO listReqVO) {
        LocalDateTime begin = toBegin(listReqVO.getFinishTime());
        LocalDateTime endExclusive = toEndExclusive(listReqVO.getFinishTime());

        List<ElderlySpecialNursingLogRespVO> respList = elderlySpecialNursingLogMapper
                .selectListByElderIdAndFinishTimeWithItemName(listReqVO.getElderId(), listReqVO.getTenantId(), begin, endExclusive);
        if (respList.isEmpty()) {
            return Collections.emptyList();
        }
        enrichElderInfo(respList);
        return respList;
    }

    @Override
    public Boolean cancel(SpecialNursingPlanCancelReqVO reqVO) {
        validateExists(reqVO);
        elderlySpecialNursingLogMapper.updateById(new ElderlySpecialNursingLogDO().setId(reqVO.getId()).setStatus(1));
        specialNursingPlanItemMapper.updateById(new ElderlySpecialNursingPlanItemDO().setId(reqVO.getSpecialItemId()).setStatus(0));
        return true;
    }

    private void enrichElderInfo(List<ElderlySpecialNursingLogRespVO> respList) {
        Set<Long> elderIds = respList.stream()
                .map(ElderlySpecialNursingLogRespVO::getElderId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        if (elderIds.isEmpty()) {
            return;
        }
        Map<Long, ElderlyInfoDO> elderMap = elderlyInfoMapper.selectBatchIds(elderIds).stream()
                .collect(Collectors.toMap(ElderlyInfoDO::getId, e -> e, (a, b) -> a));
        for (ElderlySpecialNursingLogRespVO vo : respList) {
            ElderlyInfoDO elder = elderMap.get(vo.getElderId());
            if (elder == null) {
                continue;
            }
            vo.setElderName(elder.getElderName());
            vo.setBedName(elder.getBedName());
            vo.setNurseLevelName(elder.getNurseLevelName());
        }
    }

    private static LocalDateTime toBegin(LocalDate[] range) {
        if (range == null || range.length == 0 || range[0] == null) {
            return null;
        }
        return range[0].atStartOfDay();
    }

    private static LocalDateTime toEndExclusive(LocalDate[] range) {
        if (range == null || range.length < 2 || range[1] == null) {
            return null;
        }
        return range[1].plusDays(1).atStartOfDay();
    }
    private void validateExists(SpecialNursingPlanCancelReqVO reqVO) {
        if (reqVO.getId() == null || elderlySpecialNursingLogMapper.selectById(reqVO.getId()) == null) {
            throw exception(COMMON_NOT_FOUND);
        }
        if (reqVO.getSpecialItemId() == null || specialNursingPlanItemMapper.selectById(reqVO.getSpecialItemId()) == null) {
            throw exception(COMMON_NOT_FOUND);
        }
    }
}
