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

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.azure.slb.InboundNatRuleDriver;
import com.bocloud.cmp.model.azure.slb.InboundNatRuleModel;
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.azure.AzureTaskStatus;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.azure.slb.BackEnd;
import com.bocloud.ims.entity.resource.azure.slb.FrontEnd;
import com.bocloud.ims.entity.resource.azure.slb.InboundNatRule;
import com.bocloud.ims.entity.resource.azure.slb.Slb;
import com.bocloud.ims.interfaces.resource.azure.slb.InboundNatRuleService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.azure.slb.FrontEndRepository;
import com.bocloud.ims.repository.resource.azure.slb.InboundNatRuleRepository;
import com.bocloud.ims.repository.resource.azure.slb.SlbRepository;
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 java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service("inboundNatRuleService")
public class InboundNatRuleServiceImpl implements InboundNatRuleService {

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

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

    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private InboundNatRuleRepository inboundNatRuleRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private FrontEndRepository frontEndRepository;
    @Autowired
    private InboundNatRuleDriver inboundNatRuleDriver;
    @Autowired
    private SlbRepository slbRepository;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Override
    public BocloudResult<GridBean<InboundNatRule>> 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<InboundNatRule> list = inboundNatRuleRepository.list(page, rows, params, sorter);
            int total = inboundNatRuleRepository.count(params);
            GridBean<InboundNatRule> gridBean = new GridBean<>(page, rows, total, list);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("list natRule failure:", e);
            return new BocloudResult<>(false, "查询失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> create(InboundNatRule entityParams, RequestContext context) {
        try {
            Slb slb = slbRepository.query(entityParams.getSlbId());
            Assert.notNull(slb, "负载均衡不存在");
            CloudVendor vendor = cloudVendorRepository.query(slb.getVendorId());
            Assert.notNull(vendor, "平台不存在");
            if (null != inboundNatRuleRepository.getByName(entityParams.getVendorId(), slb.getId(), entityParams.getName())) {
                return new BocloudResult<>(false, "名称已存在");
            }
            FrontEnd frontEnd = frontEndRepository.query(entityParams.getFrontEndId());
            Assert.notNull(frontEnd, "frontEnd不存在");

            InboundNatRuleModel model = new InboundNatRuleModel();
            BeanUtils.copyProperties(entityParams, model);
            model.setSlbUuid(slb.getUuid());
            model.setFrontEndName(frontEnd.getName());
            model.setFrontEndUuid(frontEnd.getUuid());
            //增加状态
            slb.setStatus(AzureTaskStatus.IN_USE.name());
            slbRepository.update(slb);
            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".inboundNatRule";
                String message = "创建入站NAT规则失败";
                BocloudResult result = inboundNatRuleDriver.create(vendor.getUuid(), slb.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "创建入站NAT规则成功";
                        LoadBalanceRuleModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), LoadBalanceRuleModel.class);
                        BeanUtils.copyProperties(newModel, entityParams);
                        entityParams.setCreatorId(context.getTarget());
                        entityParams.setVendorId(slb.getVendorId());
                        inboundNatRuleRepository.save(entityParams);
                    } else {
                        logger.error("创建入站NAT规则失败：" + 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 nat 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 nat rule error:", e);
            return new BocloudResult<>(false, "创建入站NAT规则失败:" + 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), "请求超时");
            InboundNatRule entity = inboundNatRuleRepository.query(id);
            Assert.notNull(entity, "资源不存在");
            Slb slb = slbRepository.query(entity.getSlbId());
            Assert.notNull(slb, "负载均衡不存在");
            CloudVendor vendor = cloudVendorRepository.query(slb.getVendorId());
            Assert.notNull(vendor, "平台不存在");
            InboundNatRuleModel model = new InboundNatRuleModel();
            model.setName(entity.getName());
            model.setSlbUuid(slb.getUuid());
            //增加状态
            slb.setStatus("IN_USE");
            slbRepository.update(slb);
            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".inboundNatRule";
                String message = "删除入站NAT规则失败";

                BocloudResult result = inboundNatRuleDriver.remove(vendor.getUuid(),
                        slb.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "删除入站NAT规则成功";
                        inboundNatRuleRepository.remove(id, context.getTarget());
                    } else {
                        logger.error("删除入站NAT规则失败：" + 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 nat 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 nat rule fail:", e);
            return new BocloudResult<>(false, "删除入站NAT规则失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<InboundNatRule> detail(Long id, RequestContext context) {
        try {
            InboundNatRule natRule = inboundNatRuleRepository.query(id);
            Assert.notNull(natRule, "资源不存在");
            return new BocloudResult<>(true, natRule, "查询详情成功");
        } catch (Exception e) {
            logger.error("query natRule detail fail:", e);
            return new BocloudResult<>(false, "查询详情失败:" + e.getMessage());
        }
    }
}
