package com.huimv.produce.warning.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dahuatech.hutool.http.Method;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.http.DefaultClient;
import com.dahuatech.icc.oauth.http.IClient;
import com.dahuatech.icc.oauth.model.v202010.GeneralRequest;
import com.dahuatech.icc.oauth.model.v202010.GeneralResponse;
import com.huimv.common.utils.Result;
import com.huimv.common.utils.ResultCode;
import com.huimv.common.utils.StringUtilsWork;
import com.huimv.produce.produce.utils.DateUtil;
import com.huimv.produce.warning.dao.entity.BaseWarningInfoEntity;
import com.huimv.produce.warning.dao.repo.BaseWarningInfoRepo;
import com.huimv.produce.warning.service.IAlarmService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.biosafety.uface.controller
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2020-12-25
 **/
@Service
@Slf4j
public class AlarmServiceImpl implements IAlarmService {
    @Autowired
    private com.huimv.produce.warning.dao.repo.FarmDeviceRepo deviceRepo;
    @Autowired
    private com.huimv.produce.utils.MathUtil mathUtil;
    @Autowired
    private BaseWarningInfoRepo warningInfoRepo;
    //    @Autowired
//    private BaseWarningInfoRepo warningInfoRepo;
    @Autowired
    private DateUtil dateUtil;

    @Override
    public Result getMainPageAlarm(Integer farmId) throws ParseException, ClientException {
        //今日报警
        //设备故障率
        //今日提醒（周界）
        //三级报警数量

        JSONObject outJo = new JSONObject();
        Integer bit = 1;
        //获取今天警报次数
        outJo.put("todayAlarm", getTodayAlarmTimes(farmId));

        //获取设备故障率
        outJo.put("failureRate", getDeviceFailureRate(farmId, bit));

        //事件提醒
        outJo.put("todayEventTotal",getEventTotal(farmId));

        //获取三级警报数量
        outJo.put("warningQuantity", getWarningTimes(farmId));
        return new Result(ResultCode.SUCCESS, outJo);
    }

    //事件提醒
    private String getEventTotal(Integer farmId) throws ParseException, ClientException {
        if(farmId == 1) {
            //获取人员违规
            String startTime = dateUtil.getTodayDateText() + " 00:00:00";
            log.info("今日事件提醒.开始时间>>" + startTime);
            String endTime = dateUtil.getTodayDateText() + " 23:59:59";
            log.info("今日事件提醒.结束时间>>" + endTime);

            //人员违规事件数量
            String personAlarmTotal = SendMassageGetPagePersonAlarm(startTime, endTime);
            log.info("人员违规事件数量>>" + personAlarmTotal);
            Integer rywgQuantity = 0;
            if (personAlarmTotal != null) {
                rywgQuantity = Integer.parseInt(personAlarmTotal);
            }
            //车辆闸机事件数量
            String carEventTimes = SendMassageGetPage(startTime, endTime);
            log.info("车辆闸机事件数量>>" + carEventTimes);
            Integer carEventTimesInt = 0;
            if (carEventTimes != null) {
                carEventTimesInt = Integer.parseInt(carEventTimes);
            }
            //周界检测事件数量
            String borderEventTimes = getBorderEvent(startTime, endTime);
            log.info("周界检测事件数量>>" + borderEventTimes);
            Integer borderEventTimesInt = 0;
            if (borderEventTimes != null) {
                borderEventTimesInt = Integer.parseInt(borderEventTimes);
            }
            //所有事件累计
            Integer allEventInt = rywgQuantity + carEventTimesInt + borderEventTimesInt;
            log.info("今日事件总数量>>" + allEventInt);
            return allEventInt + "次";
        }
        return "0次";
    }

