package com.ics.common.utils;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ics.common.core.domain.dto.DevicePersonDto;
import com.ics.common.core.domain.dto.DevicePersonsDto;
import com.ics.common.core.domain.dto.FacesDto;
import com.ics.common.json.JsonUtils;
import org.apache.poi.ss.util.ImageUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DeviceUtils {

    private static final Logger log = LoggerFactory.getLogger(DeviceUtils.class);
    private final  static String DEVICE_IP = "http://192.168.0.12:80";

    private static final String BASE64_PREFIX="data:image/png;base64,";


    /**
     *
     */

    public static String setDeviceInfo(String deviceId,String deviceName,String deviceAddress) {
        String url = deviceAddress + "/api/tmzz/v2/setDeviceInfo";

        JSONObject param = JSONUtil.createObj();

        param.put("deviceId", deviceId);
        param.put("deviceName", deviceName);
        param.put("deviceAddress", deviceAddress);

        String msg = HttpUtil.post(url,param.toString());
        log.info("门禁设备信息:{}", msg);
        return msg;
    }


    /**
     * 门禁设备信息
     *
     * @return
     */
    public static String getDeviceInfo() {
        String url = DEVICE_IP + "/api/tmzz/v2/getDeviceInfo";

        String msg = HttpUtil.post(url,"");
        log.info("门禁设备信息:{}", msg);
        return msg;
    }

    public static String openlock(String ip) {
        String url = ip + "/api/viso/v2/openlock";

        String msg = HttpUtil.post(url,"");
        log.info("门禁设备信息:{}", msg);
        return msg;
    }

    /**
     *设置激活状态
     *
     */

    public static String setActive() {
        String url = DEVICE_IP + "/api/tmzz/v2/setActive";


        JSONObject param = JSONUtil.createObj();

        param.put("username", "21232f297a57a5a743894a0e4a801fc3");
        param.put("password", "0192023a7bbd73250516f069df18b500");

        String msg = HttpUtil.post(url,param.toString());
        log.info("门禁设备信息:{}", msg);
        return msg;
    }

    /**
     * 获取设备激活状态
     */
    public static String getActive(String ip) {
        String url = ip + "/api/tmzz/v2/getActive";

        String msg = HttpUtil.post(url,"");
        log.info("门禁设备信息:{}", msg);
        return msg;
    }

    /**
     *设备新增人员
     *
     * {
     * "persons":[
     * {
     * "personId":"010",
     * "name":"张三",
     * "workId":"001",
     * "gender":"male",
     * "age":30,
     * "certificateType":111,
     * "certificateNumber":"12345678910",
     * "phone":"13800000000",
     * "email":"test@qq.com",
     * "address":"中国上海某街道办",
     * "personType":"staff",
     * "visitorValidStartTime":"2022-01-01T10:53:57
     * ",
     * "visitorValidEndTime":"2022-01-30T10:54:00",
     * "comment":"已调到事业一部",
     * "qrcode":"1122336",
     * "faces":[
     * {
     * "faceId":"001",
     * "data":"data:image/jpeg;base
     * 64,/9j/4AAQSkZJRgABAQEAYABgAADfoaT7K/AG2rWoA"//示例中的照片 base64 为
     * 不完整数据
     * }
     * ],
     * "accessInfo":{
     * "cardNum":"779437058",
     * "cardValidStartTime":"2022-01-01T10:
     * 53:36",
     * "cardValidEndTime":"2022-01-30T10:5
     * 3:39"
     * }
     * },
     * {
     * ]
     * }
     */
    public static String addPersons(String ip,DevicePersonDto dto) {
        log.info("ip为{}", ip);
        String url = ip + "/api/viso/v2/addPersons";
        ArrayList<DevicePersonDto> dtos = new ArrayList<>();
        DevicePersonsDto devicePersonDto = new DevicePersonsDto();

        dtos.add(dto);

        devicePersonDto.setPersons(dtos);
        log.info("人员信息为:{}", devicePersonDto);
        String json = JsonUtils.toJson(devicePersonDto);

        String msg = HttpUtil.post(url,json);
        log.info("设备新增人员:{}", msg);
        return msg;
    }

    /**
     * 删除人员信息
     */
    public static String deletePersons(String ip,Long personId) {
        String url = ip + "/api/viso/v2/deletePersons";
        ArrayList<DevicePersonDto> dtos = new ArrayList<>();
        DevicePersonsDto devicePersonDto = new DevicePersonsDto();
        DevicePersonDto dto = new DevicePersonDto();
        dto.setPersonId(String.valueOf(personId));
        dtos.add(dto);
        devicePersonDto.setPersons(dtos);
        String json = JsonUtils.toJson(devicePersonDto);
        String msg = HttpUtil.post(url,json);
        log.info("删除人员信息:{}", msg);
        return msg;
    }

    /**
     * 修改人脸
     */
    public static String modifyFaces(String ip,DevicePersonDto dto) {
        String url = ip + "/api/viso/v2/modifyFaces";
//        DevicePersonDto devicePersonDto = new DevicePersonDto();
//        FacesDto facesDto = new FacesDto();
//        facesDto.setFaceId("001");
//        String imgurl = "E:\\360MoveData\\Users\\Administrator\\Desktop\\图片\\图片\\photo.jpg";
//        String s =BASE64_PREFIX+ UrlToBase64Util.imageUrlToBase64(imgurl);
        String json = JsonUtils.toJson(dto);
        System.out.println(json);
        System.out.println(url);
        String msg = HttpUtil.post(url,json);
        log.info("设备修改人脸:{}", msg);
        return msg;
    }





    /**
     * 添加人脸照片
     */
    public static String addFaces() {
        String url = DEVICE_IP + "/api/viso/v2/addFaces";
        ArrayList<FacesDto> faceDtos = new ArrayList<>();
        DevicePersonDto devicePersonDto = new DevicePersonDto();
        devicePersonDto.setPersonId("010");
        FacesDto facesDto = new FacesDto();
        facesDto.setFaceId("001");
        String imgurl = "E:\\360MoveData\\Users\\Administrator\\Desktop\\图片\\图片\\photo.jpg";
        String s =BASE64_PREFIX+ UrlToBase64Util.imageUrlToBase64(imgurl);
        facesDto.setData(s);
        faceDtos.add(facesDto);
        devicePersonDto.setFaces(faceDtos);
        String json = JsonUtils.toJson(devicePersonDto);
        System.out.println(json);
        System.out.println(url);
        String msg = HttpUtil.post(url,json);
        log.info("设备新增人员:{}", msg);
        return msg;
    }


    /**
     *获取定期清理过期访客配置
     */
    public static String getCleanExpiredPersonConfig(String ip) {
        String url = ip + "/api/viso/v2/getCleanExpiredPersonConfig";

        String msg = HttpUtil.post(url,"");
        log.info("获取定期清理过期访客配置:{}", msg);
        return msg;
    }


    /**
     * 记录查询
     */
    public static String queryRecognizeRecord() {
        String url = DEVICE_IP + "/api/viso/v2/queryRecognizeRecord";
        JSONObject param = JSONUtil.createObj();
        param.put("pageIndex", 1);
        param.put("pageSize", 10);
        param.put("sort", "desc");
        param.put("personId", "0088");
        String json = JsonUtils.toJson(param);
        System.out.println(json);
        System.out.println(url);
        String msg = HttpUtil.post(url,json);
        log.info("设备新增人员:{}", msg);
        return msg;
    }

    public static String queryPersons(String ip,String personId) {
        String url = ip + "/api/viso/v2/queryPersons";
        JSONObject param = JSONUtil.createObj();
        param.put("any", false);
        param.put("personId", personId);
        String json = JsonUtils.toJson(param);

        String msg = HttpUtil.post(url,json);
        log.info("查询人员id:{}", msg);
        return msg;
    }


    public static boolean ping(String ipAddress) throws Exception {
        int  timeOut =  3000 ;  //超时应该在3钞以上
        boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut);     // 当返回值是true时，说明host是可用的，false则不可。
        return status;
    }

