package com.huimv.admin.controller;

import com.alibaba.fastjson.JSON;
import com.huimv.admin.common.utils.Result;
import com.huimv.admin.common.utils.ResultCode;
import com.huimv.admin.controller.feedVo.YiDong;
import com.huimv.admin.controller.feedVo.YiDongVdeio;
import com.huimv.admin.entity.dto.BasePigpenDto;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;


@RestController
@RequestMapping("/yiDongApi")
@CrossOrigin
public class YiDongApi {
    static  String   appid = "2434d08544624ba488134ca2cbf94cdc";
    static  String   secret = "JrEalX4NNVeqcnye";
    static  String   version = "1.0.0";
    static  String   apiUrl = "https://open.andmu.cn/v3/open/api/token";
    static  String   vodioUrl = "https://open.andmu.cn/v3/open/api/websdk/live";

    @GetMapping( "/getVideoList")
    public Result addPigpen() throws Exception {
        List list  = new ArrayList();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("vidoeName","大门");
        map.put("videoId","xxxxS_040312794def");

        HashMap<Object, Object> map1 = new HashMap<>();
        map1.put("vidoeName","清洗间");
        map1.put("videoId","xxxxS_0403126e81bc");

        HashMap<Object, Object> map2 = new HashMap<>();
        HashMap<Object, Object> map3 = new HashMap<>();
        HashMap<Object, Object> map4 = new HashMap<>();
        HashMap<Object, Object> map5 = new HashMap<>();
        HashMap<Object, Object> map6 = new HashMap<>();
        HashMap<Object, Object> map7 = new HashMap<>();
        map2.put("vidoeName","晾晒间");
        map2.put("videoId","xxxxS_0403126e8320");


        map3.put("vidoeName","内包房");
        map3.put("videoId","xxxxS_0403126e8220");


        map4.put("vidoeName"," 水汪汪_敏觉摄像头Smart-D2S-24A");
        map4.put("videoId","00023753262420621320000002");

        map5.put("vidoeName","水汪汪_敏觉摄像头Smart-D2S-24A");
        map5.put("videoId","00023753262420621320000010");

        map6.put("vidoeName","水汪汪_敏觉摄像头Smart-D2S-24A");
        map6.put("videoId","00023753262420621320000011");

        map7.put("vidoeName","水汪汪_敏觉摄像头Smart-D2S-24A");
        map7.put("videoId","00023753262420621320000008");
        list.add(map);
        list.add(map1);
        list.add(map2);
        list.add(map3);
        list.add(map4);
        list.add(map5);
        list.add(map6);
        list.add(map7);

        return new Result(ResultCode.SUCCESS,list);
    }

    @GetMapping( "/getVideo")
    public Result getVideo(@RequestParam("videoId") String videoId) throws Exception {
        YiDong token =  getToken();
        YiDongVdeio yiDongVdeio = getVedio(token,videoId);

      return new Result(ResultCode.SUCCESS,yiDongVdeio);
    }

    private  YiDongVdeio getVedio(YiDong token,String deviceId) throws Exception {

        String  timestamp = System.currentTimeMillis()+ "";
        RestTemplate restTemplate = new RestTemplate();

        Map<String, Object> body = new HashMap<>();
        body.put("deviceId", deviceId);
        String md5 = Hex.encodeHexString(MessageDigest.getInstance("MD5").digest(StringUtils.getBytesUtf8(JSON.toJSONString(body))));
        HttpHeaders headers = new HttpHeaders();
        headers.set("appid",appid);
        headers.set("md5",md5);
        headers.set("timestamp",timestamp);
        headers.set("token",token.getData().getToken());
        headers.set("version",version);

        String signature = signHeaders(appid, md5, timestamp, version,token.getData().getToken());
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("signature",signature);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(body, headers);

        return restTemplate.postForObject(vodioUrl, request, YiDongVdeio.class);
    }

