package com.xhpc.pp.logic;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xhpc.common.data.up.PileTimeConfigReplyData;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static cn.hutool.core.date.DatePattern.NORM_DATETIME_FORMAT;
import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.pp.utils.security.CP56Time2a.cp56toDate;

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

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

    @Resource
    XhpcDeviceMessageMapper deviceMessageMapper;

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

        Map<String, Object> req = sp.getParameters();
        ObjectMapper objectMapper = new ObjectMapper();
        PileTimeConfigReplyData pileTimeConfigReplyData = objectMapper.convertValue(req, PileTimeConfigReplyData.class);
        String pileNo = (String) req.get("pileNo");
        String pk = "pile:".concat(pileNo);
        String configTime = DateUtil.format(cp56toDate(pileTimeConfigReplyData.getSetTime()), NORM_DATETIME_FORMAT);
        String configTimeReply = pk.concat(".configTimeReply");
        REDIS.setCacheObject(configTimeReply, "校时设置成功:".concat(configTime), 30L, TimeUnit.MINUTES);
        log.debug("({}) set time success√: [{}]", pileNo, configTime);
        String remark = "充电桩同步时钟";
        XhpcDeviceMessage deviceMessage = new XhpcDeviceMessage();
        deviceMessage.setType(StationDeviceEnum.PILE.getCode());
        deviceMessage.setSerialNumber(sp.getPileNo());
        deviceMessage.setRemark(remark);
        deviceMessage.setStatus(0);
        deviceMessage.setContent((String) req.get("hex"));
        deviceMessageMapper.insertByDomain(deviceMessage);

        return new ServiceResult(false);
    }

}
