package com.aucma.report.service.impl;

import cn.hutool.core.collection.ArrayIter;
import com.aucma.common.core.domain.R;
import com.aucma.common.utils.DateUtils;
import com.aucma.report.domain.*;
import com.aucma.report.mapper.GeneralReportMapper;
import com.aucma.report.service.IQualityReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * PDA管理Service业务层处理
 *
 * @author Yinq
 * @date 2023-11-21
 */
@Service
public class QualityReportServiceImpl implements IQualityReportService {
    @Autowired
    private GeneralReportMapper reportMapper;

    /**
     * 质量缺陷统计分析
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<QualityDefectsStatisticalAnalysis> qualityDefectsStatisticalAnalysisList(Map hashMap) {
        if (hashMap.containsKey("stationCodeList")) {
            hashMap.put("stationCodeList", String.valueOf(hashMap.get("stationCodeList")).split(","));
        }
        return reportMapper.qualityDefectsStatisticalAnalysisList(hashMap);
    }

    /**
     * 少错件报表
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<FewerMistakesReport> fewerMistakesReportList(Map hashMap) {
        return reportMapper.fewerMistakesReportList(hashMap);
    }

    /**
     * 质量问题前80报表
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<QualityIssuesReport> qualityIssuesReportList(Map hashMap) {
        return reportMapper.qualityIssuesReportList(hashMap);
    }


    /**
     * 产品追溯报表
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<ProductTraceabilityReport> productTraceabilityReportList(Map hashMap) {
        return reportMapper.productTraceabilityReportList(hashMap);
    }

    /**
     * 测温记录报表
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<HashMap<String, Object>> temperatureRecordReportList(Map hashMap) {
        return reportMapper.temperatureRecordReportList(hashMap);
    }

    /**
     * 灌注记录报表
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<HashMap<String, Object>> pourRecordReportList(Map hashMap) {
        return reportMapper.pourRecordReportList(hashMap);
    }

    /**
     * 质量缺陷统计分析明细
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<HashMap<String, Object>> qualityDefectsDetailList(Map hashMap) {
        return reportMapper.qualityDefectsDetailList(hashMap);
    }

    /**
     * 产品追溯明细
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<HashMap<String, Object>> productTraceabilityDetailList(Map hashMap) {
        return reportMapper.productTraceabilityDetailList(hashMap);
    }

    /**
     * 质量缺陷统计分析明细导出
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<QualityDefectsDetail> qualityDefectsDetailListExport(Map hashMap) {
        ArrayList<QualityDefectsDetail> defectsDetailArrayList = new ArrayList<>();
        List<QualityDefectsStatisticalAnalysis> analysisList = this.qualityDefectsStatisticalAnalysisList(hashMap);
        for (QualityDefectsStatisticalAnalysis item : analysisList) {
            hashMap.put("stationCode", item.getSTATION_CODE());
            List<HashMap<String, Object>> hashMaps = this.qualityDefectsDetailList(hashMap);
            for (HashMap<String, Object> map : hashMaps) {
                QualityDefectsDetail defectsDetail = new QualityDefectsDetail();
                defectsDetail.setFACTORY_NAME(item.getFACTORY_NAME());
                defectsDetail.setPRODUCT_LINE_NAME(item.getPRODUCT_LINE_NAME());
                defectsDetail.setSTATION_CODE(item.getSTATION_CODE());
                defectsDetail.setSTATION_NAME(item.getSTATION_NAME());
                defectsDetail.setREWORK_NUMBER(item.getREWORK_NUMBER());
                defectsDetail.setSEQ(Long.valueOf(String.valueOf(map.get("SEQ"))));
                defectsDetail.setQUALITY_DEFECT_NAME(String.valueOf(map.get("QUALITY_DEFECT_NAME")));
                defectsDetail.setDEFECT_NUMBER(Long.valueOf(String.valueOf(map.get("DEFECT_NUMBER"))));
                defectsDetail.setRATE(String.valueOf(map.get("RATE")));
                defectsDetailArrayList.add(defectsDetail);


            }
        }
        return defectsDetailArrayList;
    }

    /**
     * 质量返修率报表
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<RepairRateReport> repairRateReportList(Map hashMap) {
//        if (hashMap.containsKey("PRODUCT_LINE_CODE")) {
//            String productLineCode = String.valueOf(hashMap.get("PRODUCT_LINE_CODE"));
//            if (productLineCode.equals("MF_01")){
//                hashMap.put("PRODUCT_LINE_CODE", "CX_02");
//            }
//        }
        if (hashMap.containsKey("stationCodeList")) {
            String[] stationCodeLists = String.valueOf(hashMap.get("stationCodeList")).split(",");
            hashMap.put("stationCodeList", stationCodeLists);
            for (String station : stationCodeLists) {
                if (station.equals("2001") || station.equals("2006") || station.equals("2007")
                        || station.equals("2101") || station.equals("2106") || station.equals("2107")) {
                    hashMap.put("leakFlag", "1");
                }
            }
        } else {
//            String[] stationCodeLists = {"null"};
//            hashMap.put("stationCodeList", stationCodeLists);
        }

        //日
        if (hashMap.get("month").equals("1")){
            List<RepairRateReport> repairRateReports = reportMapper.repairRateReportList(hashMap);
            return repairRateReports;
        }
        //周
        else if (hashMap.get("month").equals("2")){
            Object year = String.valueOf(hashMap.get("year"));
            String beginTime = year + "-01-01";
            String endTime = year + "-12-31";
            hashMap.put("year",endTime.substring(0,4));
            hashMap.put("beginBeginTime",beginTime);
            hashMap.put("endBeginTime",endTime);
            List<RepairRateReport> repairRateReports = reportMapper.repairRateReportListWeek(hashMap);
            List<RepairRateReport>  collect = repairRateReports.stream().collect(Collectors.collectingAndThen(
                    Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(RepairRateReport::getCOLUMN_A))),ArrayList::new
            ));

            for (int i = 0; i < collect.size(); i++){
                for (int j=0;j<repairRateReports.size();j++){
                    if (collect.get(i).getCOLUMN_A().equals(repairRateReports.get(j).getCOLUMN_A())&&
                        collect.get(i).getINSPECTOR_TIME() != repairRateReports.get(j).getINSPECTOR_TIME()
                    )
                    {
                        collect.get(i).setQUALITY_SUM(collect.get(i).getQUALITY_SUM()+ repairRateReports.get(j).getQUALITY_SUM());
                        collect.get(i).setOFF_LINE_NUM(collect.get(i).getOFF_LINE_NUM()+ repairRateReports.get(j).getOFF_LINE_NUM());
                        collect.get(i).setREPAIR_RATE(collect.get(i).getREPAIR_RATE()+ repairRateReports.get(j).getREPAIR_RATE());
                    }
                }
                NumberFormat nf = NumberFormat.getPercentInstance();
                nf.setMinimumFractionDigits(2);
                double v = collect.get(i).getQUALITY_SUM() * 1.0;
                double v1 = collect.get(i).getOFF_LINE_NUM() * 1.0;
                String format = nf.format( v/v1 );
                collect.get(i).setREPAIR_RATE(String.valueOf(format));
                collect.get(i).setINSPECTOR_TIME("第"+collect.get(i).getCOLUMN_A()+"周");

            }
            return collect;
        }
        //月
        else if (hashMap.get("month").equals("3")){
            Object year = String.valueOf(hashMap.get("year"));
            String beginTime = year + "-01-01";
            String endTime = year + "-12-31";
            hashMap.put("beginBeginTime",beginTime);
            hashMap.put("endBeginTime",endTime);
                List<RepairRateReport>  repairRateReports = reportMapper.repairRateReportListMONTH(hashMap);
            List<RepairRateReport>  collect = repairRateReports.stream().collect(Collectors.collectingAndThen(
                    Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(RepairRateReport::getCOLUMN_A))),ArrayList::new
            ));
            List<RepairRateReport> repairRateReportsSumWeek = new ArrayList<>();
            for (int i = 0; i < collect.size(); i++){

                for (int j=0;j<repairRateReports.size();j++){
                    if (collect.get(i).getCOLUMN_A().equals(repairRateReports.get(j).getCOLUMN_A())&&
                            collect.get(i).getINSPECTOR_TIME() != repairRateReports.get(j).getINSPECTOR_TIME()
                    )
                    {
                        collect.get(i).setQUALITY_SUM(collect.get(i).getQUALITY_SUM()+ repairRateReports.get(j).getQUALITY_SUM());
                        collect.get(i).setOFF_LINE_NUM(collect.get(i).getOFF_LINE_NUM()+ repairRateReports.get(j).getOFF_LINE_NUM());
                        collect.get(i).setREPAIR_RATE(collect.get(i).getREPAIR_RATE()+ repairRateReports.get(j).getREPAIR_RATE());
                    }
                }
                        NumberFormat nf = NumberFormat.getPercentInstance();
                    nf.setMinimumFractionDigits(2);
                    double v = collect.get(i).getQUALITY_SUM() * 1.0;
                    double v1 = collect.get(i).getOFF_LINE_NUM() * 1.0;
                    String format = nf.format( v/v1 );
                    collect.get(i).setREPAIR_RATE(String.valueOf(format));
                        collect.get(i).setINSPECTOR_TIME(collect.get(i).getINSPECTOR_TIME().substring(0,7));
            }
            return collect;
        }    else{
            return reportMapper.repairRateReportList(hashMap);
        }
    }

    /**
     * 获取指定日期所在周的周一
     *
     * @param date 日期
     */
    public  String  getFirstDayOfWeek(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(parse);
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            c.add(Calendar.DAY_OF_MONTH, -1);
        }
        c.add(Calendar.DATE, c.getFirstDayOfWeek() - c.get(Calendar.DAY_OF_WEEK) + 1);