    private  YiDong getToken() throws Exception {
        String sig =  Hex.encodeHexString(MessageDigest.getInstance("MD5").digest(StringUtils.getBytesUtf8(appid+secret)));
        String  timestamp = System.currentTimeMillis()+ "";
        RestTemplate restTemplate = new RestTemplate();

        Map<String, Object> body = new HashMap<>();
        body.put("sig", sig);
        body.put("operatorType", 1);

        String md5 = Hex.encodeHexString(MessageDigest.getInstance("MD5").digest(StringUtils.getBytesUtf8(JSON.toJSONString(body))));
        HttpHeaders headers = new HttpHeaders();
        headers.set("appid",appid);
        headers.set("md5",md5);
        headers.set("timestamp",timestamp);
        headers.set("version",version);
        String signature = signHeaders(appid, md5, timestamp, version,null);
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("signature",signature);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(body, headers);

        return restTemplate.postForObject(apiUrl, request, YiDong.class);

    }

    private  String signHeaders(String appid, String md5, String timestamp, String version,String token) throws Exception {
        String privateKey ="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJHrPRu7xaoEqpoCUSbSZ8caLLs3oPqJ0wcrCBo3jNLKuSi8xdvmETOHx47L33JXKoGdZzkiowun/kVNvp8WZW8xAC+vB/CELT7ddmwTG0/w+KQzJzJrLIjYvR+/xwFhyLLbypGpK4FaShQjBeet/aW7uRKe21Fex7gHapeldzCHAgMBAAECgYEAgYZsofeVyAuIXFj+LBXM5OGJH06L6Jj653v9Hzh8Goi0v0KB52ZbkoBOVaUG3XoeUxujiwYB8NDYVjBiqti4hBjjMmu0b+GvrESnh+h75zVtoWN2oMuNoNTImhmvIWvPMJ2TC0PZ18V5fd/E2JeZTw82i3EptWNvyAFEmKypBAECQQDPWtl6vKImB0N5v4CWQa3sCdfzrAnUVYcQbPk2ZcyYBb8aVH42GBjlfxkYVbpHct8Wdh9puqpf7NFa0Y2IBr2HAkEAtCa3mB0IBPWKXQAHYOp/T3LfpBZbgxaRQe4pv3ChO29WzQTIkKtYMdPzr+1e0TZ+MSG0gBmJ3gxE9OfatxC1AQJBAK5pd2bSxf0AvRPqLam1YyqYeQngWoA81JfPYawM4pO4ua7XBTZQ/JgFWUFr0n0ItXc6MmAHgAmhs9MVUlvpd38CQHQuzBTkFDnuiS91R0zvru90LFtMt/QQ59lXWcFHSBRmt9o9DYSPnK91/CEnuxC+TiAtlpVO4yU7UHWJ2fpaYgECQApGwUqJ+yjDZpKJZ8iEMaRBF2VnC4ygLcW5WeoTY6VN5XzJdki6rLMjaGiIZ0Wr3zCvy8/EneGBJY/xQQmvasw=";

        // 需要签名的参数
        Map<String, String> headersToSign = new TreeMap<>(); // 自动按key的ASCII顺序排序
        headersToSign.put("appid", appid);
        headersToSign.put("md5", md5);
        headersToSign.put("timestamp", timestamp);
        headersToSign.put("version", version);
        if (token != null &&!"".equals(token) ){
            headersToSign.put("token", token);
        }


        Base64.Encoder encoder = Base64.getEncoder();
        Base64.Decoder decoder = Base64.getDecoder();
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(decoder.decode(privateKey.getBytes()));
        PrivateKey priKey = KeyFactory.getInstance("RSA").generatePrivate(priPKCS8);
        Signature signature = Signature.getInstance("SHA1WithRSA");
        signature.initSign(priKey);
        String string = JSON.toJSONString(headersToSign);
        signature.update(string.getBytes("utf-8"));
        return encoder.encodeToString(signature.sign());

    }


}
