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.QueryEquipChargeStatusDTO;
import com.jsowell.pile.dto.QueryEquipmentDTO;
import com.jsowell.pile.dto.QueryStartChargeDTO;
import com.jsowell.pile.dto.QueryStationInfoDTO;
import com.jsowell.thirdparty.huawei.HuaWeiService;
import com.jsowell.thirdparty.lianlian.common.CommonResult;
import com.jsowell.pile.thirdparty.CommonParamsDTO;
import com.jsowell.thirdparty.platform.util.Cryptos;
import com.jsowell.thirdparty.platform.util.Encodes;
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 2024/1/15 13:52:05
 */
@Anonymous
@RestController
@RequestMapping("/huawei")
public class HuaWeiController extends BaseController {

    @Autowired
    private HuaWeiService huaWeiService;

    /**
     * 获取token接口
     * http://localhost:8080/huawei/v1/query_token
     */
    @PostMapping("/v1/query_token")
    public CommonResult<?> queryToken(@RequestBody CommonParamsDTO dto) {
        logger.info("华为平台请求令牌 params:{}", JSON.toJSONString(dto));
        try {
            Map<String, String> map = huaWeiService.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发生异常");
        }
    }


    /**
     * 查询充电站信息
     * @param dto
     */
    @RequestMapping("/v1/query_stations_info")
    public CommonResult<?> query_stations_info(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 = huaWeiService.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);
            // 转换成相应对象
            QueryStationInfoDTO queryStationInfoDTO = JSONObject.parseObject(dataStr, QueryStationInfoDTO.class);
            queryStationInfoDTO.setOperatorId(dto.getOperatorID());
            Map<String, String> map = huaWeiService.queryStationsInfo(queryStationInfoDTO);
            return CommonResult.success(0, "查询充电站信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("华为平台查询充电站信息 error", e);
        }
        return CommonResult.failed("查询充电站信息异常");
    }

    /**
     * 华为平台查询统计信息
     * http://localhost:8080/huawei/v1/query_stations_stats
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_station_status")
    public CommonResult<?> queryStationStatus(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 = huaWeiService.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);
            // 转换成相应对象
            QueryStationInfoDTO queryStationInfoDTO = JSONObject.parseObject(dataStr, QueryStationInfoDTO.class);
            queryStationInfoDTO.setOperatorId(dto.getOperatorID());
            Map<String, String> map = huaWeiService.queryStationStatus(queryStationInfoDTO);
            logger.info("华为平台查询统计信息 result:{}", JSON.toJSONString(map));
            return CommonResult.success(0, "查询统计信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("华为平台查询统计信息 error:", e);
            e.printStackTrace();
        }
        return CommonResult.failed("查询统计信息发生异常");
    }


    /**
     * 请求设备认证
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_equip_auth")
    public CommonResult<?> query_equip_auth(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("华为平台请求设备认证 param:{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(token)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            Map<String, String> resultMap = huaWeiService.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);
            // 转换成相应对象
            QueryEquipmentDTO queryEquipmentDTO = JSONObject.parseObject(dataStr, QueryEquipmentDTO.class);
            queryEquipmentDTO.setOperatorID(dto.getOperatorID());
            Map<String, String> map = huaWeiService.queryEquipAuth(queryEquipmentDTO);
            logger.info("华为平台请求设备认证 result:{}", JSON.toJSONString(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/huawei/v1/query_equip_business_policy
     * @param dto
     * @return
     */
    @PostMapping("/v1/request_equip_business_policy")
    public CommonResult<?> requestEquipBusinessPolicy(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 = huaWeiService.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);
            // 转换成相应对象
            QueryStartChargeDTO queryStartChargeDTO = JSONObject.parseObject(dataStr, QueryStartChargeDTO.class);
            queryStartChargeDTO.setOperatorId(dto.getOperatorID());
            Map<String, String> map = huaWeiService.requestEquipBusinessPolicy(queryStartChargeDTO);
            logger.info("华为平台请求计费策略 result:{}", JSON.toJSONString(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/huawei/query_equip_charge_status/{startChargeSeq}
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_equip_charge_status")
    public CommonResult<?> query_equip_charge_status(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 = huaWeiService.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);
            // 转换成相应对象
            QueryEquipChargeStatusDTO queryEquipChargeStatusDTO = JSONObject.parseObject(dataStr, QueryEquipChargeStatusDTO.class);
            queryEquipChargeStatusDTO.setOperatorID(dto.getOperatorID());
            Map<String, String> map = huaWeiService.queryEquipChargeStatus(queryEquipChargeStatusDTO);
            logger.info("华为平台查询充电状态 result:{}", JSON.toJSONString(map));
            return CommonResult.success(0, "查询充电状态成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("华为平台查询充电状态 error", e);
        }
        return CommonResult.failed("华为平台查询充电状态发生异常");
    }

    /**
     * 请求停止充电
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_stop_charge")
    public CommonResult<?> query_stop_charge(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 = huaWeiService.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);
            // 转换成相应对象
            QueryStartChargeDTO queryStartChargeDTO = JSONObject.parseObject(dataStr, QueryStartChargeDTO.class);
            queryStartChargeDTO.setOperatorId(dto.getOperatorID());
            Map<String, String> map = huaWeiService.queryStopCharge(queryStartChargeDTO);
            logger.info("华为平台请求停止充电 result:{}", JSON.toJSONString(map));
            return CommonResult.success(0, "请求停止充电成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("华为平台请求停止充电 error", e);
        }
        return CommonResult.failed("华为平台请求停止充电发生异常");
    }
}
