package com.usky.fire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.fire.domain.DemOnDuty;
import com.usky.fire.mapper.DemOnDutyMapper;
import com.usky.fire.service.DemOnDutyService;
import com.usky.fire.service.po.UnitBeOnDutyPO;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * <p>
 * 值班表 服务实现类
 * </p>
 *
 * @author JCB
 * @since 2022-11-28
 */
@Service
public class DemOnDutyServiceImpl extends AbstractCrudService<DemOnDutyMapper, DemOnDuty> implements DemOnDutyService {

    @Override
    public List<List<UnitBeOnDutyPO>> list(String startTime, String endTime, String name) {
        List<List<UnitBeOnDutyPO>> lists = new ArrayList<>();
        List<UnitBeOnDutyPO> list = new ArrayList<>();
        LambdaQueryWrapper<DemOnDuty> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.between(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime), DemOnDuty::getDutyTime, startTime, endTime)
                .eq(StringUtils.isNotBlank(name),DemOnDuty::getPersonName,name);
        List<DemOnDuty> unitBeOnDutyLists = this.list(queryWrapper);
        unitBeOnDutyLists.forEach(stringStringMap -> list.add(enhanceUnitBeOnDutyPo(stringStringMap)));
        TreeMap<String, List<UnitBeOnDutyPO>> collect = list.stream().collect(Collectors.groupingBy(UnitBeOnDutyPO::getTime, TreeMap::new, Collectors.toList()));
        for (String s : collect.keySet()) {
            lists.add(collect.get(s));
        }
        return lists;
    }

    public UnitBeOnDutyPO enhanceUnitBeOnDutyPo(DemOnDuty unitBeOnDutyMap) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        UnitBeOnDutyPO unitBeOnDutyPo = new UnitBeOnDutyPO();
        unitBeOnDutyPo.setName(unitBeOnDutyMap.getPersonName());
        unitBeOnDutyPo.setPostName(unitBeOnDutyMap.getPositionName());
        unitBeOnDutyPo.setOrganizationName(unitBeOnDutyMap.getOrganizateName());
        unitBeOnDutyPo.setOrganizationShort(unitBeOnDutyMap.getOrganizateAbbreviate());
        unitBeOnDutyPo.setOrganizationAddress(unitBeOnDutyMap.getOrganizateAddress());
        unitBeOnDutyPo.setTime(unitBeOnDutyMap.getDutyTime().format(fmt));
        return unitBeOnDutyPo;
    }

}
