package com.bocloud.ims.service.resource.azure.slb;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.azure.slb.LoadBalanceRuleDriver;
import com.bocloud.cmp.model.azure.slb.LoadBalanceRuleModel;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.common.enums.AzureTaskStatus;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.azure.slb.*;
import com.bocloud.ims.interfaces.resource.azure.slb.LbRuleService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.azure.slb.*;
import com.bocloud.ims.service.utils.ResourceEventPublisher;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service("lbRuleService")
public class LbRuleServiceImpl implements LbRuleService {

    private static Logger logger = LoggerFactory.getLogger(LbRuleServiceImpl.class);

    private static OperateResult.OperateCategory operateCategory = OperateResult.OperateCategory.ResourceEvent;

    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private LbRuleRepository lbRuleRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private SlbRepository slbRepository;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private LoadBalanceRuleDriver loadBalanceRuleDriver;
    @Autowired
    private BackEndRepository backEndRepository;
    @Autowired
    private FrontEndRepository frontEndRepository;
    @Autowired
    private ProbeRepository probeRepository;

    @Override
    public BocloudResult<GridBean<LbRule>> list(Pager pager, RequestContext context) {
        List<Param> params = Optional.ofNullable(pager.getParams()).orElse(new ArrayList<>());
        Map<String, String> sorter = Optional.ofNullable(pager.getSorter()).orElse(Maps.newHashMap());
        sorter.put("gmtCreate", Common.ONE);
        Boolean simple = Optional.ofNullable(pager.getSimple()).orElse(false);
        Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
        Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);
        try {
            List<LbRule> list = lbRuleRepository.list(page, rows, params, sorter);
            int total = lbRuleRepository.count(params);
            GridBean<LbRule> gridBean = new GridBean<>(page, rows, total, list);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("list lb rule failure:", e);
            return new BocloudResult<>(false, "查询失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> create(LbRule entityParams, RequestContext context) {
        try {
            Slb slb = slbRepository.query(entityParams.getSlbId());
            if (ObjectUtils.isEmpty(slb)) {
                logger.error("get slb failure");
                return new BocloudResult<>(false, "负载均衡不存在");
            }
            CloudVendor vendor = cloudVendorRepository.query(slb.getVendorId());
            if (null == vendor) {
                logger.error("get cloudVendor failure");
                return new BocloudResult<>(false, "平台验证失败");
            }
            if (null != lbRuleRepository.getByName(entityParams.getVendorId(), slb.getId(), entityParams.getName())) {
                return new BocloudResult<>(false, "名称已存在");
            }
            BackEnd backEnd = backEndRepository.query(entityParams.getBackEndId());
            if (null == backEnd) {
                logger.error("get backEnd failure");
                return new BocloudResult<>(false, "后端池不存在");
            }
            FrontEnd frontEnd = frontEndRepository.query(entityParams.getFrontEndId());
            if (null == frontEnd) {
                logger.error("get frontEnd failure");
                return new BocloudResult<>(false, "前端ip配置不存在");
            }
            Probe probe = probeRepository.query(entityParams.getProbeId());
            if (null == probe) {
                logger.error("get probe failure");
                return new BocloudResult<>(false, "运行探测不存在");
            }

            LoadBalanceRuleModel model = new LoadBalanceRuleModel();
            BeanUtils.copyProperties(entityParams, model);
            model.setSlbUuid(slb.getUuid());
            model.setBackEndName(backEnd.getName());
            model.setFrontEndName(frontEnd.getName());
            model.setProbeName(probe.getName());
            //增加状态
            slb.setStatus(AzureTaskStatus.IN_USE.name());
            slbRepository.update(slb);

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".lbRule";
                String message = "创建负载均衡规则失败";
                BocloudResult result = loadBalanceRuleDriver.create(vendor.getUuid(), slb.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "创建负载均衡规则成功";
                        LoadBalanceRuleModel newModel = JSONObject
                                .parseObject(JSONObject.toJSONString(result.getData()), LoadBalanceRuleModel.class);
                        BeanUtils.copyProperties(newModel, entityParams);
                        entityParams.setCreatorId(context.getTarget());
                        entityParams.setVendorId(slb.getVendorId());
                        lbRuleRepository.save(entityParams);
                    } else {
                        logger.error("创建负载均衡规则失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    logger.error("create lb rule fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } finally {
                    //重置状态
                    slb.setStatus(AzureTaskStatus.AVAILABLE.name());
                    slbRepository.update(slb);
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("create lb rule error:", e);
            return new BocloudResult<>(false, "创建负载均衡规则失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> remove(Long id, RequestContext context) {
        String path = BackEnd.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");

            LbRule entity = lbRuleRepository.query(id);
            if (null == entity) {
                logger.warn("lbRule data not exist");
                return new BocloudResult<>(false, "数据不存在");
            }

            Slb slb = slbRepository.query(entity.getSlbId());
            if (ObjectUtils.isEmpty(slb)) {
                logger.error("get slb failure");
                return new BocloudResult<>(false, "负载均衡不存在");
            }

            CloudVendor vendor = cloudVendorRepository.query(slb.getVendorId());
            if (null == vendor) {
                logger.error("get cloudVendor failure");
                return new BocloudResult<>(false, "平台验证失败");
            }

            LoadBalanceRuleModel model = new LoadBalanceRuleModel();
            model.setName(entity.getName());
            model.setSlbUuid(slb.getUuid());
            //增加状态
            slb.setStatus("IN_USE");
            slbRepository.update(slb);
            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".lbRule";
                String message = "删除负载均衡规则失败";

                BocloudResult result = loadBalanceRuleDriver.remove(vendor.getUuid(), slb.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "删除负载均衡规则成功";
                        lbRuleRepository.remove(id, context.getTarget());
                    } else {
                        logger.error("删除负载均衡规则失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    logger.error("remove lb rule fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } finally {
                    //重置状态
                    slb.setStatus("AVAILABLE");
                    slbRepository.update(slb);
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("remove lb rule fail:", e);
            return new BocloudResult<>(false, "删除负载均衡规则失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<LbRule> detail(Long id, RequestContext context) {
        try {
            LbRule rule = lbRuleRepository.query(id);
            if (null == rule) {
                return new BocloudResult<>(false, "数据不存在");
            }
            return new BocloudResult<>(true, rule, "查询详情成功");
        } catch (Exception e) {
            logger.error("query lb rule detail fail:", e);
            return new BocloudResult<>(false, "查询详情失败:" + e.getMessage());
        }
    }
}
