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

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.azure.db.CloudDatabaseDriver;
import com.bocloud.cmp.model.azure.db.AzureDatabaseModel;
import com.bocloud.cmp.model.azure.db.AzureDatabaseServerModel;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.azure.db.AzureDatabase;
import com.bocloud.ims.entity.resource.azure.db.AzureDatabaseServer;
import com.bocloud.ims.interfaces.resource.azure.db.CloudDatabaseService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.azure.db.CloudDatabaseRepository;
import com.bocloud.ims.repository.resource.azure.db.CloudDatabaseServerRepository;
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;

/**
 * @Company: 博云 www.bocloud.com
 * @ClassName: CloudDatabaseServiceImpl
 * @Description:
 * @author: zhenpingLi/李振平
 * @date: 2021/2/4 13:48
 */
@Service("cloudDatabaseService")
public class CloudDatabaseServiceImpl implements CloudDatabaseService {

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

    private static Logger logger = LoggerFactory.getLogger(CloudDatabaseServiceImpl.class);
    @Autowired
    private CloudDatabaseRepository cloudDatabaseRepository;
    @Autowired
    private CloudDatabaseServerRepository cloudDatabaseServerRepository;
    @Autowired
    private CloudVendorRepository vendorRepository;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private CloudDatabaseDriver cloudDatabaseDriver;

    @Override
    public BocloudResult<Void> create(AzureDatabase entityParams, RequestContext context) {
        try {
            AzureDatabaseServer database = cloudDatabaseServerRepository.query(entityParams.getDatabaseServerId());
            if (ObjectUtils.isEmpty(database)) {
                logger.error("get database failure");
                return new BocloudResult<>(false, "规则所属服务器不存在");
            }
            CloudVendor vendor = vendorRepository.query(database.getVendorId());
            if (ObjectUtils.isEmpty(vendor)) {
                logger.error("get cloudVendor failure");
                return new BocloudResult<>(false, "平台验证失败");
            }
            if (null != cloudDatabaseRepository.getByName(entityParams.getDatabaseServerId(), entityParams.getName())) {
                return new BocloudResult<>(false, "名称已存在");
            }
            AzureDatabaseModel model = new AzureDatabaseModel();
            BeanUtils.copyProperties(entityParams, model);
            model.setResourceGroupName(database.getResourceGroupName());
            model.setDatabaseServerName(database.getName());
            model.setDatabaseServerUuid(database.getDatabaseServerUuid());

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".azuredatabase";
                String message = "创建数据库失败";
                BocloudResult result = cloudDatabaseDriver.create(vendor.getUuid(), database.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "创建数据库成功";
                        AzureDatabaseServerModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), AzureDatabaseServerModel.class);
                        BeanUtils.copyProperties(newModel, entityParams);
                        cloudDatabaseRepository.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 database fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate, MapTools.simpleMap(
                            "vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("create database error!", e);
            return new BocloudResult<>(false, "创建失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> remove(Long id, RequestContext context) {
        String path = AzureDatabaseServer.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            AzureDatabase entity = cloudDatabaseRepository.query(id);
            if (null == entity) {
                logger.error("The data doesn't exist");
                return new BocloudResult<>(false, "数据不存在");
            }
            AzureDatabaseServer database = cloudDatabaseServerRepository.query(entity.getDatabaseServerId());
            if (ObjectUtils.isEmpty(database)) {
                logger.error("get database failure");
                return new BocloudResult<>(false, "规则所属服务器不存在");
            }
            CloudVendor vendor = vendorRepository.query(database.getVendorId());
            if (ObjectUtils.isEmpty(vendor)) {
                logger.error("get cloudVendor failure");
                return new BocloudResult<>(false, "平台验证失败");
            }
            AzureDatabaseModel model = new AzureDatabaseModel();
            model.setResourceGroupName(database.getResourceGroupName());
            model.setDatabaseServerName(database.getName());
            model.setName(entity.getName());
            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".azuredatabase";
                String message = "删除数据库失败";
                BocloudResult result = cloudDatabaseDriver.remove(vendor.getUuid(), database.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "删除数据库成功";
                        cloudDatabaseRepository.delete(id);
                    } 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 database fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("remove database error!", e);
            return new BocloudResult<>(false, "删除失败:" + e.getMessage());
        }
    }

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

    }


}