package com.huimv.video.dhicc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.StringUtilsWork;
import com.huimv.video.dhicc.icc.CommonConstant;
import com.huimv.video.dhicc.result.R;
import com.huimv.video.dhicc.service.IClientAllEventService;
import com.huimv.video.dhicc.util.GetResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
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 ClientAllEventServiceImpl implements IClientAllEventService {

    @Override
    public R getEventBySort(Integer farmId, Integer sort, String startDateText, String endDateText, Integer pageNum, Integer pageSize, HttpServletRequest request) throws ClientException {
        Map paramsMap = new HashMap();
        paramsMap.put("farmId", farmId);
        paramsMap.put("pageNum", pageNum);
        paramsMap.put("pageSize", pageSize);
        //
        switch (sort) {
            case 1:
                //大门事件
                paramsMap.put("alarmStartDateString", startDateText);
                paramsMap.put("alarmEndDateString", endDateText);
                log.info("大门事件输入参数>>" + paramsMap.toString());
                return getGateEvent(paramsMap);
            case 2:
                //洗消事件
                paramsMap.put("alarmStartDateString", startDateText);
                paramsMap.put("alarmEndDateString", endDateText);
                log.info("洗消事件输入参数>>" + paramsMap.toString());
                return getWashEvent(paramsMap);
            case 3:
                //死猪通道事件
                paramsMap.put("alarmStartDateString", startDateText);
                paramsMap.put("alarmEndDateString", endDateText);
                log.info("死猪通道事件输入参数>>" + paramsMap.toString());
                return getDeadPigChannel(paramsMap);
            case 4:
                //熏蒸事件
                paramsMap.put("alarmStartDateString", startDateText);
                paramsMap.put("alarmEndDateString", endDateText);
                log.info("熏蒸事件输入参数>>" + paramsMap.toString());
                return getFumigateChannel(paramsMap);
            case 5:
                //卖猪事件
                paramsMap.put("alarmStartDateString", startDateText);
                paramsMap.put("alarmEndDateString", endDateText);
                log.info("卖猪事件输入参数>>" + paramsMap.toString());
                return getSellPigsChannel(paramsMap);
            case 6:
                //人员门禁事件
//                paramsMap.put("startSwingTime",startDateText);
//                paramsMap.put("endSwingTime",endDateText);
//                paramsMap.put("openType",61);
                log.info("人员门禁事件输入参数>>" + paramsMap.toString());
                return getEntranceGuard(paramsMap);
            default:
                //车辆闸机事件
                log.info("车辆闸机事件输入参数>>" + paramsMap.toString());
                return getCarAutoGate(request, paramsMap);
        }
    }

    //大门事件
    private R getGateEvent(Map<String, Object> paramsMap) throws ClientException {
        //绑定大门通道
        String[] doorChannel = CommonConstant.DoorChannle;
        return R.ok("请求成功").put("data", getEventList(paramsMap, doorChannel)).put("total", CountTimes(paramsMap, doorChannel)).put("isVideo", true);
    }

    //洗消事件
    private R getWashEvent(Map<String, Object> paramsMap) throws ClientException {
        //绑定大门通道
        String[] washChannel = CommonConstant.XixiaoChannle;
        return R.ok("请求成功").put("data", getEventList(paramsMap, washChannel)).put("total", CountTimes(paramsMap, washChannel)).put("isVideo", true);
    }

    //死猪事件
    private R getDeadPigChannel(Map<String, Object> paramsMap) throws ClientException {
        String[] deadPigChannel = CommonConstant.SIZhuChannle;
        return R.ok("请求成功").put("data", getEventList(paramsMap, deadPigChannel)).put("total", CountTimes(paramsMap, deadPigChannel)).put("isVideo", true);
    }

    //熏蒸事件
    private R getFumigateChannel(Map paramsMap) throws ClientException {
        //绑定熏蒸通道
        String[] fumigateChannel = CommonConstant.XunZhengChannle;
        return R.ok("请求成功").put("data", getEventList(paramsMap, fumigateChannel)).put("total", CountTimes(paramsMap, fumigateChannel)).put("isVideo", true);
    }

    //卖猪事件
    private R getSellPigsChannel(Map paramsMap) throws ClientException {
        //卖猪通道
        String[] sellPigsChannel = CommonConstant.MaiZhuChannle;
        return R.ok("请求成功").put("data", getEventList(paramsMap, sellPigsChannel)).put("total", CountTimes(paramsMap, sellPigsChannel)).put("isVideo", true);
    }

    //人员门禁事件
    private R getEntranceGuard(Map<String, Object> paramsMap) throws ClientException {
//        String total = SendMassageGetPagePersonAlarm(paramsMap.get("alarmStartDateString").toString(),paramsMap.get("alarmEndDateString").toString());
//        if(total == null){
//            total = "0";
//        }
        //
//        return R.ok("请求成功").put("data", getAccidentRecord(paramsMap)).put("total", Integer.parseInt(total)).put("isVideo",false);
//        getAccidentRecord(paramsMap);


        return getAccidentRecord(paramsMap).put("isVideo", false);
    }

    //解析总页码
    private Integer parseTotal(String totalText) {
        totalText = totalText.substring(totalText.indexOf("data"), totalText.length());
        totalText = totalText.substring(totalText.indexOf(":") + 1, totalText.indexOf("}"));
        return Integer.parseInt(totalText);
    }

    //车辆闸机事件
    private R getCarAutoGate(HttpServletRequest request, Map<String, Object> paramsMap) throws ClientException {
        Integer farmId = (int) paramsMap.get("farmId");
        GeneralResponse grObj = getCarRecord(request, farmId);
        com.alibaba.fastjson.JSONObject grJo = JSON.parseObject(com.alibaba.fastjson.JSONObject.toJSONString(grObj));
        com.alibaba.fastjson.JSONObject resultJo = grJo.getJSONObject("result");
        com.alibaba.fastjson.JSONObject dataJo = resultJo.getJSONObject("data");
        String totalRowsText = dataJo.getString("totalRows");
        resultJo.put("total", Integer.parseInt(totalRowsText));
        return R.ok("请求成功").put("data", grObj).put("total", Integer.parseInt(totalRowsText)).put("isVideo", false);
    }

    private R getCarAutoGate_old1(HttpServletRequest request, Map<String, Object> paramsMap) throws ClientException {
        Integer farmId = (int) paramsMap.get("farmId");
        JSONObject carJo = JSONObject.fromObject(getCarRecord(request, farmId));
        String resultText = carJo.getString("result");
        String dataText = JSON.parseObject(resultText).getString("data");
        String totalRowsText = JSON.parseObject(dataText).getString("totalRows");
        //
        return R.ok("请求成功").put("data", resultText).put("total", Integer.parseInt(totalRowsText)).put("isVideo", false);
    }

    //查询车辆通行记录 by Yangdi
    public GeneralResponse getCarRecord(HttpServletRequest request, @RequestParam(name = "farmId") Integer farmId) throws ClientException {
        if (farmId != 1) {
            //返回为空数据
            return new GeneralResponse();
        }
        System.out.println(request.getRequestURL());
        System.out.println(request.getQueryString());
        String queryString = request.getQueryString();
        String URL = "/evo-apigw/ipms/carcapture/find/conditions?";  //获取事件URL    post请求
        IClient iClient = new DefaultClient();
        System.out.println("开始执行");
        String newUrl = URL + queryString;
        System.out.println(newUrl);
        //这种已经在配置文件里面安排了账号ip以及密码    现在变了
        GeneralRequest generalRequest = new GeneralRequest(newUrl, Method.GET);
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        System.out.println("执行结束");
        return generalResponse;
    }

    //返回所有的事件 的集合  包括死猪和洗消和大门 --分页参数 by Yangdi
    public GeneralResponse getEventList(Map<String, Object> params1, String[] nodeCodeListIn) throws ClientException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        Date date = new Date();
        c.setTime(date);
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date A = c.getTime();
        String formatA = format.format(A);
        c.set(Calendar.HOUR, +24);
        Date d = c.getTime();
        String formatD = format.format(d);
        Map<String, Object> params = new HashMap<>();
        params.put("alarmStartDateString", formatA);
        params.put("alarmEndDateString", formatD);
        if (StringUtilsWork.isNotEmpty((String) params1.get("alarmStartDateString"))) {
            params.put("alarmStartDateString", (String) params1.get("alarmStartDateString"));
            params.put("alarmEndDateString", (String) params1.get("alarmEndDateString"));
        }
        params.put("pageNum", (Integer) params1.get("pageNum"));
        params.put("pageSize", (Integer) params1.get("pageSize"));
        params.put("alarmType", 303);
        params.put("dbType", 0);
        params.put("deviceCategory", 1);
//        String[] nodeCodeList = CommonConstant.AllChannle;
        params.put("nodeCodeList", nodeCodeListIn);
        // String URL = "/evo-apigw/evo-event/1.2.0/alarm-record/page"; //获取事件URL    post请求
        String URL = "/evo-apigw/evo-event/1.2.0/alarm-record/page";  //获取事件URL    post请求
        IClient iClient = new DefaultClient();
        String NewUrl = URL;
        //这种已经在配置文件里面安排了账号ip以及密码
        GeneralRequest generalRequest = new GeneralRequest(NewUrl, Method.POST);
        System.out.println(NewUrl);
        generalRequest.header("Content-Type", " application/json");
        generalRequest.body(JSON.toJSONString(params));
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        return generalResponse;
    }

    //计算次数 by Yangdi
    public String CountTimes(Map<String, Object> params1, String[] nodeCodeListIn) throws ClientException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        Date date = new Date();
        c.setTime(date);
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date A = c.getTime();
        String formatA = format.format(A);
        c.set(Calendar.HOUR, +24);
        Date d = c.getTime();
        String formatD = format.format(d);
        Map<String, Object> params = new HashMap<>();
        params.put("alarmStartDateString", formatA);
        params.put("alarmEndDateString", formatD);
        if (StringUtilsWork.isNotEmpty((String) params1.get("alarmStartDateString"))) {
            params.put("alarmStartDateString", (String) params1.get("alarmStartDateString"));
            params.put("alarmEndDateString", (String) params1.get("alarmEndDateString"));
        }
        params.put("alarmType", 303);
        params.put("dbType", 0);
        params.put("deviceCategory", 1);
