package com.imdroid.beidou_ehm.simcard;

import com.imdroid.secapi.dto.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class TrafficCardService {

    @Autowired
    private TrafficCardMapper trafficCardMapper;

    @Autowired
    private TrafficDeviceMappingMapper mappingMapper;

    @Autowired
    private GnssDeviceMapper deviceMapper;

    @Transactional
    public boolean checkAndHandleICCIDChanges(GnssStatusJoin device) {
        if (device == null || device.getIccid() == null || device.getIccid().trim().isEmpty()) {
            return false;
        }

        String currentIccid = device.getIccid().trim();

        // 查询当前设备的活跃映射记录
        TrafficDeviceMapping activeMapping = mappingMapper.findActiveByDeviceId(device.getDeviceid());
        if (activeMapping == null) {
            // 第一次为设备创建映射
            createNewMapping(device.getDeviceid(), currentIccid);
            return true;
        } else if (!currentIccid.equals(activeMapping.getIccid())) {
            // ICCID变更，关闭旧映射，创建新映射
            closeExistingMapping(activeMapping);
            createNewMapping(device.getDeviceid(), currentIccid);

             // 重置MSISDN以强制更新SIM卡号
             // 换卡了必须重置这些内容，否则会显示旧卡号，后续的查询会出现问题
            resetCardMsisdn(currentIccid);
            return true;
        }

        return false;
    }

    public TrafficCard getOrCreateTrafficCard(String iccid) {
        TrafficCard card = trafficCardMapper.findByIccid(iccid);

        if (card == null) {
            card = new TrafficCard();
            card.setIccid(iccid);
            card.setMsisdn("");
            card.setStatus(TrafficCard.STATUS_UNKNOWN);
            card.setRemaining(0);
            card.setTotal(0);
            card.setUsed(0);
            card.setUpdatetime(new Date());
            card.setQuerystatus(TrafficCard.QUERY_STATUS_NORMAL);
            trafficCardMapper.insert(card);
        }

        return card;
    }

    @Transactional
    public void updateDeviceSimMapping(String deviceId, String iccid) {
        getOrCreateTrafficCard(iccid);

        // 查询现有映射
        TrafficDeviceMapping activeMapping = mappingMapper.findActiveByDeviceId(deviceId);

        if (activeMapping != null) {
            // 如果ICCID变化，关闭现有映射并创建新映射
            if (!iccid.equals(activeMapping.getIccid())) {
                closeExistingMapping(activeMapping);
                createNewMapping(deviceId, iccid);
            }
        } else {
            // 没有现有映射，创建新映射
            createNewMapping(deviceId, iccid);
        }
    }

    public void markCardAsNotCurrentVendor(String iccid) {
        trafficCardMapper.updateQueryStatus(iccid, TrafficCard.QUERY_STATUS_NOT_CURRENT_VENDOR);
    }

    public void markCardAsQueryFailed(String iccid) {
        trafficCardMapper.updateQueryStatus(iccid, TrafficCard.QUERY_STATUS_OTHER_ERROR);
    }

    private void createNewMapping(String deviceId, String iccid) {
        TrafficDeviceMapping newMapping = new TrafficDeviceMapping();
        newMapping.setDeviceid(deviceId);
        newMapping.setIccid(iccid);
        newMapping.setStarttime(new Date());
        newMapping.setEndtime(null);
        mappingMapper.insert(newMapping);
    }

    private void closeExistingMapping(TrafficDeviceMapping mapping) {
        mappingMapper.endMapping(mapping.getId());
    }

    public void resetCardMsisdn(String iccid) {
        TrafficCard card = trafficCardMapper.findByIccid(iccid);
        if (card != null && card.getMsisdn() != null && !card.getMsisdn().isEmpty()) {
            card.setMsisdn("");
            trafficCardMapper.updateCardInfo(card);
        }
    }
}