package com.cf.imes.module.system.api.organ;

import cn.hutool.core.util.ObjectUtil;
import com.cf.imes.framework.common.enums.OrderStatisticsUnit;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.module.system.api.organ.dto.OrgStatisticsIsLapseRespDTO;
import com.cf.imes.module.system.api.organ.dto.OrgStatisticsReqDTO;
import com.cf.imes.module.system.api.organ.dto.OrganizationDTO;
import com.cf.imes.module.system.controller.admin.organ.vo.organ.OrganRespVO;
import com.cf.imes.module.system.dal.mysql.organ.OrganMapper;
import com.cf.imes.module.system.service.organ.OrganService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

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

import static com.cf.imes.framework.common.pojo.CommonResult.success;
import static com.cf.imes.framework.common.util.time.StatisticsChangeUtils.generateDateRangeAxis;
import static com.cf.imes.framework.common.util.time.StatisticsChangeUtils.getDateList;

@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class OrganApiImpl implements OrganApi {

    @Resource
    private OrganService organService;


    @Resource
    private OrganMapper organMapper;


    @Override
    public CommonResult<List<Long>> getOrganIdList() {
        return success(organService.getOrganIdList());
    }

    @Override
    public CommonResult<Boolean> validOrgan(Long id) {
        organService.validOrgan(id);
        return success(true);
    }

    @Override
    public CommonResult<Map<String, Integer>> getOrgTotal() {
        return success(organService.orgTotal());
    }

    @Override
    public CommonResult<Map<String, Object>> getOrgSeparate(OrgStatisticsReqDTO reqVO) {
        setOrgStatisticsReqVO(reqVO);

        Map<String, Object> resultMap = new LinkedHashMap<>();

        // 所有的日期集合
        List<String> dateList = getDateList(reqVO.getCreateTime(),reqVO.getUnit());


        // 组织有效数量
        Map<String, List<OrgStatisticsIsLapseRespDTO>> orderNotLapseRespMap = organService.orgCountAddByOrderDateAdd(reqVO).stream()
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.groupingBy(OrgStatisticsIsLapseRespDTO::getDate, LinkedHashMap::new, Collectors.toList()));

        // 组织无效数量
        Map<String, List<OrgStatisticsIsLapseRespDTO>> orderLapseRespMap = organService.orgCountLapseByOrderDate(reqVO).stream()
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.groupingBy(OrgStatisticsIsLapseRespDTO::getDate, LinkedHashMap::new, Collectors.toList()));

        // 遍历时间跨度列表，匹配数量存入数组，没有补0存入数组
        for (String dateStr : dateList) {
            int[] countArr = new int[2];
            // 组织有效数量
            Integer orderNotLapseCount = Optional.ofNullable(orderNotLapseRespMap.get(dateStr))
                    .map(list -> list.stream().findFirst().orElse(new OrgStatisticsIsLapseRespDTO()))
                    .map(OrgStatisticsIsLapseRespDTO::getOrgCount)
                    .orElse(0);
            countArr[0] = orderNotLapseCount;


            // 组织无效数量
            Integer orderLapseCount = Optional.ofNullable(orderLapseRespMap.get(dateStr))
                    .map(list -> list.stream().findFirst().orElse(new OrgStatisticsIsLapseRespDTO()))
                    .map(OrgStatisticsIsLapseRespDTO::getOrgCount)
                    .orElse(0);
            countArr[1] = orderLapseCount;

            resultMap.put(generateDateRangeAxis(dateStr, reqVO.getUnit()), countArr);
        }

        return success(resultMap);

    }

    @Override
    public CommonResult<Map<String, List<Object>>> getWarnToOrg() {
        Map<String, List<Object>> map = new HashMap<>();

        LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        LocalDateTime afterDay = today.plusDays(15).withHour(23).withMinute(59).withSecond(59);
        LocalDateTime alertDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);

        // 即将过期组织
        List<OrganRespVO> expireOrg = organService.orgCountExpire(today, afterDay);
        map.put("expireOrg", Collections.singletonList(expireOrg));

        // 已过期组织
        List<OrganRespVO> lapseOrg = organService.orgCountExpired(alertDay);
        map.put("expiredOrg", Collections.singletonList(lapseOrg));

        return success(map);
    }

    @Override
    public CommonResult<OrganizationDTO> getOrganDetails(Long organId) {

        return success(BeanUtils.toBean(organService.validOrgan(organId),OrganizationDTO.class));
    }


    @Override
    public CommonResult<List<OrganizationDTO>> getOrganDetailsByName(String organName) {

        return null;
    }


    private void setOrgStatisticsReqVO(OrgStatisticsReqDTO reqVO){
        if (ObjectUtil.isNull(reqVO.getUnit())){
            reqVO.setUnit(OrderStatisticsUnit.DAY.getValue());
        }
        if (ObjectUtil.isNull(reqVO.getCreateTime())){
            reqVO.setCreateTime(new LocalDate[2]);
        }
        LocalDate[] time = reqVO.getCreateTime();
        reqVO.setCreateTime(new LocalDate[]{time[0], time[1]});
    }
}