//        String[] nodeCodeList = CommonConstant.AllChannle;
        params.put("nodeCodeList", nodeCodeListIn);
        String URL = "/evo-apigw/evo-event/1.0.0/alarm-record/count-num";  //获取事件URL    post请求
        IClient iClient = new DefaultClient();
        String NewUrl = URL;
        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("执行结束");
        JSONObject jsonObject = JSONObject.fromObject(generalResponse.getResult());
        Object data = jsonObject.get("data");
        JSONObject jsonObject1 = JSONObject.fromObject(data);
        System.out.println(jsonObject1);
        return jsonObject1.get("value").toString();
    }

    //刷脸失败记录 by Yangdi
    public R getAccidentRecord(Map<String, Object> params1) throws ClientException {
        System.out.println("## params1>>" + params1);
        Integer farmId = (int) params1.get("farmId");
        if (farmId != 1) {
            //返回为空数据
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        Date date = new Date();
        c.setTime(date);
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date A = c.getTime();
        String formatA = format.format(A);
        c.set(Calendar.HOUR, +24);
        Date d = c.getTime();
        String formatD = format.format(d);
        if (!StringUtilsWork.isNotEmpty((String) params1.get("alarmStartDateString"))) {
            params1.put("alarmStartDateString", formatA);
            params1.put("alarmEndDateString", formatD);
        }
        params1.put("containDomain", "1");
        params1.put("openType", "61");
//        params1.put("openResult", 1); //刷脸失败
        String URL = "/evo-apigw/evo-accesscontrol/1.0.0/card/accessControl/swingCardRecord/bycondition/combined?";
        IClient iClient = new DefaultClient();
        GeneralRequest generalRequest = new GeneralRequest(URL + Long.valueOf(String.valueOf((new Date()).getTime())), Method.POST);
        generalRequest.header("Content-Type", " application/json");
        generalRequest.body(JSON.toJSONString(params1));
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        JSONObject jsonObject = JSONObject.fromObject(generalResponse.getResult());
        GetResponse getResponse = new GetResponse();

        return R.ok("请求成功").put("data", generalResponse).put("total", getResponse.SendMassageGetPagePersonAlarm((String) params1.get("startSwingTime"), (String) params1.get("endSwingTime")));
    }

    //查询人员违规记录 by Yangdi
    public GeneralResponse getAccidentRecord1(Map<String, Object> params) throws ClientException {
        Integer farmId = (int) params.get("farmId");
        if (farmId != 1) {
            //返回为空数据
            return new GeneralResponse();
        }
        String URL = "/evo-apigw/evo-accesscontrol/1.0.0/card/accessControl/swingCardRecord/bycondition/combined";  //获取事件URL    post请求
        IClient iClient = new DefaultClient();
        System.out.println("开始执行");
        //这种已经在配置文件里面安排了账号ip以及密码
        GeneralRequest generalRequest = new GeneralRequest(URL, Method.POST);
        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("执行结束");
        return generalResponse;
    }

    /**
     * //查人员通过过去几个小时的接口---异常通过次数接口
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return
     * @throws ClientException
     */
    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);
        System.out.println("内部参数>>" + params);
        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("执行结束");
        JSONObject jsonObject = JSONObject.fromObject(generalResponse.getResult());
        Object data = jsonObject.get("data");
        System.out.println("## 内部打印结果>>" + data);
        return data.toString();
    }

    //人员通道查询总页数 by Yangdi
