package com.bootdo.datas.controller;

import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.datas.domain.DataDO;
import com.bootdo.datas.service.DataService;
import com.bootdo.datas.tools.gm.FileCryptTool;
import com.bootdo.datas.tools.gm.GmUtils;

/**
 * @date 2022/4/21 15:53
 * @author wangp
 * @description
 */
@Controller
@RequestMapping("/api")
public class ApiController {

    private static Logger log = LoggerFactory.getLogger(ApiController.class);

    @Autowired
    private GmUtils gmUtils;


    @Autowired
    private DataService dataService;

    /**
     * @Description: 数据同步接收接口
     * @Author: wangp
     * @Date: 2022/4/21 16:03
     * @param
     * @Return: R
     */
    @ResponseBody
    @PostMapping("/accessData")
    public R accessData(@RequestBody String requestBody) {
        log.info("requestBody:" + requestBody);
        // 解密
        if (StringUtils.isBlank(requestBody)) {
            return R.error(9001, "参数为空");
        }
        String value = gmUtils.decrypt(requestBody);
        // 转body
        DataDO dataDO = JSON.parseObject(value, DataDO.class);
        log.info("dataDO:" + dataDO.toString());
        // 入库  企业 备案数据
        dataService.datAsync(dataDO);
        return R.ok();
    }

    public static void main(String[] args) {
        // 测试
        DataDO dataDO = new DataDO();
        dataDO.setIndustryType("123");
        dataDO.setUnitProvince("江苏");
        String result = JSON.toJSONString(dataDO);
        System.out.println(result);
        // 加密
        byte[] sourceData = result.getBytes();
        byte[] encData = FileCryptTool.encryptData("d:/sm2/sm2_client_enc_cert.crt", sourceData);
        String encValue = "";
        if (encData != null) {
            encValue = Hex.toHexString(encData);
            System.out.println("encValue:" + encValue);
        }
        // 解密
        byte[] decData = FileCryptTool.decryptData("d:/sm2/sm2_client_enc_private.key", Hex.decode(encValue));
        String decValue = "";
        if (decData != null) {
            decValue = new String(decData);
            System.out.println("decValue:" + decValue);
        }
        DataDO dataDO1 = JSON.parseObject(decValue, DataDO.class);
        System.out
            .println("IndustryType为:" + dataDO1.getIndustryType() + "，UnitProvince为：" + dataDO1.getUnitProvince());
    }

}
