package com.yida.data.common.core.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yida.data.common.core.entity.constant.DaHuaConstant;
import com.yida.data.common.core.exception.FebsException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

@Slf4j
//@RequiredArgsConstructor
//@Component
public class DaHuaUtil {

    private final static String ADDRESS = "https://59.52.200.227:4443";
    private final static String SK = "482c4ec6b0779450d1b954a3";
    private final static String AK = "42d64cb7bba7366c990a3f04";

    private final static String BASE64_HEADER = "data:image/jpeg;base64,";

    public static String sign(String httpType, String url, String contentType, String date, String uuid) {
        String contentMD5 = "";
        String stringToSign = httpType + "\n"
                + contentMD5 + "\n"
                + contentType + "\n"
                + date + "\n"
                + uuid + "\n"
                + "1.0" + "\n"
                + url;
        try {
            SecretKeySpec signingKey = new SecretKeySpec(SK.getBytes("UTF-8"), "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(signingKey);
            mac.update(stringToSign.getBytes("UTF-8"));
            byte[] baseCode = Base64Utils.encode(mac.doFinal());
            return new String(baseCode, "UTF-8");
        } catch (Exception e) {
            log.error("大华签名失败", e);
            throw new FebsException("请求失败");
        }
    }

    /**
     * 请求大华接口
     *
     * @param requestType 请求类型  get post
     * @param url         请求路径  get请求带参数
     * @param contentType
     * @return
     */
    public static Object request(String requestType, String url, String contentType, String body) {
        String uuid = UUID.randomUUID().toString();
        contentType = StrUtil.isNotBlank(contentType) ? contentType : "";
        //签名
        String date = LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        String authorization = sign(requestType, "GET".equals(requestType) ? url : url.split("\\?")[0],
                contentType, date,
                uuid);
        HttpRequest request = HttpUtil.createRequest(parseMethod(requestType), ADDRESS + url)
                .header("Authorization", "LC-HMAC-SHA256" + " " + AK + ":" + authorization)
                .header("Content-MD5", "")
                .header("Content-Type", contentType)
                .header("X-LC-Date", date)
                .header("X-LC-Nonce", uuid)
                .header("X-LC-VERSION", "1.0");
        if (StrUtil.isNotBlank(body) && StrUtil.isNotBlank(contentType)) {
            request.body(body, contentType);
        }
        HttpResponse response = request.execute();
        log.info("大华请求接口返回,res:[{}]", response.body());
        if (response.getStatus() == 200) {
            //log.info("请求结果,res:[{}]", response.body());
            JSONObject res = JSONUtil.parseObj(response.body());
            if (!res.getInt("code").equals(200)) {
                log.error("请求大华接口失败,requestType:[{}],url:[{}],contentType:[{}],res:[{}],body:[{}]", requestType,
                        url, contentType, response, response.body());
                throw new FebsException("操作失败");
            }
            return res.get("data");
        } else {
            log.error("请求大华接口失败,requestType:[{}],url:[{}],contentType:[{}],res:[{}],body:[{}]", requestType,
                    url, contentType, response, response.body());
            throw new FebsException("操作失败");
        }
    }


    /**
     * 添加人员
     *
     * @param name      姓名
     * @param code      学工号
     * @param type      0-学生，1-教师
     * @param sex       1-男，2-女
     * @param cardNum   门禁卡号
     * @param classCode 班级学籍号
     * @return
     */
    public static Long addUser(String name, String code, Integer type, Integer sex, String cardNum,
                               String schoolCode, String campusCode, String sectionCode, String gradeCode,
                               String classCode, String picUrl) {
        JSONObject body = new JSONObject() {{
            set("code", code);
            set("name", name);
            set("roleId", type == 0 ? "student001" : "teacher001");
            set("sex", sex);
            set("accessCardsn", cardNum);
            set("colleageArea", schoolCode);
            set("colleageCode", campusCode);
            set("colleageMajor", sectionCode);
            set("colleageGrade", gradeCode);
            set("colleageClass", classCode);
        }};
        // 转换图片
//        if (StrUtil.isNotBlank(picUrl)) {
//            body.set("photoBase64", BASE64_HEADER + getImageBase64(picUrl));
//        }
        JSONArray res = (JSONArray) request("POST", DaHuaConstant.ADD_USER, "application/json",
                body.toString());
        return res.getLong(0);
    }

    /**
     * 修改人员
     *
     * @param id        id
     * @param name      姓名
     * @param code      学工号
     * @param type      0-学生，1-教师
     * @param sex       1-男，2-女
     * @param classCode 班级学籍号
     * @return
     */
    public static void updateUser(Long id, String name, String code, Integer type, Integer sex,
                                  String schoolCode, String campusCode, String sectionCode, String gradeCode,
                                  String classCode, String picUrl) {
        JSONObject body = new JSONObject() {{
            set("id", id);
            set("code", code);
            set("name", name);
            set("roleId", type == 0 ? "student001" : "teacher001");
            set("sex", sex);
            set("accessCardsn", generateCardNum());
            set("colleageArea", schoolCode);
            set("colleageCode", campusCode);
            set("colleageMajor", sectionCode);
            set("colleageGrade", gradeCode);
            set("colleageClass", classCode);
        }};
        // 转换图片
//        if (StrUtil.isNotBlank(picUrl)) {
//            body.set("photoBase64", BASE64_HEADER + getImageBase64(picUrl));
//        }
        request("PUT", DaHuaConstant.UPDATE_USER, "application/json",
                body.toString());
    }

    /**
     * 删除人员
     *
     * @param ids 逗号连接的id串
     * @return
     */
    public static void delUser(String ids) {
        StringBuilder url = new StringBuilder(DaHuaConstant.DEL_USER).append("?ids=").append(ids);
        request("DELETE", url.toString(), "application/json", null);
    }

    /**
     * 添加部门
     *
     * @param pId  父id
     * @param name 名称
     * @return
     */
    public static JSONObject addDept(String pId, String name) {
        JSONObject body = new JSONObject() {{
            set("pId", pId);
            set("name", name);
        }};
        JSONObject res = (JSONObject) request("POST", DaHuaConstant.ADD_DEPT, "application/json", body.toString());
        return res;
    }


    /**
     * 修改部门
     *
     * @param id   id
     * @param pId  父id
     * @param name 名称
     * @return
     */
    public static void updateDept(String id, String pId, String name) {
        JSONObject body = new JSONObject() {{
            set("id", id);
            set("pId", pId);
            set("name", name);
        }};
        request("PUT", DaHuaConstant.UPDATE_DEPT, "application/json", body.toString());
    }

    /**
     * 删除部门
     *
     * @param ids 部门id
     */
    public static void delDept(List<String> ids) {
        JSONObject body = new JSONObject() {{
            set("ids", ids);
        }};
        JSONObject res = (JSONObject) request("DELETE", DaHuaConstant.DEL_DEPT, "application/json", body.toString());
    }

    public static JSONObject getMqConfig(String publicKey) throws UnsupportedEncodingException {
        String secret1 = "1ncjpqp50wqdvbljuuwxb31ctmta0cyj";
        String rsaPublic = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----";
        //RSA rsa = SecureUtil.rsa(null, rsaPublic.getBytes("utf-8"));
        //String secret2= new String(rsa.encrypt(secret1,"utf-8", KeyType.PublicKey));
        String secret2 = "Zny0QjovibMgub+AxiD9FvuxjOcg2+vkCBlN6pVWi84vUjzNTUMguNtCaEt4w9qkR+JfoBVaj7o9lxkoBIdqn8iQAf+CAGo42pWZeJkNtrPNflw/btlIrN+/l7ILxFH7TvckkTY4wdKCpd08L9V4eyXtWvo4+7Z7jz7f3T4EjlU=";
        JSONObject body = new JSONObject() {{
            set("publicKey", publicKey);
            set("secretKey", secret2);
        }};
        JSONObject res = (JSONObject) request("POST", DaHuaConstant.GET_MQ_CONFIG, "application/json", body.toString());
        byte[] userName = SecureUtil.aes(secret1.getBytes()).decrypt(res.getStr("userName"));
        byte[] password = SecureUtil.aes(secret1.getBytes()).decrypt(res.getStr("password"));
        res.set("userName", new String(userName));
        res.set("password", new String(password));
        return res;
    }

    public static String getPublicKey() {
        JSONObject res = (JSONObject) request("GET", DaHuaConstant.GET_PUBLIC_KEY, null, null);
        return res.getStr("publicKey");
    }

    /**
     * 生成卡号
     *
     * @return
     */
    public static String generateCardNum() {
        return RandomUtil.randomString("abcdefABCDEF0123456789", 8);
    }

    /**
     * 生成学工号
     *
     * @return
     */
    public static String generateCode() {
        return RandomUtil
                .randomString(RandomUtil.BASE_CHAR.toUpperCase(Locale.ROOT) + RandomUtil.BASE_CHAR + RandomUtil.BASE_NUMBER,
                        20);
    }


    private static Method parseMethod(String method) {
        Method res = null;
        switch (method) {
            case "GET":
                res = Method.GET;
                break;
            case "POST":
                res = Method.POST;
                break;
            case "PUT":
                res = Method.PUT;
                break;
            case "DELETE":
                res = Method.DELETE;
                break;
            default:
                break;
        }
        return res;
    }

    /**
     * 在线图片转base64
     *
     * @param picUrl 在线图片地址
     * @return java.lang.String
     * @author ZYJ
     * @date 2022/10/13 14:30
     */
    public static String getImageBase64(String picUrl) {
        InputStream in = null;
        try {
            URL url = new URL(picUrl);
            byte[] data = null;
            // 远程文件
            in = url.openStream();
            data = new byte[in.available()];
            in.read(data);
            in.close();
            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(data);
        } catch (Exception e) {
            throw new FebsException("图片转base64失败");
        }
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
//        JSONObject data = new JSONObject() {{
//            set("categories", new JSONArray());
//            set("deviceCodes", new JSONArray());
//        }};
//        JSONObject res = (JSONObject) request("POST", "/eags/api/pims/v1.0/deviceInfo", "application/json",
//                data.toString());
//        System.out.println("");
        String picUrl = "http://zbz.yd-data.com:8864/pic/other/2022925/a62a9c08ac574d499561dd1d74c745d2.jpg";
        System.out.println(getImageBase64(picUrl));
    }
}
