package com.njcn.msgpush.module.push.service.channel;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.stream.CollectorUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.msgpush.framework.common.util.object.PageUtils;
import com.njcn.msgpush.module.push.controller.admin.channel.vo.ChannelProviderConfigReqVO;
import com.njcn.msgpush.module.push.dal.dataobject.channel.ChannelProviderConfigDO;
import com.njcn.msgpush.module.push.dal.mysql.channel.ChannelProviderConfigMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import static com.njcn.msgpush.framework.common.exception.util.ServiceExceptionUtil.invalidParamException;

@Service
public class ChannelProviderConfigServiceImpl extends ServiceImpl<ChannelProviderConfigMapper, ChannelProviderConfigDO> implements ChannelProviderConfigService {

    @Override
    public Page<ChannelProviderConfigDO> getPage(ChannelProviderConfigReqVO reqVO) {
        QueryWrapper<ChannelProviderConfigDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ChannelProviderConfigDO::getChannel, reqVO.getChannel());
        return this.page(new Page<>(PageUtils.getPageNum(reqVO), PageUtils.getPageSize(reqVO)), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChannelProviderConfigDO toggleEnableField(String id) {
        ChannelProviderConfigDO channelProviderConfigDO = this.getById(id);
        if (channelProviderConfigDO == null) {
            throw invalidParamException("渠道服务商配置不存在，id={}", id);
        }

        boolean enable = !Integer.valueOf(1).equals(channelProviderConfigDO.getEnabled());
        if (enable) {
            this.lambdaUpdate()
                    .eq(ChannelProviderConfigDO::getChannel, channelProviderConfigDO.getChannel())
                    .ne(ChannelProviderConfigDO::getId, channelProviderConfigDO.getId())
                    .set(ChannelProviderConfigDO::getEnabled, 0)
                    .update();
        } else {
            long enabledCount = this.lambdaQuery()
                    .eq(ChannelProviderConfigDO::getChannel, channelProviderConfigDO.getChannel())
                    .eq(ChannelProviderConfigDO::getEnabled, 1)
                    .count();
            if (enabledCount <= 1) {
                throw invalidParamException("渠道 {} 必须保留一个启用服务商，请先启用其它服务商后再禁用当前配置", channelProviderConfigDO.getChannel());
            }
        }

        channelProviderConfigDO.setEnabled(enable ? 1 : 0);
        this.updateById(channelProviderConfigDO);
        return channelProviderConfigDO;
    }

    @Override
    public ChannelProviderConfigDO getByTypeAndChannel(String providerType, String channel) {
        return this.lambdaQuery().eq(ChannelProviderConfigDO::getProviderType, providerType)
                .eq(ChannelProviderConfigDO::getChannel, channel)
                .one();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void failureUpdate(String providerType, String channel) {
        ChannelProviderConfigDO byTypeAndChannel = this.getByTypeAndChannel(providerType, channel);
        byTypeAndChannel.setFailureCount(byTypeAndChannel.getFailureCount() + 1);
        byTypeAndChannel.setLastFailureTime(LocalDateTime.now());
        byTypeAndChannel.setHealthStatus(byTypeAndChannel.getFailureCount() > 5 ? 0 : 1);
        this.updateById(byTypeAndChannel);
    }

    @Override
    public void successUpdate(String providerType, String channel) {
        ChannelProviderConfigDO byTypeAndChannel = this.getByTypeAndChannel(providerType, channel);
        byTypeAndChannel.setFailureCount(0);
        byTypeAndChannel.setLastFailureTime(null);
        byTypeAndChannel.setHealthStatus(1);
        this.updateById(byTypeAndChannel);
    }

    @Override
    public List<ChannelProviderConfigDO> getEnabledProviders(String channel) {
        return this.lambdaQuery()
                .eq(ChannelProviderConfigDO::getChannel, channel)
                .eq(ChannelProviderConfigDO::getEnabled, 1)
                .list();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<String> ids) {
        List<ChannelProviderConfigDO> configs = this.listByIds(ids);
        List<ChannelProviderConfigDO> enabledConfigs = configs.stream()
                .filter(config -> Integer.valueOf(1).equals(config.getEnabled()))
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(enabledConfigs)) {
            String channels = enabledConfigs.stream()
                    .map(ChannelProviderConfigDO::getChannel)
                    .distinct()
                    .collect(Collectors.joining(","));
            throw invalidParamException("启用中的服务商配置禁止删除，请先禁用后再删除。涉及渠道：{}", channels);
        }
        return this.removeBatchByIds(ids);
    }
}
