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

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.azure.slb.ProbeDriver;
import com.bocloud.cmp.model.azure.slb.ProbeModel;
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.Probe;
import com.bocloud.ims.entity.resource.azure.slb.Slb;
import com.bocloud.ims.interfaces.resource.azure.slb.ProbeService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.azure.slb.ProbeRepository;
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.*;
import java.util.concurrent.TimeUnit;

@Service("probeService")
public class ProbeServiceImpl implements ProbeService {

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

    private static Logger logger = LoggerFactory.getLogger(ProbeServiceImpl.class);
    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private ProbeRepository probeRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private ProbeDriver probeDriver;
    @Autowired
    private SlbRepository slbRepository;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;


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

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

            ProbeModel model = new ProbeModel();
            BeanUtils.copyProperties(entityParams, model);
            model.setSlbUuid(slb.getUuid());
            //增加状态
            slb.setStatus(AzureTaskStatus.IN_USE.name());
            slbRepository.update(slb);
            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".probe";
                String message = "创建运行状况探测失败";
                BocloudResult result = probeDriver.create(vendor.getUuid(), slb.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "创建运行状况探测成功";
                        ProbeModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), ProbeModel.class);
                        BeanUtils.copyProperties(newModel, entityParams);
                        entityParams.setCreatorId(context.getTarget());
                        entityParams.setVendorId(slb.getVendorId());
                        probeRepository.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 probe 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 probe error:", e);
            return new BocloudResult<>(false, "创建运行状况探测失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> modify(Probe modifyParams, RequestContext context) {
        try {
            Probe entity = probeRepository.query(modifyParams.getId());
            Assert.notNull(entity, "资源不存在");
            Slb slb = slbRepository.query(entity.getSlbId());
            Assert.notNull(slb, "负载均衡不存在");
            CloudVendor vendor = cloudVendorRepository.query(slb.getVendorId());
            Assert.notNull(vendor, "平台验证失败");

            ProbeModel model = new ProbeModel();
            BeanUtils.copyProperties(modifyParams, model);
            model.setName(entity.getName());
            model.setProtocol(entity.getProtocol());
            model.setSlbUuid(slb.getUuid());
            //增加状态
            slb.setStatus(AzureTaskStatus.IN_USE.name());
            slbRepository.update(slb);
            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".probe";
                String message = "更新运行状况探测失败";
                BocloudResult result = probeDriver.modify(vendor.getUuid(), slb.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "更新运行状况探测成功";
                        ProbeModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), ProbeModel.class);
                        BeanUtils.copyProperties(newModel, entity);
                        entity.setMenderId(context.getTarget());
                        entity.setGmtModify(new Date());
                        probeRepository.update(entity);
                    } 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("modify probe 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("modify probe 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), "请求超时");
            Probe entity = probeRepository.query(id);
            Assert.notNull(entity, "资源不存在");
            Slb slb = slbRepository.query(entity.getSlbId());
            Assert.notNull(slb, "负载均衡不存在");
            CloudVendor vendor = cloudVendorRepository.query(slb.getVendorId());
            Assert.notNull(vendor, "平台不存在");

            ProbeModel model = new ProbeModel();
            model.setName(entity.getName());
            model.setSlbUuid(slb.getUuid());
            //增加状态
            slb.setStatus("IN_USE");
            slbRepository.update(slb);
            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".probe";
                String message = "删除运行状况探测失败";

                BocloudResult result = probeDriver.remove(vendor.getUuid(),
                        slb.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "删除运行状况探测成功";
                        probeRepository.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 probe 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 probe fail:", e);
            return new BocloudResult<>(false, "删除运行状况探测失败:" + e.getMessage());
        }
    }

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