package com.pqs9300.serviceimpl.formdata;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.njcn.mapper.data.LimitRateMapper;
import com.njcn.mapper.user.DeptsMapper;
import com.njcn.pojo.commons.DatePojo;
import com.njcn.pojo.configuration.DicData;
import com.njcn.pojo.data.LimitRate;
import com.njcn.pojo.user.Depts;
import com.njcn.shiro.token.TokenManager;
import com.njcn.sso.pojo.user.User;
import com.njcn.utils.AppConfig;
import com.njcn.utils.PubUtils;
import com.njcn.utils.UserUtil;
import com.pqs9300.mapper.formdata.FormDataMapper;
import com.pqs9300.mapper.strategy.AlarmImplWarning;
import com.pqs9300.mapper.strategy.WarningStrategyMapper;
import com.pqs9300.mapper.transaction.SuperviseMapper;
import com.pqs9300.pojo.formdata.ConditionDataDto;
import com.pqs9300.pojo.formdata.FormData;
import com.pqs9300.pojo.formdata.LimitRateDto;
import com.pqs9300.pojo.strategy.ThsAlarmFormAss;
import com.pqs9300.pojo.strategy.ThsAlarmFormDTO;
import com.pqs9300.pojo.transaction.OverRunLog;
import com.pqs9300.pojo.transaction.Supervise;
import com.pqs9300.service.formdata.FormDataService;

@Service
public class FormDataServiceImpl implements FormDataService {
    @Autowired
    private AppConfig appConfig;
    @Autowired
    private FormDataMapper formDataMapper;
    @Autowired
    private DeptsMapper deptsMapper;
    @Autowired
    private AlarmImplWarning alarmImplWarning;
    @Autowired
    private SuperviseMapper superviseMapper;
    @Autowired
    private LimitRateMapper limitRateMapper;

    @Autowired
    private WarningStrategyMapper warningStrategyMapper;
    @Resource
    private UserUtil userUtil;

    @Override
    public void insertFormData(int... type) {
        int tt=type.length > 0? 1 : 0;
        Map<String, ConditionDataDto> map = getMapCondition(0, type.length > 0 ? alarmImplWarning : warningStrategyMapper); //一级策略
        Map<String, ConditionDataDto> map2 = getMapCondition(2, type.length > 0 ? alarmImplWarning : warningStrategyMapper); //三级策略
        DatePojo datePojo = new DatePojo();
        getTime(new Date(), datePojo, type.length > 0 ? appConfig.getOverRunDay() : 1);
        List<FormData> formDataList = getResultByCondition(map,map2, datePojo.getStartTime(), datePojo.getEndTime(),tt);
        Iterator<FormData> iterator = formDataList.iterator();

        while (iterator.hasNext()) { //按部门区分
            FormData formData = iterator.next();
            Map<Integer, Map<Date, FormData.resultPojo>> m = formData.getMapresultPojo();

            String lineName = "";
            String des = "";
            String uuid = UUID.randomUUID().toString();
            formData.setSupIndex(uuid);
            formData.setCreateTime(new Date());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

            if (type.length > 0) {
                Iterator<Map.Entry<Integer, Map<Date, FormData.resultPojo>>> iterator1 = m.entrySet().iterator();

                while (iterator1.hasNext()) {
                    Map.Entry<Integer, Map<Date, FormData.resultPojo>> mm = iterator1.next();
                    Iterator<Map.Entry<Date, FormData.resultPojo>> iterator2 = mm.getValue().entrySet().iterator();

                    while (iterator2.hasNext()) {
                        Map.Entry<Date, FormData.resultPojo> map1 = iterator2.next();
                        FormData.resultPojo resultPojo = map1.getValue();
                        formData.getSetDate().add(map1.getKey());
                    }
                }
            }

            if (type.length > 0 && formData.getSetDate().size() > 9 || type.length == 0) {
                Iterator<Map.Entry<Integer, Map<Date, FormData.resultPojo>>> iteratorMap = m.entrySet().iterator();

                while (iteratorMap.hasNext()) {
                    Map.Entry<Integer, Map<Date, FormData.resultPojo>> mm = iteratorMap.next();
                    Iterator<Map.Entry<Date, FormData.resultPojo>> iterator2 = mm.getValue().entrySet().iterator();

                    while (iterator2.hasNext())  {
                        Map.Entry<Date, FormData.resultPojo> map1 = iterator2.next();
                        FormData.resultPojo resultPojo = map1.getValue();
                        lineName = resultPojo.getLineName() + (m.size() > 1 ? ("等" + m.size()) : "") + "监测点";
                        des = resultPojo.getFirstDes().get(0) + "超标监督";
                        formDataMapper.insertOverData(mm.getKey(), formData.getSupIndex(), resultPojo.getDescription().toString(), formatDate(map1.getKey(), "yyyy-MM-dd"), resultPojo.getCount(), resultPojo.getName());
                    }
                }

                String deptsName = simpleDateFormat.format(new Date()) + formData.getDeptsName() + lineName + des;
                formData.setSupName(deptsName);
                formData.setCreateUser(getUserIndex(formData.getDeptsIndex()));
                formData.setEventDate(formatDate(datePojo.getStartTime(), "yyyy-MM-dd"));
                formDataMapper.insertSuperData(formData, type.length > 0 ? 1 : 0); //插入技术监督表
            }
        }
    }

