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

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.azure.automation.DeploymentDriver;
import com.bocloud.cmp.driver.azure.automation.LogAnalyticDriver;
import com.bocloud.cmp.model.azure.automation.AutomationAccountModel;
import com.bocloud.cmp.model.azure.automation.LogAnalyticModel;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.GridBean;
import com.bocloud.common.model.Pager;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.IDFactory;
import com.bocloud.common.utils.JSONTools;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.ResourceGroup;
import com.bocloud.ims.entity.resource.azure.automation.LogAnalytic;
import com.bocloud.ims.interfaces.resource.azure.automation.LogAnalyticService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.ResourceGroupRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @Company: 博云 www.bocloud.com
 * @ClassName: LogAnalyticServiceImpl
 * @Description:
 * @author: zhenpingLi/李振平
 * @date: 2020/8/10 11:39
 */
@Service("logAnalyticService")
public class LogAnalyticServiceImpl implements LogAnalyticService {

    private static Logger logger = LoggerFactory.getLogger(LogAnalyticServiceImpl.class);
    @Autowired
    private CloudVendorRepository vendorRepository;
    @Autowired
    private ResourceGroupRepository resourceGroupRepository;
    @Autowired
    private LogAnalyticDriver analyticDriver;
    @Autowired
    private DeploymentDriver deploymentDriver;


    @Override
    public BocloudResult<GridBean<LogAnalytic>> list(Pager pager, RequestContext context) {
        return null;
    }

    @Override
    public BocloudResult<LogAnalytic> detail(Long id, RequestContext context) {
        return null;
    }

    @Override
    public BocloudResult<Void> modify(LogAnalytic entityParams, RequestContext context) {
        return null;
    }

