package com.huimv.environ.env.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.environ.env.dao.entity.BaseWarningInfoEntity;
import com.huimv.environ.env.dao.entity.BaseWarningInfoEntity;
import com.huimv.environ.env.dao.repo.BaseWarningInfoRepo;
import com.huimv.environ.env.service.IAlarm;
import com.huimv.environ.env.utils.Const;
import com.huimv.environ.env.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.*;
import java.text.ParseException;
import java.util.*;

/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.biosafety.uface.controller
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2020-12-25
 **/
@Service
@Slf4j
public class AlarmImpl implements IAlarm {
    @Autowired
    private BaseWarningInfoRepo warningInfoRepo;
    @Autowired
    private DateUtil dateUtil;

    @Override
    public Result getAlarm(Integer farmId, Integer alarmType, String alarmDateText, Integer pageNo, Integer pageSize) throws ParseException {
        //转换为日期才能比较
        Date alarmDate = dateUtil.formatDate(alarmDateText);
        Specification<BaseWarningInfoEntity> sf = (Specification<BaseWarningInfoEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            if (null != farmId) {
                predList.add(criteriaBuilder.equal(root.get("farmId").as(Integer.class), farmId));
            }
            if (null != alarmType) {
                predList.add(criteriaBuilder.equal(root.get("alarmType").as(Integer.class), alarmType));
            }
            if (null != alarmDate) {
                predList.add(criteriaBuilder.equal(root.get("warningTime").as(Date.class), alarmDate));
            }
//            if (null != returnState) {
//                predList.add(criteriaBuilder.equal(root.get("returnState").as(Integer.class), returnState));
//            }
//            if (null != deliverState) {
//                predList.add(criteriaBuilder.equal(root.get("deliverState").as(Integer.class), deliverState));
//            }
            //
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        Pageable pageable = PageRequest.of( pageNo - 1, pageSize);
//        return new Result(ResultCode.SUCCESS,applyRepo.listApply(pageable,applyId));
        Page<BaseWarningInfoEntity>  warningInfoEntityPage = warningInfoRepo.findAll(sf, pageable);
        //格式化日期
//        List<BaseWarningInfoEntity> warningInfoEntityList = warningInfoEntityPage.getContent();
//        for(BaseWarningInfoEntity warningInfoEntity:warningInfoEntityList){
//            warningInfoEntity.setWarningTime(new Timestamp(dateUtil.formatDate(dateUtil.fromLongToDate(warningInfoEntity.getWarningTime().getTime(),"yyyy-MM-dd")).getTime()));
//            warningInfoEntity.setUploadTime(new Timestamp(dateUtil.formatDate(dateUtil.fromLongToDate(warningInfoEntity.getUploadTime().getTime(),"yyyy-MM-dd")).getTime()));
//        }
        return new Result(ResultCode.SUCCESS, warningInfoEntityPage);
    }

    @Override
    public Result getAlarm(Integer farmId, Integer alarmType, String alarmDateText,Integer quantity) throws ParseException {
        Specification<BaseWarningInfoEntity> sf = (Specification<BaseWarningInfoEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            if (null != farmId) {
                predList.add(criteriaBuilder.equal(root.get("farmId").as(Integer.class), farmId));
            }
            if (null != alarmType) {
                predList.add(criteriaBuilder.equal(root.get("alarmType").as(Integer.class), alarmType));
            }
            if (null != alarmDateText) {
                //转换为日期才能比较
                Date alarmDate = null;
                try {
                    alarmDate = dateUtil.formatDate(alarmDateText);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                predList.add(criteriaBuilder.equal(root.get("warningTime").as(Date.class), alarmDate));
            }
//            if (null != returnState) {
//                predList.add(criteriaBuilder.equal(root.get("returnState").as(Integer.class), returnState));
//            }
//            if (null != deliverState) {
//                predList.add(criteriaBuilder.equal(root.get("deliverState").as(Integer.class), deliverState));
//            }
            //
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
//        return new Result(ResultCode.SUCCESS,applyRepo.listApply(pageable,applyId));
        List<BaseWarningInfoEntity>  warningInfoEntityList = warningInfoRepo.findAll(sf);
        System.out.println("warningInfoEntityList.size="+warningInfoEntityList.size());
        //格式化日期
//        List<BaseWarningInfoEntity> warningInfoEntityList = warningInfoEntityPage.getContent();
//        for(BaseWarningInfoEntity warningInfoEntity:warningInfoEntityList){
//            warningInfoEntity.setWarningTime(new Timestamp(dateUtil.formatDate(dateUtil.fromLongToDate(warningInfoEntity.getWarningTime().getTime(),"yyyy-MM-dd")).getTime()));
//            warningInfoEntity.setUploadTime(new Timestamp(dateUtil.formatDate(dateUtil.fromLongToDate(warningInfoEntity.getUploadTime().getTime(),"yyyy-MM-dd")).getTime()));
//        }
        return new Result(ResultCode.SUCCESS, warningInfoEntityList);
    }

    /**
     * @Method      : getAlarm
     * @Description : 查询今天的警报
     * @Params      : [farmId, quantity]
     * @Return      : com.huimv.common.utils.Result
     * 
     * @Author      : ZhuoNing
     * @Date        : 2021/12/5       
     * @Time        : 14:54
     */
    @Override
    public Result getAlarm(Integer farmId, Integer quantity) throws ParseException {
        String today = dateUtil.getTodayDateText();
        //
        List<Object[]>  warningInfoEntityList = warningInfoRepo.findTodayAlarm(farmId,today,quantity);
        if(warningInfoEntityList.size()>0){
            JSONArray alarmJa = new JSONArray();
            for(int a=0;a<warningInfoEntityList.size();a++){
                Object[] alarmObj = (Object[]) warningInfoEntityList.get(a);
                JSONObject alarmJo = new JSONObject();
                alarmJa.add(alarmJo);
                alarmJo.put("levelName",alarmObj[0]);
                alarmJo.put("warningTime",alarmObj[1]);
                alarmJo.put("msg",alarmObj[2]);
            }
            return new Result(ResultCode.SUCCESS,alarmJa);
        }else{
            return new Result(Const.ERROR_CODE_NOTEXIST,Const.ERROR_MSG_NOTEXIST,false);
        }
    }

    /**
     * @Method      : getOneWeekAlarm
     * @Description : 报警级别分布
     * @Params      : [farmId]
     * @Return      : com.huimv.common.utils.Result
     * 
     * @Author      : ZhuoNing
     * @Date        : 2021/12/5       
     * @Time        : 17:02
     */
    @Override
    public Result getOneWeekAlarm(Integer farmId) throws ParseException {
        //倒序查询最近7天警报数据
        String startDate = dateUtil.getPastDate(6);
        String endDate = dateUtil.getTodayDateText();
        //
        List<BaseWarningInfoEntity> warningInfoEntityList = warningInfoRepo.findLastSevenDaysAlarm(farmId,startDate,endDate);
        JSONObject outJo = new JSONObject();
        outJo.put("one",_countAlarmTotal("一级",warningInfoEntityList));
        outJo.put("two",_countAlarmTotal("二级",warningInfoEntityList));
        outJo.put("three",_countAlarmTotal("三级",warningInfoEntityList));
        return new Result(ResultCode.SUCCESS,outJo);
    }

    //计算警报数量
    public Integer _countAlarmTotal(String typeName,List<BaseWarningInfoEntity> warningInfoEntityList){
        int count = 0;
        for(int a=0;a<warningInfoEntityList.size();a++){
            BaseWarningInfoEntity warningInfoEntity = warningInfoEntityList.get(a);
            if(warningInfoEntity.getLevelName().indexOf(typeName) != -1){
                count++;
            }
        }
        return count;
    }

    /**
     * @Method      : getAlarmRate
     * @Description : 计算今日报警占比数量
     * @Params      : [farmId]
     * @Return      : com.huimv.common.utils.Result
     * 
     * @Author      : ZhuoNing
     * @Date        : 2021/12/5       
     * @Time        : 18:29
     */
    @Override
    public Result getAlarmRate(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";
            System.out.println("开始时间>>"+startTime);
            String endTime = dateUtil.getTodayDateText()+" 23:59:59";
            System.out.println("结束时间>>"+endTime);
            //获取人员违规
            String personAlarmTotal = SendMassageGetPagePersonAlarm(startTime,endTime);
            int rywgQuantity = 0;
            if(personAlarmTotal != null){
                rywgQuantity = Integer.parseInt(personAlarmTotal);
            }
            //报警总量
//            int total = stjcQuantity + hjjcQuantity + rywgQuantity;
            //
            JSONObject dataJo1 = new JSONObject();
            outJa.add(dataJo1);
            dataJo1.put("name","生态监测");
            //演示
            dataJo1.put("value",stjcQuantity);
//            dataJo1.put("value",16);
            //
            JSONObject dataJo2 = new JSONObject();
            outJa.add(dataJo2);
            dataJo2.put("name","环境监测");
            dataJo2.put("value",hjjcQuantity);
//            dataJo2.put("value",0);
            //
            JSONObject dataJo3 = new JSONObject();
            outJa.add(dataJo3);
            dataJo3.put("name","人员违规");
            dataJo3.put("value",rywgQuantity);
//            dataJo3.put("value",0);
//            //
//            JSONObject dataJo4 = new JSONObject();
//            outJa.add(dataJo4);
//            dataJo4.put("name","报警总量");
//            dataJo4.put("value",total);
            return new Result(ResultCode.SUCCESS,outJa);
        }else{
            return new Result(Const.ERROR_CODE_NOTEXIST,Const.ERROR_MSG_NOTEXIST,false);
        }
    }

    //调用大华接口返回人脸门禁的数量
    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();
    }

    //计算占比数量
    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;
    }

}
