package com.jsowell.netty.handler;

import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.core.domain.ykc.YKCDataProtocol;
import com.jsowell.common.core.domain.ykc.YKCFrameTypeCode;
import com.jsowell.common.enums.ykc.OrderStatusEnum;
import com.jsowell.common.enums.ykc.StopChargingFailedReasonEnum;
import com.jsowell.common.util.BytesUtil;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.YKCUtils;
import com.jsowell.netty.factory.YKCOperateFactory;
import com.jsowell.pile.domain.OrderBasicInfo;
import com.jsowell.pile.service.IOrderBasicInfoService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 远程停机命令回复
 *
 * @author JS-ZZA
 * @date 2022/9/19 14:37
 */
@Slf4j
@Component
public class RemoteStopChargingRequestHandler extends AbstractHandler{
    private final String type = YKCUtils.frameType2Str(YKCFrameTypeCode.REMOTE_STOP_CHARGING_ANSWER_CODE.getBytes());

    @Autowired
    private IOrderBasicInfoService orderBasicInfoService;

    @Override
    public void afterPropertiesSet() throws Exception {
        YKCOperateFactory.register(type, this);
    }

    @Override
    public byte[] supplyProcess(YKCDataProtocol ykcDataProtocol, Channel channel) {
        log.info("[===远程停机命令回复===] param:{}, channel:{}", JSONObject.toJSONString(ykcDataProtocol), channel.toString());
        // 获取消息体
        byte[] msgBody = ykcDataProtocol.getMsgBody();

        int startIndex = 0;
        int length = 7;

        // 桩编号
        byte[] pileSnByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
        String pileSn = BytesUtil.bcd2Str(pileSnByteArr);

        // 保存时间
        saveLastTime(pileSn);

        // 枪号
        startIndex += length;
        length = 1;
        byte[] connectorCodeByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
        String connectorCode = BytesUtil.bcd2Str(connectorCodeByteArr);

        // 停止结果  0x00失败 0x01成功
        startIndex += length;
        byte[] stopResultByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
        String stopResult = BytesUtil.bcd2Str(stopResultByteArr);

        /**
         * 失败原因
         * 0x00 无
         * 0x01 设备编号不匹配
         * 0x02 枪未处于充电状态
         * 0x03 其他
         */
        startIndex += length;
        byte[] reasonByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
        String reasonCode = BytesUtil.bcd2Str(reasonByteArr);
        String reason = StopChargingFailedReasonEnum.getMsgByCode(reasonCode);

        // 通过桩编号+枪口号 查出订单
        OrderBasicInfo order = orderBasicInfoService.queryChargingByPileSnAndConnectorCode(pileSn, connectorCode);
        if (order != null) {
            // 收到停机回复后，修改订单状态
            if (StringUtils.equals(stopResult, "01")) {
                // 停机成功，修改订单状态为 待结算
                order.setOrderStatus(OrderStatusEnum.STAY_SETTLEMENT.getValue());
                if (order.getChargeEndTime() == null) {
                    order.setChargeEndTime(new Date()); // 结束充电时间
                }
            } else {
                // 停机失败，修改订单状态为 异常
                order.setOrderStatus(OrderStatusEnum.ABNORMAL.getValue());
                order.setReason(reason);
            }
            orderBasicInfoService.updateOrderBasicInfo(order);
        }

        return null;
    }
}
