package com.kym.service.impl;

import com.github.yulichang.base.MPJBaseServiceImpl;
import com.kym.entity.FaultSubscriber;
import com.kym.mapper.FaultSubscriberMapper;
import com.kym.service.FaultSubscriberService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class FaultSubscriberServiceImpl extends MPJBaseServiceImpl<FaultSubscriberMapper, FaultSubscriber> implements FaultSubscriberService {

    @Override
    @Transactional
    public void subscribe(String openid, String stationId) {
        var existing = lambdaQuery()
                .eq(FaultSubscriber::getOpenid, openid)
                .eq(FaultSubscriber::getStationId, stationId)
                .one();

        if (existing != null) {
            existing.setStatus(FaultSubscriber.STATUS_已订阅);
            existing.setSubscribeTime(LocalDateTime.now());
            existing.setUnbindTime(null);
            updateById(existing);
        } else {
            var subscriber = new FaultSubscriber()
                    .setOpenid(openid)
                    .setStationId(stationId)
                    .setStatus(FaultSubscriber.STATUS_已订阅)
                    .setSubscribeTime(LocalDateTime.now());
            save(subscriber);
        }
    }

    @Override
    @Transactional
    public void unsubscribe(String openid, String stationId) {
        lambdaUpdate()
                .set(FaultSubscriber::getStatus, FaultSubscriber.STATUS_已解绑)
                .set(FaultSubscriber::getUnbindTime, LocalDateTime.now())
                .eq(FaultSubscriber::getOpenid, openid)
                .eq(FaultSubscriber::getStationId, stationId)
                .update();
    }

    @Override
    public List<String> getSubscribedOpenids(String stationId) {
        return lambdaQuery()
                .select(FaultSubscriber::getOpenid)
                .eq(FaultSubscriber::getStationId, stationId)
                .eq(FaultSubscriber::getStatus, FaultSubscriber.STATUS_已订阅)
                .list()
                .stream()
                .map(FaultSubscriber::getOpenid)
                .toList();
    }

    @Override
    @Transactional
    public String toggleSubscription(String openid, String stationId) {
        var existing = lambdaQuery()
                .eq(FaultSubscriber::getOpenid, openid)
                .eq(FaultSubscriber::getStationId, stationId)
                .one();

        if (existing != null && existing.getStatus() == FaultSubscriber.STATUS_已订阅) {
            unsubscribe(openid, stationId);
            return "解绑成功";
        } else {
            subscribe(openid, stationId);
            return "绑定成功";
        }
    }
}
