package com.ruoyi.jarvis.service.impl;

import com.ruoyi.jarvis.service.IPhoneReplaceConfigService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson2.JSON;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 手机号替换配置Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class PhoneReplaceConfigServiceImpl implements IPhoneReplaceConfigService 
{
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // Redis key前缀
    private static final String REDIS_KEY_PREFIX = "phone_replace_config:";
    // 循环索引key前缀
    private static final String CYCLE_INDEX_KEY_PREFIX = "phone_cycle_index:";

    @Override
    public List<String> getPhoneList(String type) {
        if (stringRedisTemplate == null) {
            return new ArrayList<>();
        }
        try {
            String key = REDIS_KEY_PREFIX + type;
            String value = stringRedisTemplate.opsForValue().get(key);
            if (value == null || value.isEmpty()) {
                return new ArrayList<>();
            }
            return JSON.parseArray(value, String.class);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    @Override
    public int setPhoneList(String type, List<String> phoneList) {
        if (stringRedisTemplate == null) {
            return 0;
        }
        try {
            String key = REDIS_KEY_PREFIX + type;
            if (phoneList == null || phoneList.isEmpty()) {
                stringRedisTemplate.delete(key);
            } else {
                String value = JSON.toJSONString(phoneList);
                stringRedisTemplate.opsForValue().set(key, value);
            }
            return 1;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public int addPhone(String type, String phone) {
        List<String> phoneList = getPhoneList(type);
        if (!phoneList.contains(phone)) {
            phoneList.add(phone);
            return setPhoneList(type, phoneList);
        }
        return 1;
    }

    @Override
    public int removePhone(String type, String phone) {
        List<String> phoneList = getPhoneList(type);
        phoneList.remove(phone);
        return setPhoneList(type, phoneList);
    }

    @Override
    public String getNextPhone(String type, String originalPhone) {
        List<String> phoneList = getPhoneList(type);
        if (phoneList == null || phoneList.isEmpty()) {
            return originalPhone;
        }
        
        if (stringRedisTemplate == null) {
            // 如果没有Redis，使用简单的轮询（基于时间戳）
            int index = (int) (System.currentTimeMillis() % phoneList.size());
            return phoneList.get(index);
        }
        
        try {
            String sequenceKey = CYCLE_INDEX_KEY_PREFIX + type;
            Long index = stringRedisTemplate.opsForValue().increment(sequenceKey);
            if (index == null) {
                // 如果获取失败，使用时间戳
                int idx = (int) (System.currentTimeMillis() % phoneList.size());
                return phoneList.get(idx);
            }
            
            int phoneIndex = (int) ((index - 1) % phoneList.size());
            String phone = phoneList.get(phoneIndex) != null ? phoneList.get(phoneIndex) : originalPhone;
            
            // 当完成一轮循环后，重置索引为0
            if (index % phoneList.size() == 0) {
                stringRedisTemplate.opsForValue().set(sequenceKey, "0");
            }
            
            return phone;
        } catch (Exception e) {
            // 异常时使用时间戳方式
            int idx = (int) (System.currentTimeMillis() % phoneList.size());
            return phoneList.get(idx);
        }
    }
}

