package com.jsowell.api.thirdparty;

import com.alibaba.fastjson2.JSON;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.enums.thirdparty.ThirdPartyReturnCodeEnum;
import com.jsowell.common.enums.thirdparty.ThirdPlatformTypeEnum;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.dto.*;
import com.jsowell.pile.thirdparty.CommonParamsDTO;
import com.jsowell.thirdparty.lianlian.common.CommonResult;
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.util.Map;

/**
 * 对接联联平台controller
 *
 * @author JS-ZZA
 * @date 2023/4/10 14:58
 */
@Anonymous
@RestController
@RequestMapping("/LianLian")
public class LianLianController extends ThirdPartyBaseController {

    private final String platformName = "联联平台";

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

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

    /**
     * 联联平台查询充电站信息
     * http://localhost:8080/LianLian/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:{}", platformName, JSON.toJSONString(dto));
        try {
            // 校验令牌
            if (!verifyToken(request.getHeader("Authorization"))) {
                // 校验失败
                return CommonResult.failed(ThirdPartyReturnCodeEnum.TOKEN_ERROR);
            }

            // 校验签名
            if (!verifySignature(dto)) {
                // 签名错误
                return CommonResult.failed(ThirdPartyReturnCodeEnum.SIGN_ERROR);
            }

            // 解析入参
            QueryStationInfoDTO queryStationInfoDTO = parseParamsDTO(dto, QueryStationInfoDTO.class);

            // 执行逻辑
            Map<String, String> map = platformLogic.queryStationsInfo(queryStationInfoDTO);

            return CommonResult.success(0, "查询充电站信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("{}-查询充电站信息 error:", platformName, e);
        }
        return CommonResult.failed("查询充电站信息发生异常");
    }

    /**
     * 联联平台查询充电站状态信息
     * http://localhost:8080/LianLian/v1/query_station_status
     *
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_station_status")
    public CommonResult<?> query_station_status(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("{}-查询充电站状态信息 params:{}", platformName, JSON.toJSONString(dto));
        try {
            // 校验令牌
            if (!verifyToken(request.getHeader("Authorization"))) {
                // 校验失败
                return CommonResult.failed(ThirdPartyReturnCodeEnum.TOKEN_ERROR);
            }

            // 校验签名
            if (!verifySignature(dto)) {
                // 签名错误
                return CommonResult.failed(ThirdPartyReturnCodeEnum.SIGN_ERROR);
            }

            // 解析入参
            QueryStationInfoDTO queryStationInfoDTO = parseParamsDTO(dto, QueryStationInfoDTO.class);

            // 执行逻辑
            Map<String, String> map = platformLogic.queryStationStatus(queryStationInfoDTO);

            return CommonResult.success(0, "查询充电站状态信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("{}-查询充电站状态信息 error:", platformName, e);
        }
        return CommonResult.failed("查询充电站状态信息发生异常");
    }

    /**
     * 查询统计信息
     * http://localhost:8080/LianLian/v1/query_station_stats
     *
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_station_stats")
    public CommonResult<?> query_station_stats(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("{}-查询统计信息 params:{}", platformName, JSON.toJSONString(dto));
        try {
            // 校验令牌
            if (!verifyToken(request.getHeader("Authorization"))) {
                // 校验失败
                return CommonResult.failed(ThirdPartyReturnCodeEnum.TOKEN_ERROR);
            }

            // 校验签名
            if (!verifySignature(dto)) {
                // 签名错误
                return CommonResult.failed(ThirdPartyReturnCodeEnum.SIGN_ERROR);
            }

            // 解析入参
            QueryStationInfoDTO queryStationInfoDTO = parseParamsDTO(dto, QueryStationInfoDTO.class);

            // 执行逻辑
            Map<String, String> map = platformLogic.queryStationStats(queryStationInfoDTO);
            return CommonResult.success(0, "查询统计信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("{}-查询统计信息 error:", platformName, e);
        }
        return CommonResult.failed("查询统计信息发生异常");
    }

    /**
     * 充电站信息变化推送 notification_stationInfo
     * http://localhost:8080/LianLian/notificationStationInfo
     */
    @PostMapping("/notificationStationInfo")
    public RestApiResponse<?> notificationStationInfo(@RequestBody PushInfoParamDTO dto) {
        logger.info("{}-充电站信息变化推送 params:{}", platformName, JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            if (StringUtils.isBlank(String.valueOf(dto.getStationId()))) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            String result = platformLogic.notificationStationInfo(dto.getStationId());
            response = new RestApiResponse<>(result);
        } catch (BusinessException e) {
            logger.error("{}-充电站信息变化推送 error", platformName, e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("{}-充电站信息变化推送 error", platformName, e);
            response = new RestApiResponse<>(e);
        }
        logger.info("{}-充电站信息变化推送 result:{}", platformName, response);
        return response;
    }

    /**
     * 联联平台设备状态变化推送 notification_stationStatus
     * http://localhost:8080/LianLian/notificationStationStatus
     *
     * @param dto
     * @return
     */
    @PostMapping("/notificationStationStatus")
    public RestApiResponse<?> notificationStationStatus(@RequestBody PushInfoParamDTO dto) {
        logger.info("{}-设备状态变化推送 params:{}", platformName, JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            if (StringUtils.isBlank(String.valueOf(dto.getPileConnectorCode())) ||
                    StringUtils.isBlank(String.valueOf(dto.getStatus()))) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            PushRealTimeInfoDTO pushRealTimeInfoDTO = new PushRealTimeInfoDTO();
            pushRealTimeInfoDTO.setStatus(dto.getStatus());
            pushRealTimeInfoDTO.setPileConnectorCode(dto.getPileConnectorCode());
            pushRealTimeInfoDTO.setThirdPartyType(ThirdPlatformTypeEnum.LIAN_LIAN_PLATFORM.getTypeCode());
            String result = platformLogic.notificationStationStatus(pushRealTimeInfoDTO);
            response = new RestApiResponse<>(result);
        } catch (BusinessException e) {
            logger.error("{}-设备状态变化推送 error", platformName, e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("{}-设备状态变化推送 error", platformName, e);
            response = new RestApiResponse<>(e);
        }
        logger.info("{}-设备状态变化推送 result:{}", platformName, response);
        return response;
    }

    /**
     * 站点费率变化推送 notification_stationFee
     * http://localhost:8080/LianLian/notificationStationFee
     */
    @PostMapping("/notificationStationFee")
    public RestApiResponse<?> notificationStationFee(@RequestBody PushInfoParamDTO dto) {
        logger.info("{}-站点费率变化推送 params:{}", platformName, JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            if (StringUtils.isBlank(String.valueOf(dto.getStationId()))) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            String result = platformLogic.notificationStationFee(dto.getStationId());
            response = new RestApiResponse<>(result);
        } catch (BusinessException e) {
            logger.error("{}-站点费率变化推送 error", platformName, e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("{}-站点费率变化推送 error", platformName, e);
            response = new RestApiResponse<>(e);
        }
        logger.info("{}-站点费率变化推送 result:{}", platformName, response);
        return response;
    }

    /**
     * 设备充电中状态变化推送 notification_connector_charge_status
     * http://localhost:8080/LianLian/notificationConnectorChargeStatus
     *
     * @return
     */
    @GetMapping("/notificationConnectorChargeStatus/{orderCode}")
    public RestApiResponse<?> notificationConnectorChargeStatus(@PathVariable("orderCode") String orderCode) {
        logger.info("{}-设备充电中状态变化推送 params:{}", platformName, orderCode);
        RestApiResponse<?> response = null;
        try {
            if (StringUtils.isBlank(orderCode)) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            // String result = lianLianService.pushPileChargeStatusChange(orderCode);
            String result = platformLogic.notificationConnectorChargeStatus(orderCode);
            response = new RestApiResponse<>(result);
        } catch (BusinessException e) {
            logger.error("{}-设备充电中状态变化推送 error", platformName, e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("{}-设备充电中状态变化推送 error", platformName, e);
            response = new RestApiResponse<>(e);
        }
        logger.info("{}-设备充电中状态变化推送 result:{}", platformName, response);
        return response;
    }

    /**
     * 推送订单信息 notification_orderInfo
     * http://localhost:8080/LianLian/notificationOrderInfo/
     *
     * @param orderCode
     * @return
     */
    @GetMapping("/notificationOrderInfo/{orderCode}")
    public RestApiResponse<?> notificationOrderInfo(@PathVariable("orderCode") String orderCode) {
        logger.info("{}-推送订单信息 params:{}", platformName, orderCode);
        RestApiResponse<?> response = null;
        try {
            if (StringUtils.isBlank(orderCode)) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            String result = platformLogic.notificationChargeOrderInfo(orderCode);
            response = new RestApiResponse<>(result);
        } catch (BusinessException e) {
            logger.error("{}-推送订单信息 error", platformName, e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("{}-推送订单信息 error", platformName, e);
            response = new RestApiResponse<>(e);
        }
        logger.info("{}-推送订单信息 result:{}", platformName, response);
        return response;
    }

    /**
     * 请求设备认证
     * http://localhost:8080/LianLian/v1/query_equip_auth
     *
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_equip_auth")
    public CommonResult<?> query_equip_auth(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("{}-请求设备认证 param:{}", platformName, JSON.toJSONString(dto));
        try {
            // 校验令牌
            if (!verifyToken(request.getHeader("Authorization"))) {
                // 校验失败
                return CommonResult.failed(ThirdPartyReturnCodeEnum.TOKEN_ERROR);
            }

            // 校验签名
            if (!verifySignature(dto)) {
                // 签名错误
                return CommonResult.failed(ThirdPartyReturnCodeEnum.SIGN_ERROR);
            }

            // 解析入参
            QueryEquipmentDTO queryEquipmentDTO = parseParamsDTO(dto, QueryEquipmentDTO.class);

            // 执行逻辑
            Map<String, String> map = platformLogic.queryEquipAuth(queryEquipmentDTO);
            return CommonResult.success(0, "请求设备认证成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("{}-请求设备认证 error:", platformName, 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 :{}", platformName, JSON.toJSONString(dto));
        try {
            // 校验令牌
            if (!verifyToken(request.getHeader("Authorization"))) {
                // 校验失败
                return CommonResult.failed(ThirdPartyReturnCodeEnum.TOKEN_ERROR);
            }

            // 校验签名
            if (!verifySignature(dto)) {
                // 签名错误
                return CommonResult.failed(ThirdPartyReturnCodeEnum.SIGN_ERROR);
            }

            // 解析入参
            QueryStartChargeDTO queryStartChargeDTO = parseParamsDTO(dto, QueryStartChargeDTO.class);

            // 执行逻辑
            Map<String, String> map = platformLogic.queryStartCharge(queryStartChargeDTO);

            return CommonResult.success(0, "请求启动充电成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("{}-请求启动充电 error", platformName, e);
        }
        return CommonResult.failed("请求启动充电发生异常");
    }

    /**
     * 查询充电状态
     * http://localhost:8080/LianLian/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 :{}", platformName, JSON.toJSONString(dto));
        try {
            // 校验令牌
            if (!verifyToken(request.getHeader("Authorization"))) {
                // 校验失败
                return CommonResult.failed(ThirdPartyReturnCodeEnum.TOKEN_ERROR);
            }

            // 校验签名
            if (!verifySignature(dto)) {
                // 签名错误
                return CommonResult.failed(ThirdPartyReturnCodeEnum.SIGN_ERROR);
            }

            // 解析入参
            QueryEquipChargeStatusDTO queryEquipChargeStatusDTO = parseParamsDTO(dto, QueryEquipChargeStatusDTO.class);

            // 执行逻辑
            Map<String, String> map = platformLogic.queryEquipChargeStatus(queryEquipChargeStatusDTO);

            return CommonResult.success(0, "查询充电状态成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("{}-查询充电状态 error", platformName, 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 :{}", platformName, JSON.toJSONString(dto));
        try {
            // 校验令牌
            if (!verifyToken(request.getHeader("Authorization"))) {
                // 校验失败
                return CommonResult.failed(ThirdPartyReturnCodeEnum.TOKEN_ERROR);
            }

            // 校验签名
            if (!verifySignature(dto)) {
                // 签名错误
                return CommonResult.failed(ThirdPartyReturnCodeEnum.SIGN_ERROR);
            }

            // 解析入参
            QueryStartChargeDTO queryStartChargeDTO = parseParamsDTO(dto, QueryStartChargeDTO.class);

            // 执行逻辑
            Map<String, String> map = platformLogic.queryStopCharge(queryStartChargeDTO);

            return CommonResult.success(0, "请求停止充电成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("{}-请求停止充电 error", platformName, e);
        }
        return CommonResult.failed("{}-请求停止充电发生异常");
    }


    /**
     * 推送订单结算信息 （联联推给我们）
     *
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v1/notification_order_settlement_info")
    public CommonResult<?> notification_order_settlement_info(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("{}-推送订单结算信息 params:{}", platformName, JSON.toJSONString(dto));
        try {
            // 校验令牌
            if (!verifyToken(request.getHeader("Authorization"))) {
                // 校验失败
                return CommonResult.failed(ThirdPartyReturnCodeEnum.TOKEN_ERROR);
            }

            // 校验签名
            if (!verifySignature(dto)) {
                // 签名错误
                return CommonResult.failed(ThirdPartyReturnCodeEnum.SIGN_ERROR);
            }

            // 解析入参
            PushOrderSettlementDTO pushOrderSettlementDTO = parseParamsDTO(dto, PushOrderSettlementDTO.class);

            // 执行逻辑
            Map<String, String> map = platformLogic.notificationOrderSettlementInfo(pushOrderSettlementDTO);

            return CommonResult.success(0, "推送订单结算信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("{}-推送订单结算信息 error:", platformName, e);
            e.printStackTrace();
        }
        return CommonResult.failed("推送订单结算信息发生异常");
    }

    @GetMapping("/pushStationFee/{stationId}")
    public RestApiResponse<?> pushStationFee(@PathVariable("stationId") String stationId) {
        RestApiResponse<?> response = null;
        try {
            // String result = lianLianService.pushStationFee(stationId);
            String result = platformLogic.notificationStationFee(stationId);
            response = new RestApiResponse<>(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

}