        String format = sdf.format(c.getTime());
        return format;
    }

    /**
     * 根据时间获取周日
     * */
    public String getLastDayOfWeek(String date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar c = Calendar.getInstance();
        c.setTime(parse);
        // 如果是周日直接返回
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            return sdf.format(parse);
        }
        //System.out.println(c.get(Calendar.DAY_OF_WEEK));
        c.add(Calendar.DATE, 7 - c.get(Calendar.DAY_OF_WEEK) + 1);
        String format = sdf.format(c.getTime());
        return format;
    }


    /**
     * 降级品占比报表
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<DowngradeProportionReport> downgradeProportionReportList(Map hashMap) {
        if (!hashMap.containsKey("dateType")) {
            return null;
        }
        hashMap.put("timeSub", Integer.parseInt(String.valueOf(hashMap.get("dateType"))));
        return reportMapper.downgradeProportionReportList(hashMap);
    }

    /**
     * 年度不良率同比报表
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<AdverseRecordYearOnYearReport> adverseRecordYearOnYearList(Map hashMap) {
        if (!hashMap.containsKey("year")) {
            return null;
        }
        return reportMapper.adverseRecordYearOnYearList(hashMap);
    }

    /**
     * 高故障率TOP20报表
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<HighFaultReport> highFaultList(Map hashMap) {
        return reportMapper.highFaultList(hashMap);
    }

    /**
     * 焊漏率报表
     *
     * @param hashMap
     * @return
     */
    @Override
    public List<WeldLeakRateReport> weldLeakRateList(Map hashMap) {
        if (hashMap.get("month").toString().equals("0")) {
            return reportMapper.weldLeakRateList(hashMap);
        }else if (hashMap.get("month").toString().equals("1")) {
            return reportMapper.weldLeakRateListMonth(hashMap);
        }
        return null;
    }

    //根据年份获取月份日期
    public  String[] getMonthBeginTime(String year) {
        String[] array = new String[12];
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, Integer.parseInt(year));
        cal.set(Calendar.MONTH,0);
        cal.set(Calendar.DATE,1);
        cal.set(Calendar.HOUR,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);
        for (int i = 0; i < 12; i++) {
            array[i] = sdf.format(cal.getTime());
            cal.add(Calendar.MONTH, 1);
        }
        return array;
    }
    //根据年份获取月份日期
    public   String[] getMonthEndTime(String year) {
        String[] array = new String[12];
        array[0] = year+"-"+"01-31 23:59:59";
        array[1] = year+"-"+"02-29 23:59:59";
        array[2] = year+"-"+"03-31 23:59:59";
        array[3] = year+"-"+"04-31 23:59:59";
        array[4] = year+"-"+"05-31 23:59:59";
        array[5] = year+"-"+"06-31 23:59:59";
        array[6] = year+"-"+"07-31 23:59:59";
        array[7] = year+"-"+"08-31 23:59:59";
        array[8] = year+"-"+"09-31 23:59:59";
        array[9] = year+"-"+"10-31 23:59:59";
        array[10] = year+"-"+"11-31 23:59:59";
        array[11] = year+"-"+"12-31 23:59:59";
return array;
    }


}
