package com.xhpc.evcs.ykc.api;

import com.xhpc.evcs.cdjgpc.dto.CDEquipAuthRequest;
import com.xhpc.evcs.domain.XhpcInternetUser;
import com.xhpc.evcs.domain.XhpcStationInternetBlacklist;
import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.dto.CommonResponse;
import com.xhpc.evcs.dto.EquipAuthResponse;
import com.xhpc.evcs.encryption.EvcsConst;
import com.xhpc.evcs.jpa.XhpcInternetUserRepository;
import com.xhpc.evcs.jpa.XhpcStationInternetBlacklistRepository;
import com.xhpc.evcs.utils.JSONUtil;
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.time.Instant;
import java.util.Map;

import static cn.hutool.core.util.NumberUtil.isInteger;
import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;

/**
 * 云快充
 *
 * @author yuyang
 * @Date 2026-03-17 13:34
 */
@RestController
public class YKCQueryEquipAuthController {


    @Autowired
    private XhpcStationInternetBlacklistRepository xhpcStationInternetBlacklistRepo;
    @Autowired
    private XhpcInternetUserRepository xhpcInternetUserRepository;

    /**
     *  请求设备认证
     * @param commonRequest
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/v50/query_equip_auth")
    public CommonResponse queryEquipAuth(@RequestBody CommonRequest<CDEquipAuthRequest> commonRequest) throws Exception {

        CommonResponse resp = new CommonResponse();
        resp.setRet(EvcsConst.RET_SUCC);
        CDEquipAuthRequest equipAuthRequest = JSONUtil.readParams(commonRequest.getData(), CDEquipAuthRequest.class);
        if (equipAuthRequest == null) {
            resp.setRet(EvcsConst.RET_FAIL);
            resp.setMsg("Request or token params validation failed");
        } else {
            EquipAuthResponse equipAuthResponse = new EquipAuthResponse();
            String equipAuthSeq = equipAuthRequest.getEquipAuthSeq();
            String connectorId = equipAuthRequest.getConnectorId();
            equipAuthResponse.setEquipAuthSeq(equipAuthSeq);
            equipAuthResponse.setConnectorId(connectorId);
            String pileId = connectorId.substring(0, connectorId.length() - 2);
            Map<String, Object> pileDataModel = REDIS.getCacheMap("pile:" + pileId);
            Long stationId = Long.parseLong(pileDataModel.get("stationId").toString());
            Instant now = Instant.now();
            XhpcInternetUser xhpcInternetUser = xhpcInternetUserRepository
                    .findByOperatorIdEvcsLikeAndCooperationStartTimeBeforeAndCooperationEndTimeAfter(commonRequest.getOperatorId(), now, now);
            if (xhpcInternetUser == null) {
                equipAuthResponse.setSuccStat(1);
                equipAuthResponse.setFailReason(2);
                equipAuthResponse.setFailReasonMsg("身份验证失败");
                resp.setMsg("auth denied");
            } else {
                Long internetUserId = xhpcInternetUser.getInternetUserId();
                XhpcStationInternetBlacklist xhpcStationInternetBlacklist =
                        xhpcStationInternetBlacklistRepo.findByChargingStationIdAndInternetUserId(stationId, internetUserId).orElse(null);
                if (null != xhpcStationInternetBlacklist) {
                    equipAuthResponse.setSuccStat(1);
                    equipAuthResponse.setFailReason(2);
                    equipAuthResponse.setFailReasonMsg("身份验证失败");
                    resp.setMsg("auth denied");
                } else {
                    Map<String, Object> cacheGun = REDIS.getCacheMap("gun:".concat(connectorId));
                    String terminalStatus = (String) cacheGun.get("vehicleGunStatus");
                    String status = (String) cacheGun.get("status");
                    if (!"空闲".equals(status)) {
                        resp.setMsg("终端不在空闲状态:[".concat(status == null ? "未注册" : isInteger(status) ? "充电中" : status).concat(
                                "]"));
                        equipAuthResponse.setSuccStat(1);
                        equipAuthResponse.setFailReason(1);
                    } else if ("否".equals(terminalStatus)) {
                        resp.setMsg("未插枪");
                        equipAuthResponse.setSuccStat(1);
                        equipAuthResponse.setFailReason(1);
                    } else {
                        resp.setRet("0");
                        resp.setMsg("success");
                        equipAuthResponse.setSuccStat(0);
                        equipAuthResponse.setFailReason(0);
                    }

                }
            }
            resp.setData(JSONUtil.toJSONString(equipAuthResponse));
        }
        return resp;
    }


}
