package com.fs.his.service.impl;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.BeanCopyUtils;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.StringUtils;
import com.fs.course.config.RedPacketConfig;
import com.fs.his.domain.SysRedpacketConfigMore;
import com.fs.his.mapper.SysRedpacketConfigMoreMapper;
import com.fs.his.param.updateChangeMchIdParam;
import com.fs.his.service.ISysRedpacketConfigMoreService;
import com.fs.system.service.ISysConfigService;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.OptionalInt;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 多商户配置Service业务层处理
 *
 * @author fs
 * @date 2025-11-27
 */
@Slf4j
@Service
public class SysRedpacketConfigMoreServiceImpl extends ServiceImpl<SysRedpacketConfigMoreMapper, SysRedpacketConfigMore> implements ISysRedpacketConfigMoreService {


    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询多商户配置
     *
     * @param id 多商户配置主键
     * @return 多商户配置
     */
    @Override
    public SysRedpacketConfigMore selectSysRedpacketConfigMoreById(Long id)
    {
        return baseMapper.selectSysRedpacketConfigMoreById(id);
    }

    @Override
    public Long getRedPacketConFig() {

        String json = redisCache.getCacheObject("sys_config:redPacket.config.new");
        if (StringUtil.isNullOrEmpty(json) || json.isEmpty()) {
            json = configService.selectConfigByKey("redPacket.config");
        }

        RedPacketConfig config   = JSONUtil.toBean(json, RedPacketConfig.class);

        return Long.valueOf(config.getMchId());

    }

    @Override
    public R updateChangeMchId(updateChangeMchIdParam param) {

        SysRedpacketConfigMore configMore = baseMapper.selectOne(new QueryWrapper<SysRedpacketConfigMore>().eq("mch_id", param.getNewChangeMchId()));

        if (configMore == null || configMore.getMchId() == null) {
            return R.error("商户号不存在");
        }

        RedPacketConfig config = new RedPacketConfig();
        BeanCopyUtils.copy(configMore,config);

        if (config.getMchId()!=null){
            redisCache.setCacheObject("sys_config:redPacket.config.new", JSONUtil.toJsonStr(config));
            redisCache.deleteObject("sys_config:redPacket.config.newCount");
        }

        return R.ok();
    }

    @Override
    public void changeRedPacketConfig() {
        Integer count = redisCache.getCacheObject("sys_config:redPacket.config.newCount");
        if (count >= 1000) {
            String json = redisCache.getCacheObject("sys_config:redPacket.config.new");
            if (StringUtil.isNullOrEmpty(json) || json.isEmpty()) {
                json = configService.selectConfigByKey("redPacket.config");
            }

            RedPacketConfig config   = JSONUtil.toBean(json, RedPacketConfig.class);

            SysRedpacketConfigMore configMore = baseMapper.selectOne(new QueryWrapper<SysRedpacketConfigMore>().eq("mch_id", config.getMchId()));

            if (configMore == null) {
                log.error("获取不到商户号");
                return;
            }

            List<SysRedpacketConfigMore> configMoreList = baseMapper.selectList(
                    new QueryWrapper<SysRedpacketConfigMore>().orderByAsc("id")
            );

            // 空列表处理
            if (configMoreList.isEmpty()) {
                log.error("商户号列表为空");
            }


            // 查找当前元素的索引
            int currentIndex = -1;
            Long currentId = configMore != null ? configMore.getId() : null;

            for (int i = 0; i < configMoreList.size(); i++) {
                if (configMoreList.get(i).getId().equals(currentId)) {
                    currentIndex = i;
                    break;
                }
            }

            // 计算下一个索引（使用取模实现循环）
            int nextIndex = (currentIndex + 1) % configMoreList.size();

            SysRedpacketConfigMore configMoreNew = configMoreList.get(nextIndex);


            RedPacketConfig configNew = new RedPacketConfig();
            BeanCopyUtils.copy(configMoreNew,configNew);

            if (configNew.getMchId()!=null){
                log.info("自动切换商户号-原："+configMore.getMchId()+"-新："+configNew.getMchId());
                redisCache.setCacheObject("sys_config:redPacket.config.new", JSONUtil.toJsonStr(configNew));
                redisCache.deleteObject("sys_config:redPacket.config.newCount");
            }
        }
    }




    /**
     * 查询多商户配置列表
     *
     * @param sysRedpacketConfigMore 多商户配置
     * @return 多商户配置
     */
    @Override
    public List<SysRedpacketConfigMore> selectSysRedpacketConfigMoreList(SysRedpacketConfigMore sysRedpacketConfigMore)
    {
        return baseMapper.selectSysRedpacketConfigMoreList(sysRedpacketConfigMore);
    }

    /**
     * 新增多商户配置
     *
     * @param sysRedpacketConfigMore 多商户配置
     * @return 结果
     */
    @Override
    public int insertSysRedpacketConfigMore(SysRedpacketConfigMore sysRedpacketConfigMore)
    {
        return baseMapper.insertSysRedpacketConfigMore(sysRedpacketConfigMore);
    }

    /**
     * 修改多商户配置
     *
     * @param sysRedpacketConfigMore 多商户配置
     * @return 结果
     */
    @Override
    public int updateSysRedpacketConfigMore(SysRedpacketConfigMore sysRedpacketConfigMore)
    {
        return baseMapper.updateSysRedpacketConfigMore(sysRedpacketConfigMore);
    }

    /**
     * 批量删除多商户配置
     *
     * @param ids 需要删除的多商户配置主键
     * @return 结果
     */
    @Override
    public int deleteSysRedpacketConfigMoreByIds(Long[] ids)
    {
        return baseMapper.deleteSysRedpacketConfigMoreByIds(ids);
    }

    /**
     * 删除多商户配置信息
     *
     * @param id 多商户配置主键
     * @return 结果
     */
    @Override
    public int deleteSysRedpacketConfigMoreById(Long id)
    {
        return baseMapper.deleteSysRedpacketConfigMoreById(id);
    }
}
