package com.jsowell.api.thirdparty;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.util.JWTUtils;
import com.jsowell.pile.dto.ningxiajiaotou.NXJTQueryOrdersInfoDTO;
import com.jsowell.pile.dto.ningxiajiaotou.NXJTQueryStationInfoDTO;
import com.jsowell.thirdparty.lianlian.common.CommonResult;
import com.jsowell.pile.thirdparty.CommonParamsDTO;
import com.jsowell.thirdparty.lianlian.service.LianLianService;
import com.jsowell.thirdparty.platform.util.Cryptos;
import com.jsowell.thirdparty.platform.util.Encodes;
import com.jsowell.thirdparty.ningxiajiaotou.service.NXJTService;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 宁夏交投 Controller
 *
 * @author Lemon
 * @Date 2023/11/15 8:36:42
 */
@Anonymous
@RestController
@RequestMapping("/nxjt")
public class NXJTController extends BaseController {

    @Autowired
    private NXJTService nxjtService;

    @Autowired
    private LianLianService lianLianService;

    /**
     * 获取token接口
     * http://localhost:8080/nxjt/v1/query_token
     */
    @PostMapping("/v1/query_token")
    public CommonResult<?> queryToken(@RequestBody CommonParamsDTO dto) {
        logger.info("宁夏交投平台请求令牌 params:{}", JSON.toJSONString(dto));
        try {
            Map<String, String> map = nxjtService.generateToken(dto);
            logger.info("宁夏交投平台请求令牌 result:{}", JSON.toJSONString(map));
            return CommonResult.success(0, "请求令牌成功！", map.get("Data"), map.get("Sig"));
        } catch (UnsupportedEncodingException e) {
            logger.error("获取token接口 异常");
            return CommonResult.failed("获取token发生异常");
        }
    }