    public List<FormData> getResultByCondition(Map<String, ConditionDataDto> map,Map<String, ConditionDataDto> map2, Date start, Date end,Integer type, List<String>... index) {

        List<FormData> deptsList = (index.length > 0 ? getListDeptsByIndex(index[0]) : getListDepts(getSysType()));
        List<FormData> listFormData = new ArrayList<>();

        if (deptsList != null) {
            List<DicData> dicDataList = formDataMapper.getLevel("电压等级");

            for (FormData deptsIndex : deptsList) {
                String onedept =deptsIndex.getDeptsIndex(); //获取部门id
                List<String> levelList = new ArrayList<>(); //获取当前部门所能查询的电压等级
                getLevel(deptsIndex.getCustomDept(), levelList, dicDataList);

                //获取当前部门下符合电压等级的监测点
                List<Long> lineList = formDataMapper.getListLineByDepts(onedept, getSysType(), levelList);
                Set<String> set = new HashSet<>();

                List<LimitRateDto> limitRateList = new ArrayList<>(); //存储越限监测点
                List<LimitRateDto> limitRateListDel = new ArrayList<>(); //需要剔除的三级策略监测点


                List<Depts> deptsListDown = userUtil.getDeptsByNode(onedept);
                List<Depts> deptsListUp = userUtil.getDeptsByNodeUp(onedept);
                //首先查出upUser为空的，当前用户权限部门下的所有事件
                Set<String> deptsIndexs = new HashSet<>();
                deptsIndexs.add(onedept);
                for (Depts i : deptsListDown) {
                    deptsIndexs.add(i.getDeptsIndex());
                }
                for (Depts i : deptsListUp) {
                    deptsIndexs.add(i.getDeptsIndex());
                }
                List<String> listDept = new ArrayList<>(deptsIndexs);//子级父级部门
                List<Long> useful =null;
                List<Long> useless=null;
                if(type == 0){
                    //预警
                    useful =formDataMapper.getStrategyLineByDept(listDept,0);
                    useless =formDataMapper.getStrategyLineByDept(listDept,2);
                }else {
                    //告警
                    useful =formDataMapper.getAlarmStrategyLineByDept(listDept,0);
                    useless =formDataMapper.getAlarmStrategyLineByDept(listDept,2);
                }


                Iterator<Map.Entry<String, ConditionDataDto>> iterator2 = map2.entrySet().iterator();
                while (iterator2.hasNext()) {
                    Map.Entry<String, ConditionDataDto> dataEntry = iterator2.next();
                    ConditionDataDto conditionDataDtos = dataEntry.getValue();
                    ConditionDataDto zu = new ConditionDataDto();
                    String deptId = conditionDataDtos.getDeptStreateIndex();
                    Boolean flag =  listDept.contains(deptId);
                    List<Long> list = new ArrayList<>();
                    if(flag){
                        for (Long lineIndex : lineList) {
                            for (Long lineExit : conditionDataDtos.getListExitsLine()) {
                                if (lineIndex .equals(lineExit) ) {
                                    list.add(lineIndex);
                                }
                            }
                        }
                        if(conditionDataDtos.getListExitsLine().size()>0 && list.size() == 0){
                            continue;
                        }

                        zu.setListExitsLine(list);

                        zu.setListExitLoadType(conditionDataDtos.getListExitLoadType());
                        zu.setListExitOption(conditionDataDtos.getListExitOption());
                        zu.setOperation(conditionDataDtos.getOperation());

                        //处理查询条件
                        //  setCondition(zu.getListExitLoadType(),a);
                        //  setCondition(conditionDataDtos.getListExitOption(), conditionDataDtos.getListNotExitOption());
                        // setCondition(zu.getListExitsLine(), b);
                        StringBuilder[] stringBuilders = setOption(zu.getListExitOption(), zu.getOperation(), set);
                        zu.setCondition(stringBuilders[0].toString());
                        zu.setConditionResult(stringBuilders[1].toString());
                        zu.setStartTime(start);
                        zu.setEndTime(end);
                        zu.setDeptsIndex(deptsIndex.getDeptsIndex());
                        zu.setSysType(getSysType());
                        //带入查询结果查询数据
                        List<LimitRateDto> limitList2 = formDataMapper.getLimitRate(zu);
                        if(conditionDataDtos.getListExitsLine().size() == 0){
                            Iterator<LimitRateDto> itt =limitList2.iterator();
                            while (itt.hasNext()){
                                LimitRateDto limitRateDto =itt.next();
                                boolean fg =lineList.contains(limitRateDto.getLineIndex().longValue());
                                if(!fg){
                                    itt.remove();
                                    continue;
                                }
                                for(Long a :useless){
                                    if(limitRateDto.getLineIndex().equals(a)){
                                        itt.remove();
                                    }
                                }
                            }

                        }
                        limitRateListDel.addAll(limitList2);

                    }
                }



                Iterator<Map.Entry<String, ConditionDataDto>> iterator = map.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, ConditionDataDto> dataEntry = iterator.next();
                    ConditionDataDto zu = new ConditionDataDto();
                    ConditionDataDto conditionDataDtos = dataEntry.getValue();
                    String deptId = conditionDataDtos.getDeptStreateIndex();
                    Boolean flag =  listDept.contains(deptId);
                    List<Long> list = new ArrayList<>();
                    if(flag){
                        for (Long lineIndex : lineList) {
                            for (Long lineExit : conditionDataDtos.getListExitsLine()) {
                                if (lineIndex .equals(lineExit) ) {
                                    list.add(lineIndex);
                                }
                            }
                        }
                        if(conditionDataDtos.getListExitsLine().size()>0 && list.size() == 0){
                            continue;
                        }

                        zu.setListExitsLine(list);

                        zu.setListExitLoadType(conditionDataDtos.getListExitLoadType());
                        zu.setListExitOption(conditionDataDtos.getListExitOption());
                        zu.setOperation(conditionDataDtos.getOperation());

                        //处理查询条件
                        //  setCondition(zu.getListExitLoadType(),a);
                        //  setCondition(conditionDataDtos.getListExitOption(), conditionDataDtos.getListNotExitOption());
                        // setCondition(zu.getListExitsLine(), b);
                        StringBuilder[] stringBuilders = setOption(zu.getListExitOption(), zu.getOperation(), set);
                        zu.setCondition(stringBuilders[0].toString());
                        zu.setConditionResult(stringBuilders[1].toString());
                        zu.setStartTime(start);
                        zu.setEndTime(end);
                        zu.setDeptsIndex(deptsIndex.getDeptsIndex());
                        zu.setSysType(getSysType());
                        //带入查询结果查询数据
                        List<LimitRateDto> limitList = formDataMapper.getLimitRate(zu);

                        if(conditionDataDtos.getListExitsLine().size() == 0){
                            Iterator<LimitRateDto> itt =limitList.iterator();
                            while (itt.hasNext()){
                                LimitRateDto limitRateDto =itt.next();
                                boolean fg =lineList.contains(limitRateDto.getLineIndex().longValue());
                                if(!fg){
                                    itt.remove();
                                    continue;
                                }
                                for(Long a :useful){
                                    if(limitRateDto.getLineIndex().equals(a)){
                                        itt.remove();
                                    }
                                }
                            }

                        }
                        limitRateList.addAll(limitList);
                    }
                }
                //查询结果汇总



                Iterator<LimitRateDto> limitFilter = limitRateList.iterator();
                while(limitFilter.hasNext()){
                    LimitRateDto l = limitFilter.next();
                    for(LimitRateDto limitRateDto :limitRateListDel){
                        if(l.getTimes().equals(limitRateDto.getTimes()) && l.getLineIndex().equals(limitRateDto.getLineIndex())){
                            limitFilter.remove();
                            break;
                        }
                    }
                }

                Iterator<LimitRateDto> limitRateIterator = limitRateList.iterator();
                FormData formData = new FormData(); //最终汇总的数据
                formData.setDeptsIndex(deptsIndex.getDeptsIndex());
                formData.setDeptsName(deptsIndex.getDeptsName());

                while (limitRateIterator.hasNext()) {
                    LimitRateDto limitRateDto = limitRateIterator.next();
                    Map<Date, FormData.resultPojo> pojoMap = new HashMap<>();
                    LimitRate limitRate = limitRateDto.getLimitRate();
                    Iterator<String> setIterator = set.iterator(); //需要筛选展示的指标数据
                    FormData.resultPojo resultPojo = formData.new resultPojo();
                    resultPojo.setLineName(limitRateDto.getLineName());
                    resultPojo.setBdName(limitRateDto.getBdName());
                    resultPojo.setGdName(limitRateDto.getGdName());
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                    resultPojo.setName(limitRateDto.getBdName() + "_" + limitRateDto.getLineName() + "_" + simpleDateFormat.format(limitRateDto.getTimes()) + "_" + limitRateDto.getLineIndex().toString());

                    if (formData.getMapresultPojo().containsKey(limitRate.getMyIndex())) {
                        pojoMap = formData.getMapresultPojo().get(limitRate.getMyIndex());

                        if (pojoMap.containsKey(limitRateDto.getLimitRate().getTimeID())) {
                            resultPojo = pojoMap.get(limitRateDto.getLimitRate().getTimeID());
                        }
                    }

                    while (setIterator.hasNext()) {
                        switch (setIterator.next()) {
                            case "voltage": {
                                resultPojo.getLimitRate().setVoltageDevOvertime(limitRate.getVoltageDevOvertime());
                                break;
                            }
                            case "ubalance": {
                                resultPojo.getLimitRate().setUBalanceOverTime(limitRate.getUBalanceOverTime());
                                break;
                            }
                            case "uaberrance": {
                                resultPojo.getLimitRate().setUAberranceOverTime(limitRate.getUAberranceOverTime());
                                break;
                            }
                            case "freq": {
                                resultPojo.getLimitRate().setFreqDevOverTime(limitRate.getFreqDevOverTime());
                                break;
                            }
                            case "flicker": {
                                resultPojo.getLimitRate().setFlickerOverTime(limitRate.getFlickerOverTime());
                                break;
                            }
                            case "uharm": {
                                resultPojo.getLimitRate().setUHarm2OverTime(limitRate.getUHarm2OverTime());
                                resultPojo.getLimitRate().setUHarm3OverTime(limitRate.getUHarm3OverTime());
                                resultPojo.getLimitRate().setUHarm4OverTime(limitRate.getUHarm4OverTime());
                                resultPojo.getLimitRate().setUHarm5OverTime(limitRate.getUHarm5OverTime());
                                resultPojo.getLimitRate().setUHarm6OverTime(limitRate.getUHarm6OverTime());
                                resultPojo.getLimitRate().setUHarm7OverTime(limitRate.getUHarm7OverTime());
                                resultPojo.getLimitRate().setUHarm8OverTime(limitRate.getUHarm8OverTime());
                                resultPojo.getLimitRate().setUHarm9OverTime(limitRate.getUHarm9OverTime());
                                resultPojo.getLimitRate().setUHarm10OverTime(limitRate.getUHarm10OverTime());
                                resultPojo.getLimitRate().setUHarm11OverTime(limitRate.getUHarm11OverTime());
                                resultPojo.getLimitRate().setUHarm12OverTime(limitRate.getUHarm12OverTime());
                                resultPojo.getLimitRate().setUHarm13OverTime(limitRate.getUHarm13OverTime());
                                resultPojo.getLimitRate().setUHarm14OverTime(limitRate.getUHarm14OverTime());
                                resultPojo.getLimitRate().setUHarm15OverTime(limitRate.getUHarm15OverTime());
                                resultPojo.getLimitRate().setUHarm16OverTime(limitRate.getUHarm16OverTime());
                                resultPojo.getLimitRate().setUHarm17OverTime(limitRate.getUHarm17OverTime());
                                resultPojo.getLimitRate().setUHarm18OverTime(limitRate.getUHarm18OverTime());
                                resultPojo.getLimitRate().setUHarm19OverTime(limitRate.getUHarm19OverTime());
                                resultPojo.getLimitRate().setUHarm20OverTime(limitRate.getUHarm20OverTime());
                                resultPojo.getLimitRate().setUHarm21OverTime(limitRate.getUHarm21OverTime());
                                resultPojo.getLimitRate().setUHarm22OverTime(limitRate.getUHarm22OverTime());
                                resultPojo.getLimitRate().setUHarm23OverTime(limitRate.getUHarm23OverTime());
                                resultPojo.getLimitRate().setUHarm24OverTime(limitRate.getUHarm24OverTime());
                                resultPojo.getLimitRate().setUHarm25OverTime(limitRate.getUHarm25OverTime());
                                break;
                            }
                            case "iharm": {
                                resultPojo.getLimitRate().setIHarm2OverTime(limitRate.getIHarm2OverTime());
                                resultPojo.getLimitRate().setIHarm3OverTime(limitRate.getIHarm3OverTime());
                                resultPojo.getLimitRate().setIHarm4OverTime(limitRate.getIHarm4OverTime());
                                resultPojo.getLimitRate().setIHarm5OverTime(limitRate.getIHarm5OverTime());
                                resultPojo.getLimitRate().setIHarm6OverTime(limitRate.getIHarm6OverTime());
                                resultPojo.getLimitRate().setIHarm7OverTime(limitRate.getIHarm7OverTime());
                                resultPojo.getLimitRate().setIHarm8OverTime(limitRate.getIHarm8OverTime());
                                resultPojo.getLimitRate().setIHarm9OverTime(limitRate.getIHarm9OverTime());
                                resultPojo.getLimitRate().setIHarm10OverTime(limitRate.getIHarm10OverTime());
                                resultPojo.getLimitRate().setIHarm11OverTime(limitRate.getIHarm11OverTime());
                                resultPojo.getLimitRate().setIHarm12OverTime(limitRate.getIHarm12OverTime());
                                resultPojo.getLimitRate().setIHarm13OverTime(limitRate.getIHarm13OverTime());
                                resultPojo.getLimitRate().setIHarm14OverTime(limitRate.getIHarm14OverTime());
                                resultPojo.getLimitRate().setIHarm15OverTime(limitRate.getIHarm15OverTime());
                                resultPojo.getLimitRate().setIHarm16OverTime(limitRate.getIHarm16OverTime());
                                resultPojo.getLimitRate().setIHarm17OverTime(limitRate.getIHarm17OverTime());
                                resultPojo.getLimitRate().setIHarm18OverTime(limitRate.getIHarm18OverTime());
                                resultPojo.getLimitRate().setIHarm19OverTime(limitRate.getIHarm19OverTime());
                                resultPojo.getLimitRate().setIHarm20OverTime(limitRate.getIHarm20OverTime());
                                resultPojo.getLimitRate().setIHarm21OverTime(limitRate.getIHarm21OverTime());
                                resultPojo.getLimitRate().setIHarm22OverTime(limitRate.getIHarm22OverTime());
                                resultPojo.getLimitRate().setIHarm23OverTime(limitRate.getIHarm23OverTime());
                                resultPojo.getLimitRate().setIHarm24OverTime(limitRate.getIHarm24OverTime());
                                resultPojo.getLimitRate().setIHarm25OverTime(limitRate.getIHarm25OverTime());
                                break;
                            }
                        }
                    }

                    pojoMap.put(limitRateDto.getLimitRate().getTimeID(), resultPojo);
                    formData.getMapresultPojo().put(limitRate.getMyIndex(), pojoMap);
                }

                Map<Integer, Map<Date, FormData.resultPojo>> m = formData.getMapresultPojo();

                if (m.size() > 0) {
                    formData.setValue();
                    listFormData.add(formData);
                }
            }
        }

