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

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.azure.redis.RedisFirewallRuleDriver;
import com.bocloud.cmp.model.NotifyMessage;
import com.bocloud.cmp.model.azure.redis.RedisFirewallRuleModel;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.azure.redis.CloudRedis;
import com.bocloud.ims.entity.resource.azure.redis.CloudRedisFirewallRule;
import com.bocloud.ims.interfaces.resource.azure.redis.CloudRedisFirewallRuleService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.azure.redis.CloudRedisFirewallRuleRepository;
import com.bocloud.ims.repository.resource.azure.redis.CloudRedisRepository;
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.amqp.core.AmqpTemplate;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Company: 博云 www.bocloud.com
 * @ClassName: CloudRedisFirewallRuleServiceImpl
 * @Description:
 * @author: zhenpingLi/李振平
 * @date: 2021/3/1 14:42
 */
@Service
public class CloudRedisFirewallRuleServiceImpl implements CloudRedisFirewallRuleService {

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

    private static Logger logger = LoggerFactory.getLogger(CloudRedisFirewallRuleServiceImpl.class);
    @Autowired
    private CloudVendorRepository vendorRepository;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private CloudRedisRepository cloudRedisRepository;
    @Autowired
    private CloudRedisFirewallRuleRepository cloudRedisFirewallRuleRepository;
    @Autowired
    private RedisFirewallRuleDriver redisFirewallRuleDriver;
    @Autowired
    private AmqpTemplate amqpTemplate;


    @Override
    public BocloudResult<Void> create(CloudRedisFirewallRule entityParams, RequestContext context) {
        try {
            CloudRedis redis = cloudRedisRepository.query(entityParams.getRedisId());
            Assert.notNull(redis, "所属服务器不存在");
            CloudVendor vendor = vendorRepository.query(redis.getVendorId());
            Assert.notNull(vendor, "平台不存在");
            if (null != cloudRedisFirewallRuleRepository.getByName(entityParams.getRedisId(), entityParams.getName())) {
                return new BocloudResult<>(false, "名称已存在");
            }
            RedisFirewallRuleModel model = new RedisFirewallRuleModel();
            BeanUtils.copyProperties(entityParams, model);
            model.setResourceGroupName(redis.getResourceGroupName());
            model.setRedisName(redis.getName());
            model.setRedisUuid(redis.getRedisUuid());

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".redisfirewallrule";
                String message = "创建防火墙规则失败";
                BocloudResult result = redisFirewallRuleDriver.create(vendor.getUuid(), redis.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "尊敬的客户，您好！您的Redis防火墙规则【" + entityParams.getName() + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "创建成功，请登录控制台查看及管理。";
                        RedisFirewallRuleModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), RedisFirewallRuleModel.class);
                        BeanUtils.copyProperties(newModel, entityParams);
                        cloudRedisFirewallRuleRepository.save(entityParams);
                    } else {
                        logger.error("创建防火墙规则失败：" + result.getMessage());
                        message = "尊敬的客户，您好！您的Redis防火墙规则【" + entityParams.getName() + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "创建失败，失败信息：" + result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                    //站内信推送
                    NotifyMessage notifyMessage = new NotifyMessage(context, "MySQL防火墙:", message, null,
                            true, false);
                    amqpTemplate.convertAndSend("event.notice.queue", notifyMessage);
                } catch (Exception e) {
                    logger.error("create DatabaseFirewallRule 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 redisFirewallRule error!", e);
            return new BocloudResult<>(false, "创建失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> remove(Long id, RequestContext context) {
        String path = CloudRedisFirewallRule.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            CloudRedisFirewallRule entity = cloudRedisFirewallRuleRepository.query(id);
            Assert.notNull(entity, "资源不存在");
            CloudRedis redis = cloudRedisRepository.query(entity.getRedisId());
            Assert.notNull(redis, "所属服务器不存在");
            CloudVendor vendor = vendorRepository.query(redis.getVendorId());
            Assert.notNull(vendor, "平台不存在");

            RedisFirewallRuleModel model = new RedisFirewallRuleModel();
            model.setResourceGroupName(redis.getResourceGroupName());
            model.setRedisName(redis.getName());
            model.setName(entity.getName());
            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".redisfirewallrule";
                String message = "删除防火墙规则失败";
                BocloudResult result = redisFirewallRuleDriver.remove(vendor.getUuid(), redis.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "删除防火墙规则成功";
                        cloudRedisFirewallRuleRepository.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 redisFirewallRule 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 redisFirewallRule error!", e);
            return new BocloudResult<>(false, "删除失败:" + e.getMessage());
        }
    }

    public BocloudResult<GridBean<CloudRedisFirewallRule>> list(Pager pager, RequestContext context) {
        try {
            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);

            GridBean gridBean;
            if (null == sorter) {
                sorter = Maps.newHashMap();
            }
            int total = cloudRedisFirewallRuleRepository.count(params);
            List<CloudRedisFirewallRule> list = this.cloudRedisFirewallRuleRepository.list(page, rows, params, sorter);
            gridBean = GridHelper.getBean(page, rows, total, list);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("list redisFirewallRule error!", e);
            return new BocloudResult<>(false, "查询失败:" + e.getMessage());
        }

    }
}