package com.bocloud.ims.service.scheduler.scheduler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.loadbalance.LbDriver;
import com.bocloud.cmp.entity.enums.CloudProvider;
import com.bocloud.cmp.model.LbListenerModel;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.utils.ListTool;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.LoadBalancer;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.LoadBalancerRepository;
import com.bocloud.ims.service.transporter.vendor.VolcengineTransporter;
import com.bocloud.service.core.CurrentService;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;

/**
 * @ClassName: LbListenerHealthScheduler
 * @Description: 负载均衡监听器健康状态定时刷新
 * @Author lxy
 * @Date 2021/10/20 14:19
 */
@Component
public class LbListenerHealthScheduler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private CurrentService service;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private LbDriver lbDriver;
    @Autowired
    private VolcengineTransporter volcengineTransportor;
    @Autowired
    private LoadBalancerRepository loadBalancerRepository;

    @Scheduled(cron = "${vendor.lblistenerhealth.scheduler:0 0/2 * * * ?}")
    void updateLbListenerHealthMsg() {
        if (!service.isLeader()) {
            return;
        }
        List<CloudVendor> vendors = cloudVendorRepository.listByType(CloudProvider.VOLCENGINE.name());
        if (vendors.isEmpty()) {
            return;
        }
        logger.info("开始定时更新负载均衡监听器健康状态...");
        for (CloudVendor vendor : vendors) {
            Assert.notNull(vendor, "云平台不存在");
            try {
                JSONObject object = JSONObject.parseObject(vendor.getAuthentication());
                List<String> regions = JSONArray.parseArray(object.getString("regions"), String.class);
                for (String region : regions) {
                    List<LoadBalancer> balancers = loadBalancerRepository.listByVid(vendor.getId(), region);
                    if (ListTool.isEmpty(balancers)) {
                        continue;
                    }
                    BocloudResult<List<LbListenerModel>> result = lbDriver.listListener(vendor.getUuid(), region);
                    Map<String, Long> balancerMap = Maps.newHashMap();
                    for (LoadBalancer balancer : balancers) {
                        balancerMap.put(balancer.getLbUuid(), balancer.getId());
                    }
                    if (result.isSuccess() && null != result.getData()) {
                        logger.info("Start sync Listener health : " + vendor.getName());
                        volcengineTransportor.syncLbListener(result.getData(), balancerMap, vendor.getId(), Long.valueOf(1), region, false);
                        logger.info("End sync Listener health : " + vendor.getName());
                    }
                }
            } catch (Exception e) {
                logger.error("负载均衡监听器健康状态定时刷新异常，原因：" + e);
            }
        }
        logger.info("定时更新负载均衡监听器健康状态完成");
    }
}
