package com.xhpc.evcs.cwj.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.xhpc.common.api.PowerPileService;
import com.xhpc.common.core.domain.R;
import com.xhpc.evcs.domain.EtOrderMapping;
import com.xhpc.evcs.domain.XhpcChargingPile;
import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.dto.CommonResponse;
import com.xhpc.evcs.dto.QueryStopChargeRequest;
import com.xhpc.evcs.dto.QueryStopChargeResponse;
import com.xhpc.evcs.encryption.EvcsConst;
import com.xhpc.evcs.jpa.OrderMappingRepository;
import com.xhpc.evcs.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
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.RestController;

import java.io.IOException;
import java.util.Map;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;

/**
 * @author yuyang
 * @Date 2025-07-16 17:26
 */
@Slf4j
@RestController
public class CWJQueryStopChargeController {
    @Autowired
    PowerPileService powerPileService;
    //三方订单与redis内部订单映射表
    @Autowired
    private OrderMappingRepository etOrderMappingRepo;

    @Autowired
    private com.xhpc.evcs.jpa.XhpcChargingPileRepository XhpcChargingPileRepository;

    /**
     * 请求停止充电
     * @param commonRequest
     * @return
     * @throws IOException
     */
    @PostMapping("/v40/query_stop_charge")
    public CommonResponse queryStopCharge(@RequestBody CommonRequest<QueryStopChargeRequest> commonRequest) throws IOException {

        CommonResponse commonResponse = new CommonResponse();
        commonResponse.setRet(EvcsConst.RET_FAIL);
        QueryStopChargeRequest queryStopChargeRequest = JSONUtil.readParams(commonRequest.getData(),
                QueryStopChargeRequest.class);
        if (queryStopChargeRequest == null) {
            commonResponse.setMsg("Request or token params validation failed");
        } else {
            // evcs电订单号(27位)
            String startChargeSeq = queryStopChargeRequest.getStartChargeSeq();
            QueryStopChargeResponse queryStopChargeResponse = new QueryStopChargeResponse();
            queryStopChargeResponse.setStartChargeSeq(startChargeSeq);
            //判断三方的订单号是否存在
            EtOrderMapping etOrderMapping = etOrderMappingRepo.findByEvcsOrderNo(startChargeSeq).orElse(null);
            if (etOrderMapping == null) {
                return failCommonResponse(queryStopChargeResponse, "错误的充电订单号");
            }
            String xhOrderNo = etOrderMapping.getXhOrderNo();
            String pushOrderkey = "pushOrder:".concat(xhOrderNo);
            Map<String, Object> pushOrder = REDIS.getCacheMap(pushOrderkey);
            if (pushOrder == null || (pushOrder.get("isStopNotified") != null && (Boolean) pushOrder.get("isStopNotified"))) {
                return failCommonResponse(queryStopChargeResponse, "已下发停止充电指令");
            }
            //充电设备接口编码（枪编码）
            String connectorId = queryStopChargeRequest.getConnectorId();
            String pileNum = connectorId.substring(0, connectorId.length() - 2);
            //从数据库中查询对应的桩的版本信息
            XhpcChargingPile pileInfo = XhpcChargingPileRepository.findBySerialNumber(pileNum).orElse(null);
            String versionNum = pileInfo.getCommunicationProtocolVersion() != null ?
                    pileInfo.getCommunicationProtocolVersion() :
                    "0A";
            //给对应的枪发送停止充电指令
            // System.out.println("=================22========给对应的枪发送停止充电指令==================停止 充电=================="+xhOrderNo);
            // System.out.println("=================22========给对应的枪发送停止充电指令==================停止 充电=================="+xhOrderNo);

            R r = powerPileService.stopCharging(xhOrderNo, pileNum, connectorId, versionNum);
            // 判断停止指令发送是否成功
            if (r.getCode() != 200) {
                //向redis中放入停止充电指令没有下发成功的标识
                REDIS.setCacheMap(pushOrderkey, pushOrder);
                //充电订单状态
                queryStopChargeResponse.setStartChargeSeqStat(5);
                //操作结果
                queryStopChargeResponse.setSuccStat(1);
                //失败原因
                String errorMsg = r.getMsg();
                if (errorMsg.contains("未注册")) {
                    queryStopChargeResponse.setFailReasonMsg("此设备不存在");
                    queryStopChargeResponse.setFailReason(1);
                }
                if (errorMsg.contains("离线")) {
                    queryStopChargeResponse.setFailReasonMsg("此设备离线");
                    queryStopChargeResponse.setFailReason(2);
                }
                if (errorMsg.contains("订单号")) {
                    //4 means error orderNumber
                    queryStopChargeResponse.setFailReasonMsg("订单号不正确");
                    queryStopChargeResponse.setFailReason(4);
                }
                if (errorMsg.contains("端口")) {
                    //5 means port is not charging
                    queryStopChargeResponse.setFailReasonMsg("端口不在充电中");
                    queryStopChargeResponse.setFailReason(5);
                }
                queryStopChargeResponse.setStartChargeSeqStat(4);
                queryStopChargeResponse.setSuccStat(1);
                String data = JSONUtil.toJSONString(queryStopChargeResponse);
                commonResponse.setMsg("请求停止充电失败");
                commonResponse.setData(data);
                return commonResponse;
            }
            //设置该订单已经被停止的标识
            Map<String, Object> order = REDIS.getCacheMap("order:" + xhOrderNo);
            order.replace("status", "已结束");
            REDIS.setCacheMap("order:".concat(xhOrderNo), order);
            REDIS.setCacheMap(pushOrderkey, pushOrder);
            queryStopChargeResponse.setStartChargeSeqStat(3);
            queryStopChargeResponse.setSuccStat(0);
            queryStopChargeResponse.setFailReason(0);
            String data = JSONUtil.toJSONString(queryStopChargeResponse);
            commonResponse.setRet("0");
            commonResponse.setMsg("请求停止充电成功");
            commonResponse.setData(data);
        }
        return commonResponse;
    }

    private CommonResponse failCommonResponse(QueryStopChargeResponse queryStopChargeResponse, String msg) throws JsonProcessingException {

        queryStopChargeResponse.setStartChargeSeqStat(5);
        queryStopChargeResponse.setSuccStat(1);
        queryStopChargeResponse.setFailReason(0);
        String data = JSONUtil.toJSONString(queryStopChargeResponse);
        CommonResponse commonResponse = new CommonResponse();
        commonResponse.setRet("500");
        commonResponse.setMsg(msg);
        commonResponse.setData(data);
        return commonResponse;
    }

}