        return listFormData;
    }

    public <T extends WarningStrategyMapper> Map<String, ConditionDataDto> getMapCondition(Integer grade, T t) {   //key-策略的guid，value-策略的具体配置
        List<ThsAlarmFormDTO> listExist = t.getEarlyWarnListbyGrade(grade); //获取一级预警策略
        Map<String, ConditionDataDto> map = new HashMap<>();

        if (listExist != null) {
            Iterator<ThsAlarmFormDTO> iterator = listExist.iterator();

            while (iterator.hasNext()) {
                ThsAlarmFormDTO thsAlarmFormDTO = iterator.next();
                if (thsAlarmFormDTO.getGrade().equals(grade)) {
                    ConditionDataDto conditionData = new ConditionDataDto();

                    if (map.containsKey(thsAlarmFormDTO.getWfIndex())) {
                        conditionData = map.get(thsAlarmFormDTO.getWfIndex());
                    }

                    conditionData.setOperation(thsAlarmFormDTO.getOperation());
                    conditionData.setDeptStreateIndex(userUtil.getDeptsIndex(thsAlarmFormDTO.getUserIndex()));
                    List<ThsAlarmFormAss> thsAlarmFormAssList = t.getEarlyWarnAssBywfIndex(thsAlarmFormDTO.getWfIndex());

                    transLate(thsAlarmFormAssList, conditionData);

                    if (conditionData.getListExitOption().size() > 0) { //过滤掉只建立没有配置的数据
                        map.put(thsAlarmFormDTO.getWfIndex(), conditionData);
                    }
                }
            }
        }

        return map;
    }

    private StringBuilder[] setOption(List<String> list, Integer operation, Set<String> set) {
        List<String> listOptionName = formDataMapper.getOptionList(list);
        StringBuilder[] stringBuilders = new StringBuilder[2];
        StringBuilder option = new StringBuilder("");
        StringBuilder result = new StringBuilder("");
        String strOption = (operation == 0 ? " and " : " or ");

        for (String optionName : listOptionName) {
            switch (optionName) {
                case "电压偏差": {
                    option.append("b.voltage_dev_overtime > 0").append(strOption);
                    result.append("b.voltage_dev_overtime voltageDevOvertime,");
                    set.add("voltage");
                    break;
                }
                case "不平衡电压": {
                    option.append("b.ubalance_overtime > 0").append(strOption);
                    result.append("b.ubalance_overtime UBalanceOverTime,");
                    set.add("ubalance");
                    break;
                }
                case "电压总畸变率": {
                    option.append("b.uaberrance_overtime > 0").append(strOption);
                    result.append("b.uaberrance_overtime UAberranceOverTime,");
                    set.add("uaberrance");
                    break;
                }
                case "频率偏差": {
                    option.append("b.freq_dev_overtime > 0").append(strOption);
                    result.append("b.freq_dev_overtime freqDevOverTime,");
                    set.add("freq");
                    break;
                }
                case "谐波电压含有率": {
                    String str = "";
                    String s = "";

                    for (int i = 2; i < 26; i++) {
                        if(i ==2){
                            str += "(b.UHarm_" + i + "_OverTime > 0" + " or ";
                            s += "b.UHarm_" + i + "_OverTime UHarm" + i + "OverTime,";
                        }else if(i==25){
                            str += "b.UHarm_" + i + "_OverTime > 0)" + " "+strOption+" ";
                            s += "b.UHarm_" + i + "_OverTime UHarm" + i + "OverTime,";
                        }else {
                            str += "b.UHarm_" + i + "_OverTime > 0" + " or ";
                            s += "b.UHarm_" + i + "_OverTime UHarm" + i + "OverTime,";
                        }

                    }

                    option.append(str);
                    result.append(s);
                    set.add("uharm");
                    break;
                }
                case "谐波电流幅值": {
                    String str = "";
                    String s = "";

                    for (int i = 2; i < 26; i++) {
                        if(i==2){
                            str += "(b.IHarm_" + i + "_OverTime > 0" + " or ";
                            s += "b.IHarm_" + i + "_OverTime IHarm" + i + "OverTime,";
                        }else if(i==25){
                            str += "b.IHarm_" + i + "_OverTime > 0)" + " "+strOption+" ";
                            s += "b.IHarm_" + i + "_OverTime IHarm" + i + "OverTime,";
                        }else {
                            str += "b.IHarm_" + i + "_OverTime > 0" + " or ";
                            s += "b.IHarm_" + i + "_OverTime IHarm" + i + "OverTime,";
                        }
                    }

                    option.append(str);
                    result.append(s);
                    set.add("iharm");
                    break;
                }
                case "长时电压闪变": {
                    option.append("b.flicker_overtime > 0").append(strOption);
                    result.append("b.flicker_overtime flickerOverTime,");
                    set.add("flicker");
                    break;
                }
            }
        }

        option.delete(option.lastIndexOf(strOption), option.length());
        result.delete(result.lastIndexOf(","), result.length());
        stringBuilders[0] = option;
        stringBuilders[1] = result;
        return stringBuilders;
    }

    public List<FormData> getListDeptsByIndex(List<String> index) {
        return formDataMapper.getListDeptsByIndex(index);
    }

    //获取
    private void getLevel(Integer level, List<String> list, List<DicData> dicDataList) {
        for (DicData dicData : dicDataList) {
            if (dicData.getDicName().startsWith("正负") || dicData.getDicName().startsWith("±")){
                continue;
            }
            Float f = Float.parseFloat(dicData.getDicName().substring(0, dicData.getDicName().indexOf("kV")));
            if (level.equals(0) && f.floatValue() < 220f) { //非自定义  220kV以下电压等级
                list.add(dicData.getDicIndex());
            } else if (level.equals(1) && f.floatValue() >= 220f) { //自定义 220kV以上电压等级
                list.add(dicData.getDicIndex());
            }
        }
    }


    private void transLate(List<ThsAlarmFormAss> list, ConditionDataDto conditionData) {
        if (list != null) {
            Iterator<ThsAlarmFormAss> iterator = list.iterator();

            while (iterator.hasNext()) {
                ThsAlarmFormAss thsAlarmFormAss = iterator.next();

                switch (thsAlarmFormAss.getType().intValue()) {
                    case 0: { //干扰源类型
                        conditionData.getListExitLoadType().add(thsAlarmFormAss.getWfassIndex());
                        break;
                    }
                    case 1: { //指标类型
                        conditionData.getListExitOption().add(thsAlarmFormAss.getWfassIndex());
                        break;
                    }
                    case 2: { //监测点ID
                        conditionData.getListExitsLine().add(Long.parseLong(thsAlarmFormAss.getWfassIndex()));
                        break;
                    }
                }
            }
        }
    }


    private void getTime(Date time, DatePojo datePojo, int offset) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.DAY_OF_MONTH, 0 - offset);
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(time);
        if (offset > 0) {
            calendar1.add(Calendar.DAY_OF_MONTH, -1);
        } else {
            calendar1.add(Calendar.DAY_OF_MONTH, 0);
        }

        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND,0);
        calendar1.set(Calendar.HOUR_OF_DAY, 23);
        calendar1.set(Calendar.MINUTE, 59);
        calendar1.set(Calendar.SECOND, 59);
        calendar1.set(Calendar.MILLISECOND,999);
        datePojo.setStartTime(calendar.getTime());
        datePojo.setEndTime(calendar1.getTime());
    }

    @Override
    public List<OverRunLog> getListOverRunLog(List<String> deptsIndex, Date time, int... type) {
        Map<String, ConditionDataDto> firstMap = getMapCondition(0, type.length > 0 ? alarmImplWarning : warningStrategyMapper); //一级策略
        Map<String, ConditionDataDto> secondMap = getMapCondition(1, type.length > 0 ? alarmImplWarning : warningStrategyMapper); //二级策略
        Map<String, ConditionDataDto> map = new HashMap<>();
        List<OverRunLog> list = new ArrayList<>();
        Set<Integer> set = new HashSet<>();
        map.putAll(firstMap);
        map.putAll(secondMap);

        DatePojo datePojo = new DatePojo();
        getTime(time, datePojo, type.length > 0 ? 11 : 0);
        Map<String, ConditionDataDto> map2 = getMapCondition(2, type.length > 0 ? alarmImplWarning : warningStrategyMapper); //三级策略
        List<FormData> formDataList = getResultByCondition(map,map2, datePojo.getStartTime(), datePojo.getEndTime(),type.length>0?1:0,deptsIndex);
        Iterator<FormData> iterator = formDataList.iterator();

        while (iterator.hasNext()) {   //按部门区分
            FormData formData = iterator.next();
            Iterator<Map.Entry<Integer, Map<Date, FormData.resultPojo>>> mapIterator = formData.getMapresultPojo().entrySet().iterator();

            while (mapIterator.hasNext()) {
                Map.Entry<Integer, Map<Date, FormData.resultPojo>> mm = mapIterator.next();
                Iterator<Map.Entry<Date, FormData.resultPojo>> iterator1 = mm.getValue().entrySet().iterator();

                while (iterator1.hasNext()) {
                    OverRunLog overRunLog = new OverRunLog();
                    Map.Entry<Date, FormData.resultPojo> map1 = iterator1.next();
                    FormData.resultPojo resultPojo = map1.getValue();
                    overRunLog.setLineIndex(mm.getKey());
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                    overRunLog.setName(resultPojo.getName());
                    overRunLog.setOverRunDescribe(resultPojo.getDescription().toString());
                    overRunLog.setUpdateTime(map1.getKey());
                    overRunLog.setGdName(resultPojo.getGdName());
                    overRunLog.setSubName(resultPojo.getBdName());
                    overRunLog.setLineName(resultPojo.getLineName());
                    overRunLog.setOverRunDate(simpleDateFormat.format(map1.getKey()));
                    overRunLog.setOverRunTimes(resultPojo.getCount());
                    overRunLog.setFirstDes(resultPojo.getFirstDes().get(0));

                    if (type.length > 0) {
                        formData.getSetDate().add(map1.getKey());
                    }

                    if (!set.contains(mm.getKey())) {
                        list.add(overRunLog);
                        set.add(mm.getKey());
                    }
                }
            }

            if (type.length > 0 && formData.getSetDate().size() < 10) { //不是连续十天的数据清空数据
                list.clear();
            }
        }

        return list;
    }



    /**
     * 转换日期格式
     *
     * @param time
     * @return
     */
    private Date formatDate(Date time, String form) {
        try {
            String dateString = PubUtils.date2String(time, form);
            return PubUtils.string2Date(dateString, form);
        } catch (Exception e) {
            return null;
        }
    }

    private String getUserIndex(String deptsIndex) {
        List<String> list = formDataMapper.getUserIndexByDeptsIndex(deptsIndex);

        if (list != null && list.size() > 0) {
            return list.get(list.size() - 1);
        }

        return "";
    }

    public List<OverRunLog> getTechnicalDetail(String deptsIndex, Date time, int... type) {
//    	List<OverRunLog> result = new ArrayList<>();
        List<OverRunLog> allList = getListOverRunLog(getSonDepts(deptsIndex), time, type);
//    	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
//
//        List<OverRunLog> logList = formDataMapper.getExistLog(time, type.length > 0 ? 1 : 0);
//
//        for(OverRunLog all : allList){
//        	boolean flag = true;
//        	for (OverRunLog log : logList){
//        		if(all.getLineIndex().equals(log.getLineIndex()) &&
//        				simpleDateFormat.format(all.getUpdateTime()).equals(simpleDateFormat.format(log.getUpdateTime()))){
//        			flag = false;
//        		}
//        	}
//        	if(flag){
//        		result.add(all);
//        	}
//        }

        return allList;
    }

    public String saveOverRunLog(String deptsIndex, Date time, List<String> indexs, int... type) {
        List<OverRunLog> tmp = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Depts detp = deptsMapper.selectByPrimaryKey(deptsIndex);
        User user = TokenManager.getToken();

        FormData formData = new FormData();
        formData.setDeptsIndex(deptsIndex);
        String supIndex = UUID.randomUUID().toString();
        formData.setSupIndex(supIndex);
        formData.setCreateTime(new Date());
        String des = simpleDateFormat.format(time) + detp.getDeptsName();
        String linename = "";
        formData.setCreateUser(user.getUserIndex());

        tmp = this.getListOverRunLog(getSonDepts(deptsIndex), time, type);
        for (String index : indexs) {
            for (OverRunLog overRun : tmp) {
                if (overRun.getLineIndex().equals(Integer.valueOf(index))) {
                    formDataMapper.insertOverData(Integer.valueOf(index), supIndex, overRun.getOverRunDescribe(), time, overRun.getOverRunTimes(), overRun.getName());
                    linename = overRun.getLineName() + overRun.getFirstDes();
                }
            }
        }

        des = des + linename + "超标监督";
        formData.setSupName(des);
        formData.setEventDate(time);
        formDataMapper.insertSuperData(formData, type.length > 0 ? 1 : 0); //插入技术监督表

        return supIndex;
    }

    public void modOverRunLog(String supIndex,String deptsIndex, Date time, List<String> indexs, int... type) {
        List<OverRunLog> tmp = new ArrayList<>();

        formDataMapper.deleteBySupIndex(supIndex);
        tmp = this.getListOverRunLog(getSonDepts(deptsIndex), time, type);
        for (String index : indexs) {
            for (OverRunLog overRun : tmp) {
                if (overRun.getLineIndex().equals(Integer.valueOf(index))) {
                    formDataMapper.insertOverData(Integer.valueOf(index), supIndex, overRun.getOverRunDescribe(), time, overRun.getOverRunTimes(), overRun.getName());
                }
            }
        }
    }

    public void delTechnical(String supIndex){
    	formDataMapper.deleteBySupIndex(supIndex);
    	int falg = superviseMapper.deleteByPrimaryKey(supIndex);
    }

    private List<String> getSonDepts(String deptsIndex) {
        List<Depts> deptlist = new ArrayList<>();
        List<String> deptindexs = new ArrayList<>();

        deptlist = userUtil.getDeptsByNode(deptsIndex);

        if (deptlist.size() > 0) {
            for (Depts dep : deptlist) {
                deptindexs.add(dep.getDeptsIndex());
            }
        } else {
            deptindexs.add(deptsIndex);
        }

        return deptindexs;
    }

    public Supervise getTechnicalByID(String supIndex) {
        Supervise result = new Supervise();

        result = superviseMapper.selectByPrimaryKey(supIndex);
        Depts dept = deptsMapper.selectByPrimaryKey(result.getDepts());

//        List<OverRunLog> allLog = new ArrayList<>();
//        if(result.getType() == 0){
//            allLog = this.getListOverRunLog(getSonDepts(dept.getDeptsIndex()), result.getEventDate());
//        }else{
//            allLog = this.getListOverRunLog(getSonDepts(dept.getDeptsIndex()), result.getEventDate(),result.getType());
//        }
        List<OverRunLog> overrun = formDataMapper.getLogBySupIndex(supIndex);
        for(int i = 0;i < overrun.size(); i++){
        	overrun.get(i).setChoosen(true);
        }

        result.setDepts(dept.getDeptsIndex());
        result.setDeptName(dept.getDeptsName());
        result.setOverRunLog(overrun);

        return result;
    }

    public List<String> getOptions(Long lineIndex, Date time) {
        List<String> result = new ArrayList<>();
        LimitRate limitRate = new LimitRate();
        limitRate = limitRateMapper.selectLimitRate(lineIndex.intValue(), time);
        if (limitRate != null) {
            if (limitRate.getVoltageDevOvertime() > 0) {
                result.add("电压偏差");
            }
            if (limitRate.getUBalanceOverTime() > 0) {
                result.add("电压不平衡");
            }
            if (limitRate.getUAberranceOverTime() > 0) {
                result.add("电压总谐波畸变率");
            }
            if (limitRate.getFreqDevOverTime() > 0) {
                result.add("频率偏差");
            }
            if (limitRate.getFlickerOverTime() > 0) {
                result.add("长时电压闪变");
            }
            if (limitRate.getUHarm2OverTime() > 0) {
                result.add("2次谐波电压含有率");
            }
            if (limitRate.getUHarm3OverTime() > 0) {
                result.add("3次谐波电压含有率");
            }
            if (limitRate.getUHarm4OverTime() > 0) {
                result.add("4次谐波电压含有率");
            }
            if (limitRate.getUHarm5OverTime() > 0) {
                result.add("5次谐波电压含有率");
            }
            if (limitRate.getUHarm6OverTime() > 0) {
                result.add("6次谐波电压含有率");
            }
            if (limitRate.getUHarm7OverTime() > 0) {
                result.add("7次谐波电压含有率");
            }
            if (limitRate.getUHarm8OverTime() > 0) {
                result.add("8次谐波电压含有率");
            }
            if (limitRate.getUHarm9OverTime() > 0) {
                result.add("9次谐波电压含有率");
            }
            if (limitRate.getUHarm10OverTime() > 0) {
                result.add("10次谐波电压含有率");
            }
            if (limitRate.getUHarm11OverTime() > 0) {
                result.add("11次谐波电压含有率");
            }
            if (limitRate.getUHarm12OverTime() > 0) {
                result.add("12次谐波电压含有率");
            }
            if (limitRate.getUHarm13OverTime() > 0) {
                result.add("13次谐波电压含有率");
            }
            if (limitRate.getUHarm14OverTime() > 0) {
                result.add("14次谐波电压含有率");
            }
            if (limitRate.getUHarm15OverTime() > 0) {
                result.add("15次谐波电压含有率");
            }
            if (limitRate.getUHarm16OverTime() > 0) {
                result.add("16次谐波电压含有率");
            }
            if (limitRate.getUHarm17OverTime() > 0) {
                result.add("17次谐波电压含有率");
            }
            if (limitRate.getUHarm18OverTime() > 0) {
                result.add("18次谐波电压含有率");
            }
            if (limitRate.getUHarm19OverTime() > 0) {
                result.add("19次谐波电压含有率");
            }
            if (limitRate.getUHarm20OverTime() > 0) {
                result.add("20次谐波电压含有率");
            }
            if (limitRate.getUHarm21OverTime() > 0) {
                result.add("21次谐波电压含有率");
            }
            if (limitRate.getUHarm22OverTime() > 0) {
                result.add("22次谐波电压含有率");
            }
            if (limitRate.getUHarm23OverTime() > 0) {
                result.add("23次谐波电压含有率");
            }
            if (limitRate.getUHarm24OverTime() > 0) {
                result.add("24次谐波电压含有率");
            }
            if (limitRate.getUHarm25OverTime() > 0) {
                result.add("25次谐波电压含有率");
            }
            if (limitRate.getIHarm2OverTime() > 0) {
                result.add("2次谐波电流幅值");
            }
            if (limitRate.getIHarm3OverTime() > 0) {
                result.add("3次谐波电流幅值");
            }
            if (limitRate.getIHarm4OverTime() > 0) {
                result.add("4次谐波电流幅值");
            }
            if (limitRate.getIHarm5OverTime() > 0) {
                result.add("5次谐波电流幅值");
            }
            if (limitRate.getIHarm6OverTime() > 0) {
                result.add("6次谐波电流幅值");
            }
            if (limitRate.getIHarm7OverTime() > 0) {
                result.add("7次谐波电流幅值");
            }
            if (limitRate.getIHarm8OverTime() > 0) {
                result.add("8次谐波电流幅值");
            }
            if (limitRate.getIHarm9OverTime() > 0) {
                result.add("9次谐波电流幅值");
            }
            if (limitRate.getIHarm10OverTime() > 0) {
                result.add("10次谐波电流幅值");
            }
            if (limitRate.getIHarm11OverTime() > 0) {
                result.add("11次谐波电流幅值");
            }
            if (limitRate.getIHarm12OverTime() > 0) {
                result.add("12次谐波电流幅值");
            }
            if (limitRate.getIHarm13OverTime() > 0) {
                result.add("13次谐波电流幅值");
            }
            if (limitRate.getIHarm14OverTime() > 0) {
                result.add("14次谐波电流幅值");
            }
            if (limitRate.getIHarm15OverTime() > 0) {
                result.add("15次谐波电流幅值");
            }
            if (limitRate.getIHarm16OverTime() > 0) {
                result.add("16次谐波电流幅值");
            }
            if (limitRate.getIHarm17OverTime() > 0) {
                result.add("17次谐波电流幅值");
            }
            if (limitRate.getIHarm18OverTime() > 0) {
                result.add("18次谐波电流幅值");
            }
            if (limitRate.getIHarm19OverTime() > 0) {
                result.add("19次谐波电流幅值");
            }
            if (limitRate.getIHarm20OverTime() > 0) {
                result.add("20次谐波电流幅值");
            }
            if (limitRate.getIHarm21OverTime() > 0) {
                result.add("21次谐波电流幅值");
            }
            if (limitRate.getIHarm22OverTime() > 0) {
                result.add("22次谐波电流幅值");
            }
            if (limitRate.getIHarm23OverTime() > 0) {
                result.add("23次谐波电流幅值");
            }
            if (limitRate.getIHarm24OverTime() > 0) {
                result.add("24次谐波电流幅值");
            }
            if (limitRate.getIHarm25OverTime() > 0) {
                result.add("25次谐波电流幅值");
            }
        }
        return result;
    }

    //获取当前系统9300默认使用9000
    public String getSysType() {
        return appConfig.getSysTypeWt();
    }

    /*获取当前系统下的所有部门*/
    public List<FormData> getListDepts(String sysType) {
        return formDataMapper.getListDepts(getSysType());
    }


}
