package com.pqs9900.serviceImpl.linedata;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.njcn.enums.DicDataTypeEnum;
import com.njcn.mapper.configuration.NodeInformationMapper;
import com.njcn.pojo.commons.AreaGeneralData;
import com.njcn.pojo.commons.device.Tree;
import com.njcn.pojo.configuration.DicData;
import com.njcn.pojo.configuration.NodeInformation;
import com.njcn.pojo.pointInfo.LineLedger;
import com.njcn.service.configuration.DeviceService;
import com.njcn.utils.UserUtil;
import com.njcn.utils.Utils;
import com.pqs9900.mapper.linedata.LineMarkMapper;
import com.pqs9900.pojo.linedata.MarkExcel;
import com.pqs9900.service.linedata.LineMarkService;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * system
 * 监测点打分
 *
 * @author cdf
 * @date 2021/10/27
 */
@Service
public class LineMarkServiceImpl implements LineMarkService {

    @Resource
    private LineMarkMapper lineMarkMapper;

    @Resource
    private DeviceService deviceService;

    @Resource
    private NodeInformationMapper nodeInformationMapper;



    @Resource
    private UserUtil userUtil;

    /**
     * 获取监测点台账
     *
     * @author cdf
     * @date 2021/10/27
     */
    @Override
    public List<LineLedger> getLineMark(Integer status,Integer lineGrade) {
        return  lineMarkMapper.getLineMark(status,lineGrade);
    }

    @Override
    public Integer singleOperate(Integer lineIndex, String lineGrade) {
        if(StrUtil.isBlank(lineGrade)){
            lineGrade = null;
        }
        return lineMarkMapper.singleOperate(lineIndex,lineGrade);
    }

    @Override
    public LineLedger getLineGrade(Integer lineIndex) {
        return lineMarkMapper.getLineGrade(lineIndex);
    }

    @Override
    public MarkExcel getLineMarkData(String gdName, String subName, String devName, String lineName) {
        return lineMarkMapper.getLineMarkData(gdName, subName, devName, lineName);
    }

    @Override
    public Integer updateMark(String lineGrade, Integer lineIndex) {
        return lineMarkMapper.updateMark(lineGrade, lineIndex);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String dealData(List<MarkExcel> list) {
        List<DicData> dicDataList = deviceService.getdicdata(DicDataTypeEnum.terminalGrade.getName());
        if (CollectionUtil.isEmpty(dicDataList)) {
            return "获取字典表"+DicDataTypeEnum.terminalGrade.getName()+"异常";
        }

        Integer flag = 2;
        for (MarkExcel item : list) {
            String errMsg = "第" + flag + "行";
            MarkExcel m = lineMarkMapper.getLineMarkData(item.getGdName(), item.getSubName(), item.getDevName(), item.getLineName());
            if (Objects.isNull(m)) {
                return errMsg + "未匹配到监测点对象，请仔细检查!";
            } else {
                if (Objects.isNull(m.getLineIndex()) || Objects.isNull(m.getDevIndex())) {
                    return errMsg + "获取监测点ID异常,请联系管理员!";
                }
                item.setLineIndex(m.getLineIndex());
                item.setDevIndex(m.getDevIndex());

                if (CollectionUtil.isNotEmpty(dicDataList)) {
                    boolean g = false;
                    for (DicData dicData : dicDataList) {
                        if (dicData.getDicName().equals(item.getMark())) {
                            item.setMarkId(dicData.getDicIndex());
                            item.setMarkLeave(dicData.getDicLeave());
                            g = true;
                        }
                    }
                    if (!g) {
                        return errMsg + "未知评级异常,请检查监测点评级是否存在!";
                    }
                } else {
                    return errMsg + "未知异常,请联系管理员!";
                }

            }
            flag++;
        }

        //进行批量操作E
        Integer res = lineMarkMapper.batchUpdateForLine(list);
        if (res != -1) {
            return "批量操作监测点评级失败";
        }

       /* //执行修改评级完毕进行批量修改终端前置操作
        Map<Integer, List<Long>> nodeLeave = new HashMap<>();
        List<NodeInformation> nodeInformationList = nodeInformationMapper.selectAll();
        if(CollectionUtil.isNotEmpty(nodeInformationList)){
            nodeInformationList = nodeInformationList.stream().filter((item)->{return item.getNodeStatus() == 1;}).collect(Collectors.toList());
            if(CollectionUtil.isEmpty(nodeInformationList)){
                return "前置机为空";
            }else{
                for(NodeInformation n:nodeInformationList){
                    if(nodeLeave.containsKey(n.getNodeGrade())){
                        List<Long> nodeIdList = nodeLeave.get(n.getNodeGrade());
                        nodeIdList.add(n.getNodeIndex());
                        nodeLeave.put(n.getNodeGrade(), nodeIdList);
                    }else{
                        List<Long> nodeIdList = new ArrayList<>();
                        nodeIdList.add(n.getNodeIndex());
                        nodeLeave.put(n.getNodeGrade(), nodeIdList);
                    }
                }

                //判断前置机是否每个级别的都有
                if(!nodeLeave.containsKey(0)||!nodeLeave.containsKey(1)){
                    return "当前缺少重要或普通前置机";
                }
            }
        }

        Random random = new Random();

        Map<Integer, Integer> map = test(list);
        List<MarkExcel> abc = new ArrayList<>();
        map.forEach((key,value)->{
            MarkExcel markExcel = new MarkExcel();
            markExcel.setDevIndex(key);
           if(value == 0){
               Long nodeId = nodeLeave.get(0).get(random.nextInt(nodeLeave.get(0).size()));
               markExcel.setMarkLeaveId(nodeId);
           }else {
               Long nodeId = nodeLeave.get(1).get(random.nextInt(nodeLeave.get(1).size()));
               markExcel.setMarkLeaveId(nodeId);
           }
            abc.add(markExcel);
        });


        System.out.println("一共有"+abc.size()+"台装置要修改前置机");

        Integer nodeRes = lineMarkMapper.batchUpdateNode(abc);
        if(nodeRes != -1){
            return "批量配置前置机失败";
        }
*/
        return "操作成功";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdateLineMarkStop() {
        List<MarkExcel> ppList = new ArrayList<>();
        List<Integer> lineIds = lineMarkMapper.getStopLineIds();

        lineIds.forEach(item->{
            MarkExcel markExcel = new MarkExcel();
            markExcel.setLineIndex(item);
            markExcel.setMarkId(null);
            ppList.add(markExcel);
        });

        if(CollectionUtil.isEmpty(ppList)){
            return false;
        }

        lineMarkMapper.batchUpdateForLine(ppList);
        return true;
    }


    //
    public Map<Integer, Integer> test(List<MarkExcel> list){
        Map<Integer,Integer> map = new HashMap();
        for(MarkExcel markExcel:list){
            if(map.containsKey(markExcel.getDevIndex())){
                Integer leave = map.get(markExcel.getDevIndex());
                if(markExcel.getMarkLeave()>leave){
                    map.put(markExcel.getDevIndex(), markExcel.getMarkLeave());
                }
            }else {
                map.put(markExcel.getDevIndex(),markExcel.getMarkLeave());
            }

        }
        return map;
    }


}