//    public  static  boolean ping(String ipAddress,  int pingTimes,  int timeOut)  {
//        BufferedReader in =  null;
//        Runtime r = Runtime.getRuntime();   //  将要执行的ping命令,此命令是windows格式的命令
//        String pingCommand = "ping " + ipAddress + " -n " + pingTimes    + " -w " + timeOut;
//        try {    //  执行命令并获取输出
//            System.out.println(pingCommand);
//            Process p = r.exec(pingCommand);
//            if (p ==  null) {
//                return  false;
//            }
//            in =  new BufferedReader( new InputStreamReader(p.getInputStream()));    //  逐行检查输出,计算类似出现=23ms TTL=62字样的次数
//            int connectedCount = 0;
//            String line =  null;
//            while ((line = in.readLine()) !=  null) {
//                connectedCount += getCheckResult(line);
//            }    //  如果出现类似=23ms TTL=62这样的字样,出现的次数=测试次数则返回真
//            return connectedCount == pingTimes;
//        }  catch (Exception ex) {
//            ex.printStackTrace();    //  出现异常则返回假
//            return  false;
//        }  finally {
//            try {
//                in.close();
//            }  catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }
    // 若line含有=18ms TTL=16字样,说明已经ping通,返回1,否則返回0.
    private  static  int getCheckResult(String line) {   //  System.out.println("控制台输出的结果为:"+line);
        Pattern pattern = Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)",    Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            return 1;
        }
        return 0;
    }



    public static void main(String[] args) {

//        String s = addPersons(null,null);
//        deletePersons("192.168.0.12");
//        System.out.println(s);
//        String s = queryPersons("10000");
//
//        JSONObject jsonObject = JSONUtil.parseObj(s);
//        Integer amount = (Integer) jsonObject.get("amount");
//        System.out.println(amount);

//        Boolean isHost = ping("192.168.0.12",1,3000);
//        System.out.println(isHost);
    }


    public static String openControlLock(String ip) {
        String url = "http://192.168.30.36:808/api/Op/OpDoor?ipaddress="+ip;
        String msg = HttpUtil.get(url);
        log.info("开门控制器的结果为结果:{}", msg);
        return msg;
    }


}
