package com.ximai.mes.kanban.service;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximai.mes.kanban.dto.abnormal.AbnormalMonthStatDto;
import com.ximai.mes.md.domain.MdWorkunit;
import com.ximai.mes.md.mapper.MdWorkunitMapper;
import com.ximai.mes.md.service.IMdWorkunitService;
import com.ximai.mes.qc.domain.QcAbnormalInformation;
import com.ximai.mes.qc.domain.QcAbnormalReport;
import com.ximai.mes.qc.dto.QcAbnormalReportDto;
import com.ximai.mes.qc.dto.QcAbnormalReportStatusEnum;
import com.ximai.mes.qc.dto.QcAbnormalTypeEnum;
import com.ximai.mes.qc.mapper.QcAbnormalReportMapper;
import com.ximai.mes.qc.service.IQcAbnormalInformationService;
import com.ximai.mes.qc.service.IQcAbnormalReportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class KanbanAbnormalService {

    @Autowired
    IQcAbnormalReportService abnormalReportService;
    @Autowired
    IQcAbnormalInformationService abnormalInformationService;
    @Autowired
    MdWorkunitMapper workunitMapper;
    @Autowired
    QcAbnormalReportMapper abnormalReportMapper;

    @ApiOperation("当月异常分布数据")
    @PostMapping("/currentMonthStat")
    public AbnormalMonthStatDto currentMonthStat() {
        //本月第一天
        LocalDateTime monthFirstDay = LocalDateTime.now().withDayOfMonth(1).with(LocalTime.MIN);
        AbnormalMonthStatDto rst = new AbnormalMonthStatDto();
        QueryWrapper<QcAbnormalReport> query = new QueryWrapper<>();
        query.ge("create_time", monthFirstDay);
        List<QcAbnormalReportDto> abnormalList = abnormalReportService.selectQcAbnormalReportDtoList(query);

        Map<String, List<QcAbnormalReportDto>> abnormalTypeMap = abnormalList.stream().collect(Collectors.groupingBy(s->s.getAbnormalType()));
        List<QcAbnormalReportDto> equipAbnormal = abnormalTypeMap.getOrDefault(QcAbnormalTypeEnum.DEVI.getType(), new ArrayList<>());
        List<QcAbnormalReportDto> productAbnormal = abnormalTypeMap.getOrDefault(QcAbnormalTypeEnum.PROD.getType(), new ArrayList<>());
        AbnormalMonthStatDto.AbnormalMonthStatDetail abnormal1 = this.stat(equipAbnormal);
        AbnormalMonthStatDto.AbnormalMonthStatDetail abnormal2 = this.stat(productAbnormal);
        rst.setProductAbnormal(abnormal2);
        rst.setEquipAbnormal(abnormal1);
        //统计所有未关闭设备异常
        QueryWrapper<MdWorkunit> workunitQuery = new QueryWrapper<>();
        workunitQuery.eq("enable_flag", "Y");
        int workunitCt = workunitMapper.selectCount(workunitQuery);
        workunitQuery.eq("fault_flag", "Y");
        int errorWorkunitCt = workunitMapper.selectCount(workunitQuery);
        rst.setEquipErrorCt(errorWorkunitCt);
        rst.setEquipCt(workunitCt-errorWorkunitCt);
        //查询七天内设备异常，按天统计
        Calendar last7Day = Calendar.getInstance();
        last7Day.set(Calendar.DATE, -6);
        Map<String,List<QcAbnormalReportDto>> newEquipAbnormalMap = equipAbnormal.stream()
                .filter(s->s.getCreateTime().compareTo(last7Day.getTime())>0)
                .collect(Collectors.groupingBy(s-> DateUtil.format(s.getCreateTime(),"MMdd")));
        //按日期dd/MM分组
        List<Integer> last7EquipAbnormalCt = new ArrayList<>();
        Calendar tempCurr = Calendar.getInstance();
        for(int i=0;i<7;i++){
            String key = DateUtil.format(tempCurr.getTime(), "MMdd");
            if(newEquipAbnormalMap.containsKey(key)){
                last7EquipAbnormalCt.add(newEquipAbnormalMap.get(key).size());
            }else {
                last7EquipAbnormalCt.add(0);
            }
            tempCurr.add(Calendar.DATE, -1);
        }
        rst.setEquipErrorArr(last7EquipAbnormalCt);
        return rst;
    }

    private AbnormalMonthStatDto.AbnormalMonthStatDetail stat(List<QcAbnormalReportDto> abnormalList){
        AbnormalMonthStatDto.AbnormalMonthStatDetail abnormal1 = new AbnormalMonthStatDto.AbnormalMonthStatDetail();
        if(abnormalList==null){
            return abnormal1;
        }
        abnormal1.setTotalCt(abnormalList.size());
        //报检时间超一天未关闭-超时未闭
        Calendar curr = Calendar.getInstance();
        curr.add(Calendar.DATE, -1);
        int expireCt = abnormalList.stream().filter(s->{
            if(s.getAbnormalStatus().equals(QcAbnormalReportStatusEnum.NOT.getStatus())
                ||s.getAbnormalStatus().equals(QcAbnormalReportStatusEnum.SUBMIT.getStatus())){
                Calendar createTemp = Calendar.getInstance();
                createTemp.setTime(s.getCreateTime());
                createTemp.add(Calendar.DATE, 1);
                if(createTemp.getTime().compareTo(curr.getTime())<0){
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList()).size();
        abnormal1.setExpireUnClose(expireCt);
        abnormal1.setUnCloseCt(abnormalList.stream().filter(s->s.getAbnormalStatus().equals(QcAbnormalReportStatusEnum.NOT.getStatus())
                ||s.getAbnormalStatus().equals(QcAbnormalReportStatusEnum.SUBMIT.getStatus())).collect(Collectors.toList()).size());
        return abnormal1;
    }

}
