package com.sptg.repeater.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sptg.repeater.vo.CommonValues;
import com.sptg.repeater.vo.Response;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.math.BigInteger;
import java.util.Map;


@Component
public class HttpUti {

    private static final Logger logger = Logger.getLogger(HttpUti.class);

    private static CommonValues cv;

    @Autowired
    public HttpUti(CommonValues cv) {
        HttpUti.cv = cv;
    }

    /**
     * post大豪设备
     * @param url
     * @param paramMap
     * @return
     */
    public static Response postDH(String url, Map<String, Object> paramMap) {
        try {
            String result = HttpUtil.post(url, paramMap);

//            logger.info("调用大豪接口结果："+result);

            if(StrUtil.isBlank(result)) {
                // api无返回结果
                return new Response(405);
            }
//{"msg":"DEVICELOCK_STATUS(1:onLine 0:notOnLine) : 1","result":0,"data":"{\"DEVICEID\":\"CD329D84\",\"CMD\":\"01\",\"status\":1}"}
            JSONObject jsonRes = JSONUtil.parseObj(result);
            int resultCode = Convert.toInt(jsonRes.get("result"), -100);
            String msg = jsonRes.getStr("msg");
            Object data = null;

            if(!StrUtil.isBlank(jsonRes.getStr("data"))){
                if(JSONUtil.isJson(jsonRes.getStr("data"))){
                    data = JSONUtil.createObj();
                    data = JSONUtil.parseObj(jsonRes.get("data"));
                }else{
                    data = jsonRes.get("data");
                }
            }

            return new Response(resultCode, msg, data);
        }catch (Exception e){
            logger.error("post大豪设备：",e);
            // 连接异常
            return new Response(508, e.getMessage());
        }
    }


    /**
     * 发送结果到常运智慧项目
     * @param id       指令Id
     * @param code     例如：add_notice
     * @param status   状态：{ 2：成功，3：异常 }
     * @param errorMsg 失败原因
     * @param data     JSON格式
     */
    public static void postCallback(String id, String code, String status, String errorMsg, JSONObject data){
        try {
            String callbackData = "{}";
            if(data != null){
                callbackData = JSONUtil.toJsonStr(data);
            }
            String url = cv.getLzUrl() + cv.getLzCallback();
            JSONObject param = JSONUtil.createObj()
                        .put("id", id)
                        .put("instructCode", code)
                        .put("status", status)
                        .put("errorMsg", errorMsg)
                        .put("callbackData", callbackData);

            String result = HttpRequest.post(url)
                    .body(param.toString())
                    .execute().body();

            logger.info("发送结果到常运智慧项目的参数："+ "id :" + id +", code: "+ code +", status: "+ status + ", errorMsg: "+ errorMsg +", data: "+ data);
            logger.info("发送结果到常运智慧项目的结果："+ result);

        } catch (Exception e){
            logger.error("发送结果到常运智慧项目异常：", e);
        }
    }

    /**
     * 发送异常结果给常运智慧项目
     * @param object
     * @param errorMsg
     * @param resData
     */
    public static void postLzAbnormal(JSONObject object, String errorMsg, JSONObject resData){
        String code = object.getStr("code");
        String id = object.getStr("id");
        // 发送结果到常运智慧项目
        postCallback(id, code, "3", errorMsg, resData);
    }

    /**
     * 发送异常结果给常运智慧项目
     * @param instructId 常运智慧项目指令ID
     * @param errorMsg
     * @param resData
     */
    public static void postLzAbnormal(String instructId, String code, String status, String errorMsg, JSONObject resData){
        // 发送结果到常运智慧项目
        postCallback(instructId, code, status, errorMsg, resData);
    }

    /**
     * 发送异常消息到常运智慧项目
     * @param errorMsg
     * @param resData
     */
    public static void postLzAbnormal(String errorMsg, JSONObject resData){
        // 发送结果到常运智慧项目
        postCallback("500", "err", "3", errorMsg, resData);
    }