//    @RequestMapping("/get_person_record_totalpage")
//    public GeneralResponse get_person_record_totalpage( @RequestBody Map<String, Object> params ) throws ClientException {
//        Integer  farmId= (int) params.get("farmId");
//        if(farmId!=1){
//            //返回为空数据
//            return  new GeneralResponse() ;
//        }
//        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("执行结束");
//        return generalResponse;
//    }

    public static void main(String[] args) throws ClientException {

        Map<String, Object> params1 = new HashMap<>();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        Date date = new Date();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        //调整天数
        c.add(Calendar.DATE, 0);
        Date A = c.getTime();
        String formatA = format.format(A);
        c.set(Calendar.HOUR, +24);
        Date d = c.getTime();
        String formatD = format.format(d);
        System.out.println(formatA + formatD);

        System.out.println("########### formatA>>" + formatA);
        System.out.println("########### formatD>>" + formatD);

        params1.put("pageNum", 1);
        params1.put("pageSize", 20);
        params1.put("startSwingTime", formatA);
        params1.put("endSwingTime", formatD);
//        params1.put("startSwingTime","2021-12-24 00:00:00");
//        params1.put("endSwingTime","2021-12-24 23:59:59");

        params1.put("containDomain", "1");
        params1.put("openResult", 0); //刷脸失败
        String URL = "/evo-apigw/evo-accesscontrol/1.0.0/card/accessControl/swingCardRecord/bycondition/combined?systime=";
        IClient iClient = new DefaultClient();
        GeneralRequest generalRequest = new GeneralRequest(URL + Long.valueOf(String.valueOf((new Date()).getTime())), Method.POST);
        generalRequest.header("Content-Type", " application/json");
        generalRequest.body(JSON.toJSONString(params1));
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
//        System.out.println("## generalResponse>>"+generalResponse.toString());
        JSONObject jsonObject = JSONObject.fromObject(generalResponse.getResult());
//        System.out.println("## getResult>>"+generalResponse.getResult());
        GetResponse getResponse = new GetResponse();

        System.out.println("total>>" + getResponse.SendMassageGetPagePersonAlarm((String) params1.get("startSwingTime"), (String) params1.get("endSwingTime")));
        System.out.println(jsonObject.toString());
//        System.out.println("## 1>>"+JSON.toJSONString(generalResponse.getResult()));
//        JSON.parseObject(JSON.toJSONString(generalResponse.getResult()));
//        com.alibaba.fastjson.JSONObject resultJo = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(generalResponse.getResult());
//        System.out.println("## resultJo>>"+resultJo);
        com.alibaba.fastjson.JSONObject grObj = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(generalResponse);
        System.out.println("grObj>>" + grObj);
        com.alibaba.fastjson.JSONObject resultJo = grObj.getJSONObject("result");
        System.out.println("resultJo>>" + resultJo);
        com.alibaba.fastjson.JSONObject dataJo = resultJo.getJSONObject("data");
        System.out.println("dataJo>>" + dataJo);
        JSONArray pageDataJa = dataJo.getJSONArray("pageData");
        System.out.println("pageDataJa>>" + pageDataJa);
        System.out.println("pageDataJa.size>>" + pageDataJa.size());


    }
}