    //周界检测事件数量
    private String getBorderEvent(String startTime,String endTime) throws ClientException {
        //合并通道
        final String[] AllChannle =  {"1003442$1$0$0","1002871$1$0$0","1002872$1$0$0","1002873$1$0$0","1002874$1$0$0","1002875$1$0$0","1002876$1$0$0","1002877$1$0$0","1002878$1$0$0","1002879$1$0$0","1002880$1$0$0","1002881$1$0$0","1002882$1$0$0","1002883$1$0$0","1002884$1$0$0","1002885$1$0$0","1002886$1$0$0","1002887$1$0$0","1002888$1$0$0","1002889$1$0$0","1002890$1$0$0","1002891$1$0$0","1002892$1$0$0","1002893$1$0$0", "1002894$1$0$0","1002895$1$0$0","1002896$1$0$0","1002897$1$0$0","1002898$1$0$0","1002899$1$0$0","1002900$1$0$0","1002901$1$0$0","1002902$1$0$0","1002903$1$0$0","1002904$1$0$0","1002905$1$0$0","1002906$1$0$0","1002907$1$0$0","1002908$1$0$0","1002909$1$0$0","1002910$1$0$0","1002911$1$0$0","1002912$1$0$0","1002913$1$0$0","1002939$1$0$0","1002939$1$0$1","1002939$1$0$2","1002939$1$0$3","1002939$1$0$4","1002939$1$0$5","1002939$1$0$6","1002939$1$0$7","1002939$1$0$8","1002939$1$0$9","1002940$1$0$0","1002940$1$0$1","1002940$1$0$2","1002940$1$0$3","1002940$1$0$4","1002940$1$0$5","1002940$1$0$6","1002940$1$0$7","1002939$1$0$10","1002939$1$0$11","1002939$1$0$12","1002939$1$0$13","1002939$1$0$14","1002939$1$0$15"};
        Map<String, Object> params = new HashMap<>();
        params.put("alarmStartDateString",startTime);
        params.put("alarmEndDateString",endTime);
        params.put("alarmType",303);
        params.put("dbType",0);
        params.put("deviceCategory",1);
        String[]  nodeCodeList= AllChannle;
        params.put("nodeCodeList",nodeCodeList);
        String URL = "/evo-apigw/evo-event/1.0.0/alarm-record/count-num";  //获取事件URL    post请求
        IClient iClient = new DefaultClient();
        String NewUrl = URL ;
        //这种已经在配置文件里面安排了账号ip以及密码
        GeneralRequest generalRequest = new GeneralRequest(NewUrl, Method.POST);
        generalRequest.header("Content-Type", " application/json");
        //里面是
        generalRequest.body(JSON.toJSONString(params));
        //发起请求处理应答
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        JSONObject jsonObject = JSONObject.parseObject(generalResponse.getResult());
        Object data = jsonObject.get("data");
        JSONObject jsonObject1 = JSONObject.parseObject(data.toString());
        return jsonObject1.get("value").toString();
    }

    /**
     *  //查车辆通行数量的接口**不分进出
     * @param begin  开始时间
     * @param end  结束时间
     * @return
     * @throws ClientException
     */
    public String SendMassageGetPage(String begin, String end  ) throws ClientException {
        String param = "queryTimeBegin=" + begin + "&queryTimeEnd=" + end;
        String Url = "/evo-apigw/ipms/carcapture/find/conditions?";
        IClient iClient = new DefaultClient();
        String newUrl = Url + param;
        GeneralRequest generalRequest = new GeneralRequest(newUrl, Method.GET);
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        JSONObject jsonObject = JSON.parseObject(generalResponse.getResult());
        Object data = jsonObject.get("data");
        JSONObject   bject = JSON.parseObject(data.toString());
        Object data1 = bject.get("totalRows"); //打印 2390
        return data1.toString();

    }

    //获取三级警报数量
    private String getWarningTimes(Integer farmId) {
//        return "7次";
        //读取三级警报数量
        Integer classInt = 3;
        List<Object[]> objList = warningInfoRepo.countThirdClassAlarm(farmId, classInt);
        Object[] totalObj = (Object[]) objList.get(0);
        return totalObj[0].toString() + "次";
    }