    /**
     * 发送开门记录到常运智慧项目
     * @Param resData 请求数据
     * index：0:设备序列号，1：记录条数，2：开门类型{(1:APP ID; 2:密码; 3:卡片(4Bytes);4:指纹 ;5:身份证:(8Bytes) 6:银行卡)}，3：大豪加工过的卡号，4：操作方式，5,：开门时间
     */
    public static void postLzAbnormalUploadDoorLog(JSONObject resData){
        try {
            if(resData != null){
                Object serialNumber = resData.get("DEVICEID");
                JSONArray array = JSONUtil.parseArray(resData.get("PARAMS"));
                String oriOpenDoorType = null;
                if(array.size() > 2){
                    if(array.get(2) != null){
                        oriOpenDoorType = (String)array.get(2); //开门方式
                    }
                    Object openDoorType = null; //开门方式
                    if(oriOpenDoorType.equals("2")){ //大豪密码开门方式
                        openDoorType = "1"; //社区密码开门方式
                    }else if(oriOpenDoorType.equals("3")){ //大豪卡片开门方式
                        openDoorType = "2"; //社区卡片开门方式
                    }
                    String accessCardNo = null;
                    if(array.get(3) != null){
                        accessCardNo = ((String)array.get(3)).substring(0, 8); //开门卡号/密码
                    }
                    if(accessCardNo != null){
                        if(oriOpenDoorType.equals("3")){
                            BigInteger bigint=new BigInteger(accessCardNo, 16);
                            Long l = bigint.longValue();
                            accessCardNo = l.toString();
                        }else if(oriOpenDoorType.equals("2")){
                            String[] split = accessCardNo.split("");
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < split.length; i++){
                                if(split[i].equals("F")){

                                }else{
                                    sb.append(split[i]);
                                }
                            }
                            accessCardNo = sb.toString();
                        }
                    }else{
                        return ;
                    }
                    Object accessDate = null;
                    if(array.get(5) != null){
                        accessDate = array.get(5); //开门时间
                    }
                    String url = cv.getLzUrl() + cv.getUploadOpenDoorLog();
                    JSONObject param = JSONUtil.createObj()
                            .put("serialNumber", serialNumber)
                            .put("openDoorType", openDoorType)
                            .put("accessCardNo", accessCardNo)
                            .put("accessDate", accessDate);
                    String result = HttpRequest.post(url)
                            .body(param.toString())
                            .execute().body();
                    logger.info("上传开门记录到常运智慧项目的参数："+ "serialNumber :" + serialNumber +", openDoorType: "+ openDoorType +", accessCardNo: "+ accessCardNo + ", accessDate: "+ accessDate);
                    logger.info("上传开门记录到常运智慧项目的参数："+ result);
                }else{
                    return;
                }
            }else{
                return;
            }
        } catch (Exception e){
            logger.error("发送结果到常运智慧项目异常：", e);
        }
    }

    /**
     * 发送远程开门记录到常运智慧项目
     * @Param resData 请求数据
     */
    public static void postLzAbnormalUploadOpenDoor(JSONObject resData){
        try {
            if(resData != null){
                Object serialNumber = resData.get("DEVICEID");
                String url = cv.getLzUrl() + cv.getUploadOpenDoorLog();
                String serialNo = (String)resData.get("SERIALNO"); //这里特别点，有指令ID=住户ID拼接而成的字符串，比如1343423423=u_1239584867
                String userId = serialNo.split("=")[1];
                JSONObject param = JSONUtil.createObj()
                        .put("serialNumber", serialNumber)
                        .put("openDoorType", "3") //常运智慧远程开门类型
                        .put("accessCardNo", null)
                        .put("userId", userId)
                        .put("accessDate", null);
                String result = HttpRequest.post(url)
                        .body(param.toString())
                        .execute().body();
                logger.info("上传开门记录到常运智慧项目的参数："+ "serialNumber :" + serialNumber +", openDoorType: "+ "3" +", accessCardNo: "+ null + ", userId: "+ userId + ", accessDate: "+ null);
                logger.info("上传开门记录结果到常运智慧项目："+ result);
            }else{
                return;
            }
        } catch (Exception e){
            logger.error("发送结果到常运智慧项目异常：", e);
        }
    }

    /**
     * 发送心跳记录到常运智慧项目
     * @Param resData 请求数据
     */
    public static void postLzAbnormalCheckHeartBeat(JSONObject resData){
        try {
            if(resData != null){
                Object serialNumber = resData.get("DEVICEID");
                String url = cv.getLzUrl() + cv.getHeartbeat();
                logger.info("上传常运智慧项目地址：" + url);
                JSONObject param = JSONUtil.createObj()
                        .put("serialNumber", serialNumber);
                String result = HttpRequest.post(url)
                        .body(param.toString())
                        .execute().body();
                logger.info("上传心跳记录到常运智慧项目的参数："+ "serialNumber :" + serialNumber);
                logger.info("心跳发送结果："+ "result :" + result);
            }else{
                return;
            }
        } catch (Exception e){
            logger.error("发送结果到常运智慧项目异常：", e);
        }
    }

    /**
     * 发送门禁卡下发回调记录到常运智慧项目
     * @Param serialNo 单个指令的id
     */
    public static void postLzAbnormalAddOpenCard(String serialNo){
        try {
            if(StringUtils.hasText(serialNo)){
                String url = cv.getLzUrl() + cv.getUploadOpenDoorLog();
                JSONObject param = JSONUtil.createObj()
                        .put("id", serialNo);
                String result = HttpRequest.post(url)
                        .body(param.toString())
                        .execute().body();
                logger.info("上传卡片下发回调结果到常运智慧项目的参数："+ "id :" + serialNo);
                logger.info("卡片下发回调结果："+ "result :" + result);
            }else{
                return;
            }
        } catch (Exception e){
            logger.error("发送结果到常运智慧项目异常：", e);
        }
    }

    // 多张发卡（IMPORTFLAG=1）
    // 回调结果
    // {"DEVICEID":"CD329D84","RESULT":0,"OPERATE":"27","SERIALNO":"1163664108063813634","PARAMS":["CD329D84","00"]}
    // {"DEVICEID":"CD329D84","RESULT":0,"OPERATE":"AB","SERIALNO":"1163664108063813634","PARAMS":["CD329D84","00","00e0d06c"]}
    // {"DEVICEID":"CD329D84","RESULT":0,"OPERATE":"AC","SERIALNO":"1163664108063813634","PARAMS":["CD329D84","00"]}

}
