package com.hzjt.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzjt.domain.Ftp;
import com.hzjt.util.RedisEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * ftp地址获取工具服务类
 * @author cp
 */
@Slf4j
@Service
public class FtpService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private List<Ftp> ftpList;
    @Autowired
    CacheLoadService cacheLoadService;
    @Autowired
    public FtpService(StringRedisTemplate stringRedisTemplate) {
        try {
            this.ftpList = getFtpList(stringRedisTemplate.opsForValue().get(RedisEnum.FTPLIST.getValue()));
        }catch (Exception e){
            log.error("ftpList获取失败:"+e.toString());
        }
    }

    public Ftp reloadFtp() {
        try {
            if(null==stringRedisTemplate.opsForValue().get(RedisEnum.FTPLIST.getValue())){
                cacheLoadService.loadFtpCache();
            }
            ftpList = getFtpList(stringRedisTemplate.opsForValue().get(RedisEnum.FTPLIST.getValue()));
        }catch (Exception e){
            log.error("ftpList获取失败:"+e.toString());
        }

        Long count = null;
        try {
            count = stringRedisTemplate.opsForValue().increment(RedisEnum.FTPLIST_INDEX.getValue(), 1L);
        } catch (Exception e) {
            log.error("获取redis FtpIndex异常" + e.toString());
        }
        if (count == null) {
            count = 0L;
        }
        long index = count % ftpList.size();
        return ftpList.get((int) index);
    }

    private List<Ftp> getFtpList(String ftpJson) {
        JSONArray jsonArr = JSONObject.parseArray(ftpJson);
        List<Ftp> ftpList = new ArrayList<>();
        for (int i = 0; i < jsonArr.size(); i++) {
            Ftp ftp = new Ftp();
            JSONObject jsonObject = jsonArr.getJSONObject(i);
            ftp.setFtpIp(jsonObject.getString("serveip"));
            ftp.setFtpPort(jsonObject.getInteger("serverport"));
            ftp.setFtpUsername(jsonObject.getString("serveruser"));
            ftp.setFtpPassword(jsonObject.getString("serverpassword"));
            ftpList.add(ftp);
        }
        return ftpList;
    }
}
