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.enums.thirdparty.ThirdPlatformTypeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.JWTUtils;
import com.jsowell.pile.domain.ThirdPartyPlatformConfig;
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.pile.service.ThirdPartyPlatformConfigService;
import com.jsowell.pile.thirdparty.CommonParamsDTO;
import com.jsowell.thirdparty.lianlian.common.CommonResult;
import com.jsowell.thirdparty.platform.util.Cryptos;
import com.jsowell.thirdparty.platform.util.Encodes;
import com.jsowell.thirdparty.platform.service.ThirdPartyPlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

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

/**
 * 海南
 */
@Anonymous
@RestController
@RequestMapping("/hainan")
public class HaiNanPlatformController extends BaseController {
    // 使用海南平台处理逻辑
    // @Autowired
    // private AbsInterfaceWithPlatformLogic platformLogic = new HaiNanPlatformLogic();

    @Autowired
    @Qualifier("haiNanPlatformServiceImpl")
    private ThirdPartyPlatformService platformLogic;

    @Autowired
    private ThirdPartyPlatformConfigService thirdPartyPlatformConfigService;

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

    /**
     * 海南平台查询充电站信息
     * http://localhost:8080/hainan/v1/query_stations_info
     * @param dto
     * @return
     */
    @PostMapping("/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(request)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            // Map<String, String> resultMap = platformLogic.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");