    //获取今天警报次数
    private String getTodayAlarmTimes(Integer farmId) throws ParseException, ClientException {
        String todayText = dateUtil.getTodayDateText();
        //查询今天所有报警记录
        List<BaseWarningInfoEntity> warningInfoEntityList = warningInfoRepo.findTodayAllAlarm(farmId, todayText);
        if (warningInfoEntityList.size() > 0) {
            JSONArray outJa = new JSONArray();
            //生态监测
            int stjcQuantity = _countRateQuantity("7,8,9,10", warningInfoEntityList);
            //环境监测
            int hjjcQuantity = _countRateQuantity("15,16,17,18", warningInfoEntityList);
            //人员违规
            String startTime = dateUtil.getTodayDateText() + " 00:00:00";
            log.info("开始时间>>" + startTime);
            String endTime = dateUtil.getTodayDateText() + " 23:59:59";
            log.info("结束时间>>" + endTime);
            //获取人员违规
            int rywgQuantity = 0;
            if(farmId == 1) {
                String personAlarmTotal = SendMassageGetPagePersonAlarm(startTime, endTime);
                if (personAlarmTotal != null) {
                    rywgQuantity = Integer.parseInt(personAlarmTotal);
                }
            }
            //报警总量
            int total = stjcQuantity + hjjcQuantity + rywgQuantity;
            return total + "次";
        }
        return 0 + "次";
    }

    //计算占比数量
    public Integer _countRateQuantity(String alarmType, List<BaseWarningInfoEntity> warningInfoEntityList) {
        if (alarmType == null || alarmType.trim().length() == 0) {
            log.error("警报类型alarmType不能为空或null.");
        }
        String[] alarmArray = alarmType.split(",");
        int count = 0;
        for (int a = 0; a < warningInfoEntityList.size(); a++) {
            BaseWarningInfoEntity warningInfoEntity = warningInfoEntityList.get(a);
            for (int b = 0; b < alarmArray.length; b++) {
                if (warningInfoEntity.getAlarmType() == Integer.parseInt(alarmArray[b])) {
                    count++;
                    break;
                }
            }
        }
        return count;
    }

    //调用大华接口返回人脸门禁的数量
    public String SendMassageGetPagePersonAlarm(String begin, String end) throws ClientException {
        Map<String, Object> params = new HashMap<>();
        params.put("startSwingTime", begin);
        params.put("endSwingTime", end);
        params.put("containDomain", "1");
        params.put("openResult", 0);
        String URL = "/evo-apigw/evo-accesscontrol/1.0.0/card/accessControl/swingCardRecord/bycondition/combinedCount?systime=";  //获取事件URL    post请求
        IClient iClient = new DefaultClient();
        String timestamp = String.valueOf((new Date()).getTime());
        Long aLong = Long.valueOf(timestamp);
        String NewUrl = URL + aLong;
        System.out.println("开始执行");
        //这种已经在配置文件里面安排了账号ip以及密码
        GeneralRequest generalRequest = new GeneralRequest(NewUrl, Method.POST);
        System.out.println(NewUrl);
        generalRequest.header("Content-Type", " application/json");
        System.out.println(JSON.toJSONString(params));
        //里面是
        generalRequest.body(JSON.toJSONString(params));
        //发起请求处理应答
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        System.out.println("执行结束");
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(generalResponse.getResult());
        Object data = jsonObject.get("data");
        return data.toString();
    }

    //获取设备故障率
    private String getDeviceFailureRate(Integer farmId, Integer bit) {
//        return "16%";
        if (bit == null || bit == 0) {
            bit = 2;
        }
        //获取设备总数
        List<Object[]> objList = deviceRepo.findDeviceTotal(farmId);
        Object[] totalObj = (Object[]) objList.get(0);
        int total = Integer.parseInt(totalObj[0].toString());
        if(total == 0){
            return "0%";
        }
        System.out.println("total>>"+total);
        //获取有故障设备数
        Integer failureState = 2;
        List<Object[]> failureList = deviceRepo.findFailureDeviceTotal(farmId, failureState);
        Object[] failureObj = (Object[]) failureList.get(0);
        int num = Integer.parseInt(failureObj[0].toString());
        System.out.println("num>>"+num);
        String rate = mathUtil.countRate(num, total, bit);
        return rate + "%";
    }
}
