package com.pqs9300.controller.strategy;

import com.njcn.enums.LogTypeEnum;
import com.njcn.mapper.configuration.OverLimitMapper;
import com.njcn.mapper.user.UserMapper;
import com.njcn.pojo.commons.DatePojo;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.device.*;
import com.njcn.pojo.configuration.DicData;
import com.njcn.pojo.configuration.HistoryResult;
import com.njcn.pojo.configuration.OverLimit;
import com.njcn.pojo.configuration.OverLimtResult;
import com.njcn.pojo.user.*;
import com.njcn.service.configuration.DeviceService;
import com.njcn.service.configuration.HistoryResultService;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.sso.pojo.user.User;
import com.njcn.utils.PubUtils;
import com.njcn.utils.redis.RedisCacheUtil;
import com.pqs9300.pojo.strategy.DicStrategyRVO;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.security.auth.login.AccountException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.regex.Pattern;


@Controller
@RequestMapping(value = "device")
public class DeviceController {
    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(DeviceController.class);

    @Resource
    private DeviceService getDeviceInfo;
    @Autowired
    HistoryResultService historyResultService;

    @Autowired
    UserLogDetailService userLog;
    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private OverLimitMapper overLimitMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 终端树
     *
     * @return
     */
    @RequestMapping(value = "getTree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getTree() {
        HttpResult result;
        User user = TokenManager.getToken();
        List<Tree> data;
        try {
            data = getDeviceInfo.getStrategyTree(user.getLoginName());
            result = PubUtils.assignmentResult(data, 200, "获取设备树信息成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 200, "获取设备树信息失败");
        }
        return result;
    }

    /**
     * @return com.njcn.pojo.configuration.HistoryResult
     * @Author denghuajun
     * @Description //TODO 获取历史数据
     * @Date 2018/9/26 10:13
     * @Param [request, startTime, endTime, lineIndex, type, number]
     **/
    @RequestMapping(value = "getHistoryResult", method = RequestMethod.POST)
    @ResponseBody
    public HistoryResult getHistoryResult(HttpServletRequest request, String startTime, String endTime, Long lineIndex, String type,
                                          String number, String obj) throws AccountException {
        int num = 0;
        HistoryResult result = new HistoryResult();
        JSONArray json = JSONArray.fromObject(obj); //使用net.sf.json.JSONObject对象来解析json
        List<List> listw = new ArrayList<List>();
        String k = json.getJSONObject(0).getString("condition");
        String o = String.valueOf(json.getJSONObject(0).getString("condition"));
        String startT = (String) json.getJSONObject(0).get("startTime");
        startTime = startT;                      //获取时间段的开始时间
        String endT = (String) json.getJSONObject(0).get("endTime");
        endTime = endT;
        String start = (String) json.getJSONObject(0).get("start");
        String end = (String) json.getJSONObject(0).get("end");
        String point = json.getJSONObject(0).getString("point");
        String[] pointid = null;
        try {
            int g = 0;
            pointid = point.split(",");
            g = pointid.length;
            for (int j = 0; j < pointid.length; j++) {
                lineIndex = Long.valueOf(pointid[j]);
                HistoryResult resultTemp = new HistoryResult();
                //datePojo=PubUtils.ChooseDate(startTime,endTime,"[-getHistoryData");
                if (Integer.parseInt(o) == 41 || Integer.parseInt(o) == 42) {
                    number = String.valueOf(json.getJSONObject(0).get("harmonic"));
                } else if (Integer.parseInt(o) == 43) {
                    number = String.valueOf(json.getJSONObject(0).get("inHarmonic"));
                }else {
                    number = String.valueOf(0);
                }
                switch (Integer.parseInt(o)) {
                    case 11:
                        type = "getXVrValue";                //相电压有效值
                        break;
                    case 12:
                        type = "getLVrValue";                //线电压有效值
                        break;
                    case 13:
                        type = "getDypc";                //电压偏差
                        break;
                    case 15:
                        type = "getSxbphd";                //三相电压不平衡度
                        break;
                    case 16:
                        type = "getBphdy";                //电压不平衡
                        break;
                    case 17:
                        type = "getDyzjbl";                //电压总谐波畸变率
                        break;
                    case 21:
                        type = "getDlyxz";                //电流有效值
                        break;
                    case 22:
                        type = "getDlzjbl";                //电流总谐波畸变率
                        break;
                    case 31:
                        type = "getPl";                //频率
                        break;
                    case 41:
                        if (number.equalsIgnoreCase("1")) {
                            type = "getJbhyl";
                        } else {
                            type = "getXbhyl";                //谐波电压含有率(N次谐波)
                        }
                        break;
                    case 42:
                        type = "getXbdlfz";                //谐波电流幅值
                        break;
                    case 51:
                        type = "getYggl";                //三相有功功率
                        break;
                    case 52:
                        type = "getWggl";                //三相无功功率
                        break;
                    case 53:
                        type = "getSzgl";                //三相视在功率
                        break;
                    case 54:
                        type = "getYgzgl";                //三相有功总功率
                        break;
                    case 55:
                        type = "getWgzgl";                //三相无功总功率
                        break;
                    case 56:
                        type = "getSzzgl";                //三相视在总功率
                        break;
                    case 61:
                        type = "getDssb";                //短时电压闪变
                        break;
                    case 62:
                        type = "getCssb";                //长时电压闪变
                        break;
                    case 63:
                        type = "getDybd";                //电压波动
                        break;
                    default:
                        break;
                }
                num += 1;

                //xuyang_add number增加正则判断，只能读取非0的正整数
                String pattern = "^\\+?[1-9][0-9]*$";
                if (Integer.parseInt(o) == 41 || Integer.parseInt(o) == 42 || Integer.parseInt(o) == 43) {
                    if (Pattern.matches(pattern, number)) {
                        resultTemp = historyResultService.getHistroyResult(startTime, endTime, lineIndex, start, end, type, number, num, g, Integer.parseInt(o),0,0);
                        if (num == 2) {
                            result.setData2(resultTemp.getData2());
                        } else if (num == 3) {
                            result.setData3(resultTemp.getData3());
                        } else if (num == 1) {
                            result.setData1(resultTemp.getData1());
                        }
                        result.setData4(resultTemp.getData4());
                    }
                } else {
                    resultTemp = historyResultService.getHistroyResult(startTime, endTime, lineIndex, start, end, type, number, num, g, Integer.parseInt(o),0,0);
                    if (num == 2) {
                        result.setData2(resultTemp.getData2());
                    } else if (num == 3) {
                        result.setData3(resultTemp.getData3());
                    } else if (num == 1) {
                        result.setData1(resultTemp.getData1());
                    }
                    result.setData4(resultTemp.getData4());
                }
            }
            result.setMsg(String.valueOf(num));
            result.setMsg1(String.valueOf(g));
            //userLog.getLog("查询稳态趋势对比", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            System.out.println(e.toString());
            userLog.getLog("查询稳态趋势对比", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            logger.error("获取历史数据异常，异常是" + e.toString());
        }
        return result;
    }

    @RequestMapping(value = "getUserAll", method = RequestMethod.POST)
    @ResponseBody
    public UserDetail getUserAll(HttpServletRequest request, String userIndex) {
        UserDetail result = new UserDetail();
        try {
            result = userMapper.getUserAll(userIndex);
        } catch (Exception e) {
            result = null;
        }

        return result;
    }

    //获取限值
    @RequestMapping(value = "getXz", method = RequestMethod.POST)
    @ResponseBody
    public OverLimtResult getXz(HttpServletRequest request, Long lineIndex, String number, String obj) {
        OverLimtResult result = new OverLimtResult();
        JSONArray json = JSONArray.fromObject(obj); //使用net.sf.json.JSONObject对象来解析json
        String point = (String) json.getJSONObject(0).get("point");
        String[] pointid = point.split(",");
        try {
            for (int j = 0; j < pointid.length; j++) {
                lineIndex = Long.valueOf(pointid[j]);
                Example example = new Example(OverLimit.class);
                example.createCriteria().andEqualTo("myIndex", lineIndex);
                List<OverLimit> overLimit = overLimitMapper.selectByExample(example);

                if (!overLimit.isEmpty()) {
                    for (int i = 0; i < overLimit.size(); i++) {
                        List<Float> list = new ArrayList<>();
                        list.add(overLimit.get(i).getFreqDev());//频率限值
                        list.add(overLimit.get(i).getUbalance());//三相电压不平衡度限值
                        list.add(overLimit.get(i).getFlicker());//闪变限值
                        list.add(overLimit.get(i).getUaberrance());//电压畸变限值
                        list.add(overLimit.get(i).getVoltageDev());//电压偏差限值

                        list.add(overLimit.get(i).getUharm_2());//2次谐波电压限值
                        list.add(overLimit.get(i).getUharm_3());//3次谐波电压限值
                        list.add(overLimit.get(i).getUharm_4());//4次谐波电压限值
                        list.add(overLimit.get(i).getUharm_5());//5次谐波电压限值
                        list.add(overLimit.get(i).getUharm_6());//6次谐波电压限值
                        list.add(overLimit.get(i).getUharm_7());//7次谐波电压限值
                        list.add(overLimit.get(i).getUharm_8());//8次谐波电压限值
                        list.add(overLimit.get(i).getUharm_9());//9次谐波电压限值
                        list.add(overLimit.get(i).getUharm_10());//10次谐波电压限值
                        list.add(overLimit.get(i).getUharm_11());//11次谐波电压限值
                        list.add(overLimit.get(i).getUharm_12());//12次谐波电压限值
                        list.add(overLimit.get(i).getUharm_13());//13次谐波电压限值
                        list.add(overLimit.get(i).getUharm_14());//14次谐波电压限值
                        list.add(overLimit.get(i).getUharm_15());//15次谐波电压限值
                        list.add(overLimit.get(i).getUharm_16());//16次谐波电压限值
                        list.add(overLimit.get(i).getUharm_17());//17次谐波电压限值
                        list.add(overLimit.get(i).getUharm_18());//18次谐波电压限值
                        list.add(overLimit.get(i).getUharm_19());//19次谐波电压限值
                        list.add(overLimit.get(i).getUharm_20());//20次谐波电压限值
                        list.add(overLimit.get(i).getUharm_21());//21次谐波电压限值
                        list.add(overLimit.get(i).getUharm_22());//22次谐波电压限值
                        list.add(overLimit.get(i).getUharm_23());//23次谐波电压限值
                        list.add(overLimit.get(i).getUharm_24());//24次谐波电压限值
                        list.add(overLimit.get(i).getUharm_25());//25次谐波电压限值

                        list.add(overLimit.get(i).getIharm_2());//2次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_3());//3次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_4());//4次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_5());//5次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_6());//6次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_7());//7次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_8());//8次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_9());//9次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_10());//10次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_11());//11次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_12());//12次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_13());//13次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_14());//14次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_15());//15次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_16());//16次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_17());//17次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_18());//18次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_19());//19次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_20());//20次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_21());//21次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_22());//22次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_23());//23次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_24());//24次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_25());//25次谐波幅值限值

                        result.getData().add(list);
                    }
                } else {
                    result.getData().add(null);
                }
            }
        } catch (Exception e) {
            logger.error("获取限值异常，异常是" + e.toString());
        }
        result.setMsg("200");
        return result;
    }

}