    @Override
    public BocloudResult<Void> create(LogAnalytic entityParams, RequestContext context) {
        try {
            CloudVendor vendor = vendorRepository.query(entityParams.getVendorId());
            if (ObjectUtils.isEmpty(vendor)) {
                logger.error("get cloudVendor failure");
                return new BocloudResult<>(false, "平台验证失败");
            }
            ResourceGroup resourceGroup = resourceGroupRepository.query(entityParams.getResourceGroupId());
            if (ObjectUtils.isEmpty(resourceGroup)) {
                logger.error("get resourceGroup failure");
                return new BocloudResult<>(false, "资源组不能为空");
            }
            LogAnalyticModel model = new LogAnalyticModel();
            BeanUtils.copyProperties(entityParams, model);
            model.setResourceGroupName(resourceGroup.getName());
            BocloudResult result = analyticDriver.create(vendor.getUuid(), entityParams.getRegionId(), model);
            if (result.isFailed()) {
                return new BocloudResult<>(false, result.getMessage());
            }
            return new BocloudResult<>(true, "创建成功");
        } catch (Exception e) {
            logger.error("create LogAnalytic error!", e);
            return new BocloudResult<>(false, "创建失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> remove(Long id, RequestContext context) {
        return null;
    }

    @Override
    public BocloudResult list(String params) {
        JSONObject object = JSONTools.isJSONObj(params);
        Long vendorId = object.getLong("vendorId");
        CloudVendor vendor = vendorRepository.query(vendorId);
        if (ObjectUtils.isEmpty(vendor)) {
            logger.error("get cloudVendor failure");
            return new BocloudResult(false, "平台验证失败");
        }
        return analyticDriver.list(vendor.getUuid());
    }

    @Override
    public BocloudResult sharedKeys(String params) {
        JSONObject object = JSONTools.isJSONObj(params);
        LogAnalytic entityParams = JSONObject.parseObject(object.getString("logAnalytic"), LogAnalytic.class);
        try {
            CloudVendor vendor = vendorRepository.query(entityParams.getVendorId());
            if (ObjectUtils.isEmpty(vendor)) {
                logger.error("get cloudVendor failure");
                return new BocloudResult(false, "平台验证失败");
            }
            LogAnalyticModel model = new LogAnalyticModel();
            BeanUtils.copyProperties(entityParams, model);
            return analyticDriver.sharedKeys(vendor.getUuid(), model);
        } catch (Exception e) {
            logger.error("sharedKeys LogAnalytic error!", e);
            return new BocloudResult(false, "请求失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult detail(LogAnalytic entityParams) {
        try {
            CloudVendor vendor = vendorRepository.query(entityParams.getVendorId());
            if (ObjectUtils.isEmpty(vendor)) {
                logger.error("get cloudVendor failure");
                return new BocloudResult(false, "平台验证失败");
            }
            LogAnalyticModel model = new LogAnalyticModel();
            BeanUtils.copyProperties(entityParams, model);
            return analyticDriver.detail(vendor.getUuid(), model);
        } catch (Exception e) {
            logger.error("detail LogAnalytic error!", e);
            return new BocloudResult(false, "请求失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult remove(String params) {
        JSONObject object = JSONTools.isJSONObj(params);
        LogAnalytic entityParams = JSONObject.parseObject(object.getString("logAnalytic"), LogAnalytic.class);
        try {
            CloudVendor vendor = vendorRepository.query(entityParams.getVendorId());
            if (ObjectUtils.isEmpty(vendor)) {
                logger.error("get cloudVendor failure");
                return new BocloudResult(false, "平台验证失败");
            }
            LogAnalyticModel model = new LogAnalyticModel();
            BeanUtils.copyProperties(entityParams, model);
            return analyticDriver.remove(vendor.getUuid(), model);
        } catch (Exception e) {
            logger.error("remove LogAnalytic error!", e);
            return new BocloudResult(false, "请求失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult linkedServices(String params) {
        JSONObject object = JSONTools.isJSONObj(params);
        LogAnalytic entityParams = JSONObject.parseObject(object.getString("logAnalytic"), LogAnalytic.class);
        try {
            CloudVendor vendor = vendorRepository.query(entityParams.getVendorId());
            if (ObjectUtils.isEmpty(vendor)) {
                logger.error("get cloudVendor failure");
                return new BocloudResult(false, "平台验证失败");
            }
            LogAnalyticModel model = new LogAnalyticModel();
            BeanUtils.copyProperties(entityParams, model);
//            return analyticDriver.linkedServices(vendor.getUuid(), model);
            BocloudResult result = analyticDriver.linkedServices(vendor.getUuid(), model);
            if (result.isSuccess()) {
                Thread.sleep(3000);
                String name = IDFactory.instance().mac();
                AutomationAccountModel accountModel = new AutomationAccountModel();
                accountModel.setLogAnalyticName(model.getName());
                accountModel.setResourceGroupName(model.getResourceGroupName());
                accountModel.setName(model.getAutomationAccountName());
                accountModel.setRegionId(model.getRegionId());
                return deploymentDriver.deploymentAutomationAccount(vendor.getUuid(), model.getRegionId(), accountModel, name);
            } else {
                return new BocloudResult(false, "关联失败");
            }
        } catch (Exception e) {
            logger.error("linkedServices LogAnalytic error!", e);
            return new BocloudResult(false, "请求失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult queryLogAnalytic(String params) {
        JSONObject object = JSONTools.isJSONObj(params);
        String operation = object.getString("operation");
        String resourceId = object.getString("resourceId");
        LogAnalytic entityParams = JSONObject.parseObject(object.getString("logAnalytic"), LogAnalytic.class);
        try {
            CloudVendor vendor = vendorRepository.query(entityParams.getVendorId());
            if (ObjectUtils.isEmpty(vendor)) {
                logger.error("get cloudVendor failure");
                return new BocloudResult(false, "平台验证失败");
            }
            LogAnalyticModel model = new LogAnalyticModel();
            BeanUtils.copyProperties(entityParams, model);
            BocloudResult result = analyticDriver.queryLogAnalytic(vendor.getUuid(), model, operation, resourceId);
            if (result.isFailed()) {
                return new BocloudResult(false, "控制器未完成变更，请稍后查询！");
            }
            return result;
        } catch (Exception e) {
            logger.error("query LogAnalytic error!", e);
            return new BocloudResult(false, "自动化账户启动部署失败，请重新部署。或者刚部署成功，数据没有更新请稍后查询！");
        }
    }


}