package com.xhpc.pp.logic;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xhpc.common.api.PileOrderService;
import com.xhpc.common.data.up.RemoteStopReplyData;
import com.xhpc.pp.tx.ServiceParameter;
import com.xhpc.pp.tx.ServiceResult;
import com.xhpc.pp.tx.logic.ServiceLogic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.pp.tx.ServiceResult.HEX_01;

@Lazy
@Component("RemoteStopReplyDataLogic")
public class RemoteStopReplyDataLogic implements ServiceLogic {

    private static Logger log = LoggerFactory.getLogger(RemoteStopReplyDataLogic.class);

    @Autowired
    private PileOrderService pileOrderService;
    private static String[] frs = {"无", "设备编号不匹配", "枪未处于充电状态", "其他"};

    @Override
    public ServiceResult service(ServiceParameter sp) throws Exception {
//        log.error("=====0X35=====getServiceName================"+sp.getServiceName());
//        log.error("=====0X35=====getPileNo================"+sp.getPileNo());
//        log.error("=====0X35=====getParameters================"+sp.getParameters());
//        log.error("=====0X35=====getVersion================"+sp.getVersion());
        Map<String, Object> req = sp.getParameters();
        ObjectMapper objectMapper = new ObjectMapper();
        RemoteStopReplyData remoteStopReplyData = objectMapper.convertValue(req, RemoteStopReplyData.class);
        String gunkey = "gun:".concat(remoteStopReplyData.getPileNo()).concat(remoteStopReplyData.getGunId());
        Map<String, Object> cacheGun = REDIS.getCacheMap(gunkey);
        String orderkey = (String) cacheGun.get("orderkey");
        if (orderkey != null) {
            Map<String, Object> cacheOrder = REDIS.getCacheMap(orderkey);
            String stopResult = remoteStopReplyData.getStopResult();
            cacheOrder.put("stopResult", stopResult);
            REDIS.setCacheMap(orderkey, cacheOrder);
            String orderNo = orderkey.replace("order:", "");
            if (HEX_01.equals(remoteStopReplyData.getStopResult())) {
                pileOrderService.pileStop(orderNo, 1, "停止充电成功");
            } else {
                pileOrderService.pileStop(orderNo, 2, frs[Integer.parseInt(remoteStopReplyData.getFailReason())]);
            }
        }
        return new ServiceResult(false);
    }

}
