package com.xhpc.pp.logic;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xhpc.common.api.PileOrderService;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.data.up.ReturnGunGecord;
import com.xhpc.common.enums.StationDeviceEnum;
import com.xhpc.pp.domain.XhpcDeviceMessage;
import com.xhpc.pp.mapper.XhpcDeviceMessageMapper;
import com.xhpc.pp.tx.ServiceParameter;
import com.xhpc.pp.tx.ServiceResult;
import com.xhpc.pp.tx.logic.ServiceLogic;
import com.xhpc.pp.utils.HexUtils;
import com.xhpc.pp.utils.security.CRCCalculator;
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 javax.annotation.Resource;
import java.util.Map;

/**
 * 归枪记录
 *
 * @author yuyang
 * @Date 2026-02-12 10:13
 */
@Lazy
@Component("ReturnGunGecordLogic")
public class ReturnGunGecordLogic implements ServiceLogic {

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

    @Autowired
    private PileOrderService pileOrderService;
    @Resource
    XhpcDeviceMessageMapper deviceMessageMapper;

    @Override
    public ServiceResult service(ServiceParameter sp) throws Exception {

        Map<String, Object> req = sp.getParameters();
        ObjectMapper objectMapper = new ObjectMapper();
        ReturnGunGecord returnGunGecord = objectMapper.convertValue(req, ReturnGunGecord.class);

        pileOrderService.getReturnGunRecord(returnGunGecord.getOrderNo(),returnGunGecord.getStartTime(),returnGunGecord.getEndTime());

        XhpcDeviceMessage deviceMessage = new XhpcDeviceMessage();
        deviceMessage.setType(StationDeviceEnum.PILE.getCode());
        deviceMessage.setSerialNumber(sp.getPileNo());
        deviceMessage.setRemark("归枪记录");
        deviceMessage.setStatus(0);
        deviceMessage.setContent((String) req.get("hex"));
        deviceMessage.setChargeOrderNo((String) req.get("orderNo"));
        deviceMessageMapper.insertByDomain(deviceMessage);

        R r = null;
        String orderNo = returnGunGecord.getOrderNo();
        if (!orderNo.equals("00000000000000000000000000000000")) r = pileOrderService.pileEndOrder(orderNo);

        String resultStr = "680E".concat(req.get("seqhex").toString()).concat("004A").concat(orderNo);
        if ((r != null && r.getCode() == 200) || (r != null && r.getMsg() != null && r.getMsg().contains("重复结算"))) {
            resultStr = resultStr.concat(ServiceResult.HEX_00);
            resultStr = resultStr.concat(CRCCalculator.calcCrc(resultStr));
            return new ServiceResult(HexUtils.toBytes(resultStr), ServiceResult.OK);
        } else {
            resultStr = resultStr.concat(ServiceResult.HEX_01);
            resultStr = resultStr.concat(CRCCalculator.calcCrc(resultStr));
            return new ServiceResult(HexUtils.toBytes(resultStr), ServiceResult.FAIL);
        }
    }
}