            // 查询配置信息
            ThirdPartyPlatformConfig platformConfig = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorID());
            String operatorSecret = platformConfig.getOperatorSecret();
            String dataString = dto.getData();
            String dataSecret = platformConfig.getDataSecret();
            String dataSecretIV = platformConfig.getDataSecretIv();

            // 解密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());
            queryStationInfoDTO.setThirdPlatformType(ThirdPlatformTypeEnum.HAI_NAN_1_PLATFORM.getTypeCode());
            Map<String, String> map = platformLogic.queryStationsInfo(queryStationInfoDTO);
            logger.info("海南平台查询充电站信息 result:{}", JSON.toJSONString(map));
            return CommonResult.success(0, "查询充电站信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("海南平台查询充电站信息 error:", e);
        }
        return CommonResult.failed("查询充电站信息发生异常");
    }

    /**
     * 海南平台查询统计信息
     * http://localhost:8080/hainan/v1/query_stations_stats
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_station_stats")
    public CommonResult<?> queryStationStats(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("海南平台查询统计信息 params:{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            if (!JWTUtils.checkThirdPartyToken(request)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            // Map<String, String> resultMap = platformLogic.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");

            // 查询配置信息
            ThirdPartyPlatformConfig platformConfig = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorID());
            String operatorSecret = platformConfig.getOperatorSecret();
            String dataString = dto.getData();
            String dataSecret = platformConfig.getDataSecret();
            String dataSecretIV = platformConfig.getDataSecretIv();

            // 解密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 = platformLogic.queryStationStats(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("查询统计信息发生异常");
    }

    /**
     * 海南平台设备接口状态查询
     * http://localhost:8080/hainan/v1/query_stations_status
     * @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(request)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            // Map<String, String> resultMap = platformLogic.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");

            // 查询配置信息
            ThirdPartyPlatformConfig platformConfig = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorID());
            String operatorSecret = platformConfig.getOperatorSecret();
            String dataString = dto.getData();
            String dataSecret = platformConfig.getDataSecret();
            String dataSecretIV = platformConfig.getDataSecretIv();

            // 解密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 = platformLogic.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);
        }
        return CommonResult.failed("设备接口状态查询发生异常");
    }

    /**
     * 请求设备认证
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_equip_auth")
    public CommonResult<?> queryEquipAuth(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("请求设备认证 param:{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            // String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(request)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            // Map<String, String> resultMap = platformLogic.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");

            // 查询配置信息
            ThirdPartyPlatformConfig platformConfig = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorID());
            String operatorSecret = platformConfig.getOperatorSecret();
            String dataString = dto.getData();
            String dataSecret = platformConfig.getDataSecret();
            String dataSecretIV = platformConfig.getDataSecretIv();

            // 解密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 = platformLogic.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);
        }
        return CommonResult.failed("请求设备认证发生异常");
    }

    /**
     * 查询业务策略信息结果
     * http://localhost:8080/hainan/v1/query_equip_business_policy
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_equip_business_policy")
    public CommonResult<?> queryEquipBusinessPolicy(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("查询业务策略信息 params:{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            // String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(request)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            // Map<String, String> resultMap = platformLogic.checkoutSign(dto);
            // if (resultMap == null) {
            //     // 签名错误
            //     return CommonResult.failed("签名校验错误");
            // }

            // 查询配置信息
            ThirdPartyPlatformConfig platformConfig = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorID());
            String operatorSecret = platformConfig.getOperatorSecret();
            String dataString = dto.getData();
            String dataSecret = platformConfig.getDataSecret();
            String dataSecretIV = platformConfig.getDataSecretIv();

            // 解密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 = platformLogic.queryEquipBusinessPolicy(queryStartChargeDTO);
            logger.info("查询业务策略信息 result:{}", JSON.toJSONString(map));

            return CommonResult.success(0, "查询业务策略信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("查询业务策略信息 error:", e);
        }
        return CommonResult.failed("查询业务策略信息发生异常");
    }

    /**
     * 请求启动充电
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_start_charge")
    public CommonResult<?> query_start_charge(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("海南平台请求启动充电 params :{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            if (!JWTUtils.checkThirdPartyToken(request)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            // Map<String, String> resultMap = platformLogic.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");

            // 查询配置信息
            ThirdPartyPlatformConfig platformConfig = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorID());
            String operatorSecret = platformConfig.getOperatorSecret();
            String dataString = dto.getData();
            String dataSecret = platformConfig.getDataSecret();
            String dataSecretIV = platformConfig.getDataSecretIv();

            // 解密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 = platformLogic.queryStartCharge(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("请求启动充电发生异常");
    }

    /**
     * 推送启动充电结果
     * http://localhost:8080/hainan/notificationStartChargeResult/{orderCode}
     * @param orderCode
     * @return
     */
    @GetMapping("/notificationStartChargeResult/{orderCode}")
    public RestApiResponse<?> notificationStartChargeResult(@PathVariable("orderCode") String orderCode) {
        logger.info("【{}】推送启动充电结果 params:{}", this.getClass().getSimpleName(), orderCode);
        RestApiResponse<?> response = null;
        try {
            String result = platformLogic.notificationStartChargeResult(orderCode);
            response = new RestApiResponse<>(result);
        }catch (BusinessException e) {
            logger.error("【{}】推送启动充电结果 error",this.getClass().getSimpleName(), e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        }catch (Exception e) {
            logger.error("【{}】推送启动充电结果 error", this.getClass().getSimpleName(), e);
            response = new RestApiResponse<>(e);
        }
        logger.info("【{}】推送启动充电结果 result:{}", this.getClass().getSimpleName(), response);
        return response;
    }

    /**
     * 查询充电状态
     * http://localhost:8080/xindiantu/query_equip_charge_status/{startChargeSeq}
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_equip_charge_status")
    public CommonResult<?> queryEquipChargeStatus(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("【{}】查询充电状态 params :{}", this.getClass().getSimpleName(), JSON.toJSONString(dto));
        try {
            // 校验令牌
            // String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(request)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            // Map<String, String> resultMap = platformLogic.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");

            // 查询配置信息
            ThirdPartyPlatformConfig platformConfig = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorID());
            String operatorSecret = platformConfig.getOperatorSecret();
            String dataString = dto.getData();
            String dataSecret = platformConfig.getDataSecret();
            String dataSecretIV = platformConfig.getDataSecretIv();

            // 解密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 = platformLogic.queryEquipChargeStatus(queryEquipChargeStatusDTO);
            logger.info("【{}】查询充电状态 result:{}", this.getClass().getSimpleName(), JSON.toJSONString(map));
            return CommonResult.success(0, "查询充电状态成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("【{}】平台查询充电状态 error", this.getClass().getSimpleName(), e);
        }
        return CommonResult.failed("新电途平台查询充电状态发生异常");
    }

    /**
     * 推送充电状态
     * http://localhost:8080/hainan/notificationEquipChargeStatus
     * @param orderCode
     * @return
     */
    @GetMapping("/notificationEquipChargeStatus/{orderCode}")
    public RestApiResponse<?> notificationEquipChargeStatus(@PathVariable("orderCode") String orderCode) {
        logger.info("推送充电状态 params:{}", orderCode);
        RestApiResponse<?> response = null;
        try {
            String result = platformLogic.notificationEquipChargeStatus(orderCode);
            response = new RestApiResponse<>(result);
        }catch (BusinessException e) {
            logger.error("推送充电状态 error",e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        }catch (Exception e) {
            logger.error("推送充电状态 error", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("推送充电状态 result:{}", response);
        return response;
    }

    /**
     * 请求停止充电
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_stop_charge")
    public CommonResult<?> queryStopCharge(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("请求停止充电 params :{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            // String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(request)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            // Map<String, String> resultMap = platformLogic.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");

            // 查询配置信息
            ThirdPartyPlatformConfig platformConfig = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorID());
            String operatorSecret = platformConfig.getOperatorSecret();
            String dataString = dto.getData();
            String dataSecret = platformConfig.getDataSecret();
            String dataSecretIV = platformConfig.getDataSecretIv();

            // 解密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 = platformLogic.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("请求停止充电发生异常");
    }

    /**
     * 推送停止充电结果
     * http://localhost:8080/hainan/notificationStopChargeResult
     * @param orderCode
     * @return
     */
    @GetMapping("/notificationStopChargeResult/{orderCode}")
    public RestApiResponse<?> notificationStopChargeResult(@PathVariable("orderCode") String orderCode) {
        logger.info("推送停止充电结果 params:{}", orderCode);
        RestApiResponse<?> response = null;
        try {
            String result = platformLogic.notificationStopChargeResult(orderCode);
            response = new RestApiResponse<>(result);
        }catch (BusinessException e) {
            logger.error("推送停止充电结果 error",e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        }catch (Exception e) {
            logger.error("推送停止充电结果 error", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("推送停止充电结果 result:{}", response);
        return response;
    }
}