    /**
     * 宁夏交投平台查询充电站信息
     * http://localhost:8080/nxjt/v1/query_stations_info
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_stations_info")
    public CommonResult<?> queryStationsInfo(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("宁夏交投平台查询充电站信息 params:{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(token)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            Map<String, String> resultMap = lianLianService.checkoutSign(dto);
            if (resultMap == null) {
                // 签名错误
                return CommonResult.failed("签名校验错误");
            }
            String operatorSecret = resultMap.get("OperatorSecret");
            String dataString = resultMap.get("Data");
            String dataSecret = resultMap.get("DataSecret");
            String dataSecretIV = resultMap.get("DataSecretIV");
            // 解密data
            byte[] plainText = Cryptos.aesDecrypt(Encodes.decodeBase64(dataString), dataSecret.getBytes(), dataSecretIV.getBytes());
            String dataStr = new String(plainText, StandardCharsets.UTF_8);
            // 转换成相应对象
            NXJTQueryStationInfoDTO nxjtQueryStationInfoDTO = JSONObject.parseObject(dataStr, NXJTQueryStationInfoDTO.class);
            nxjtQueryStationInfoDTO.setOperatorId(dto.getOperatorID());
            Map<String, String> map = nxjtService.queryStationsInfo(nxjtQueryStationInfoDTO);
            // return CommonResult.success(map);
            return CommonResult.success(0, "查询充电站信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("宁夏交投平台查询充电站信息 error:", e);
            e.printStackTrace();
        }
        return CommonResult.failed("查询充电站信息发生异常");
    }


    /**
     * 宁夏交投平台查询充电站中空闲桩数量
     * http://localhost:8080/nxjt/v1/query_free_pile_number
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_free_pile_number")
    public CommonResult<?> queryFreePileNumber(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("宁夏交投平台查询充电站中空闲桩数量 params:{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(token)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            Map<String, String> resultMap = lianLianService.checkoutSign(dto);
            if (resultMap == null) {
                // 签名错误
                return CommonResult.failed("签名校验错误");
            }
            String operatorSecret = resultMap.get("OperatorSecret");
            String dataString = resultMap.get("Data");
            String dataSecret = resultMap.get("DataSecret");
            String dataSecretIV = resultMap.get("DataSecretIV");
            // 解密data
            byte[] plainText = Cryptos.aesDecrypt(Encodes.decodeBase64(dataString), dataSecret.getBytes(), dataSecretIV.getBytes());
            String dataStr = new String(plainText, StandardCharsets.UTF_8);
            // 转换成相应对象
            NXJTQueryStationInfoDTO nxjtQueryStationInfoDTO = JSONObject.parseObject(dataStr, NXJTQueryStationInfoDTO.class);
            nxjtQueryStationInfoDTO.setOperatorId(dto.getOperatorID());
            Map<String, String> map = nxjtService.queryFreePileNumber(nxjtQueryStationInfoDTO);
            // return CommonResult.success(map);
            return CommonResult.success(0, "查询充电站中空闲桩数量信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("宁夏交投平台查询充电站中空闲桩数量 error:", e);
            e.printStackTrace();
        }
        return CommonResult.failed("查询充电站中空闲桩数量信息发生异常");
    }

    /**
     * 宁夏交投平台查询某车牌号消费记录
     * http://localhost:8080/nxjt/v1/query_free_pile_number
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_orders_info_by_Plate_number")
    public CommonResult<?> queryOrdersInfoByPlateNumber(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("宁夏交投平台查询某车牌号消费记录 params:{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(token)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            Map<String, String> resultMap = lianLianService.checkoutSign(dto);
            if (resultMap == null) {
                // 签名错误
                return CommonResult.failed("签名校验错误");
            }
            String operatorSecret = resultMap.get("OperatorSecret");
            String dataString = resultMap.get("Data");
            String dataSecret = resultMap.get("DataSecret");
            String dataSecretIV = resultMap.get("DataSecretIV");
            // 解密data
            byte[] plainText = Cryptos.aesDecrypt(Encodes.decodeBase64(dataString), dataSecret.getBytes(), dataSecretIV.getBytes());
            String dataStr = new String(plainText, StandardCharsets.UTF_8);
            // 转换成相应对象
            NXJTQueryOrdersInfoDTO nxjtQueryOrdersInfoDTO = JSONObject.parseObject(dataStr, NXJTQueryOrdersInfoDTO.class);
            nxjtQueryOrdersInfoDTO.setOperatorId(dto.getOperatorID());
            Map<String, String> map = nxjtService.queryOrdersInfoByPlateNumber(nxjtQueryOrdersInfoDTO);
            // return CommonResult.success(map);
            return CommonResult.success(0, "查询充电站中空闲桩数量信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("宁夏交投平台查询某车牌号消费记录 error:", e);
            e.printStackTrace();
        }
        return CommonResult.failed("查询某车牌号消费记录发生异常");
    }


    /**
     * 宁夏交投平台查询某段时间内消费记录
     * http://localhost:8080/nxjt/v1/query_orders_info
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_orders_info")
    public CommonResult<?> queryOrdersInfo(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("宁夏交投平台查询某段时间内消费记录 params:{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(token)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            Map<String, String> resultMap = lianLianService.checkoutSign(dto);
            if (resultMap == null) {
                // 签名错误
                return CommonResult.failed("签名校验错误");
            }
            String operatorSecret = resultMap.get("OperatorSecret");
            String dataString = resultMap.get("Data");
            String dataSecret = resultMap.get("DataSecret");
            String dataSecretIV = resultMap.get("DataSecretIV");
            // 解密data
            byte[] plainText = Cryptos.aesDecrypt(Encodes.decodeBase64(dataString), dataSecret.getBytes(), dataSecretIV.getBytes());
            String dataStr = new String(plainText, StandardCharsets.UTF_8);
            // 转换成相应对象
            NXJTQueryOrdersInfoDTO nxjtQueryOrdersInfoDTO = JSONObject.parseObject(dataStr, NXJTQueryOrdersInfoDTO.class);
            nxjtQueryOrdersInfoDTO.setOperatorId(dto.getOperatorID());
            Map<String, String> map = nxjtService.queryOrdersInfo(nxjtQueryOrdersInfoDTO);
            // return CommonResult.success(map);
            return CommonResult.success(0, "查询充电站中空闲桩数量信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("宁夏交投平台查询某段时间内消费记录 error:", e);
            e.printStackTrace();
        }
        return CommonResult.failed("查询某段时间内消费记录发生异常");
    }
}
