package com.bocloud.ims.service.resource;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.Sign;
import com.bocloud.common.utils.ListTool;
import com.bocloud.ims.entity.resource.AlarmLevel;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.interfaces.resource.AlarmLevelService;
import com.bocloud.ims.repository.resource.AlarmLevelRepository;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 告警级别设置service实现
 *
 * @author Shaolong_an
 * @version 1.0
 * @since 2018年4月25日
 */
@Service("AlarmLevelService")
public class AlarmLevelServiceImpl implements AlarmLevelService {
    private static Logger logger = LoggerFactory.getLogger(AlarmLevelServiceImpl.class);
    @Autowired
    private AlarmLevelRepository alarmLevelRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;

    @Override
    public BocloudResult<AlarmLevel> create(AlarmLevel alarmLevel) {
        try {
            if (StringUtils.isEmpty(alarmLevel.getAlarmMode())) {
                alarmLevel.setAlarmMode("PERCENT");
            }
            this.alarmLevelRepository.create(alarmLevel);
            return new BocloudResult<>(true, alarmLevel, "创建成功!");
        } catch (Exception e) {
            logger.error("create alarm_level error:", e);
            return new BocloudResult<>(false, "创建失败!");
        }
    }

    @Override
    public BocloudResult<AlarmLevel> modify(AlarmLevel alarmLevel) {
        String path = AlarmLevel.class.getSimpleName() + "_" + alarmLevel.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            AlarmLevel object = this.alarmLevelRepository.query(alarmLevel.getId());
            Assert.notNull(object, "数据不存在");
            this.alarmLevelRepository.update(alarmLevel);
            return new BocloudResult<>(true, "修改成功");
        } catch (Exception e) {
            logger.error("Modify alarm_level fail:", e);
            return new BocloudResult<>(false, "修改失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<List<AlarmLevel>> getLevel(String params) {
        @SuppressWarnings("unchecked")
        Map<String, Object> map = JSONObject.parseObject(params, HashMap.class);
        Assert.notNull(map, "参数格式错误");
        // 获取平台告警级别信息
        try {
            Long vendorId = Long.valueOf(map.get("vendorId").toString());
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            Assert.notNull(vendor, "云平台不存在！");
            List<Param> list = Lists.newArrayList();
            list.add(new Param(map, Sign.EQ));
            List<AlarmLevel> levels = alarmLevelRepository.list(list);
            if (ListTool.isEmpty(levels)) {
                logger.info("Don't set alarm level, send default values to client.");
                AlarmLevel level = new AlarmLevel(new BigDecimal(60), new BigDecimal(80));
                levels.add(level);
            }
            return new BocloudResult<>(true, levels, "获取平台告警设置成功");
        } catch (Exception e) {
            logger.error("get alarm level by vendor error:", e);
            return new BocloudResult<>(false, "获取平台告警设置失败");
        }
    }

    @Override
    public BocloudResult<AlarmLevel> setting(AlarmLevel level) {
        // 更新已有的告警级别
        try {
            if (null != level.getId()) {
                AlarmLevel alarmLevel = alarmLevelRepository.query(level.getId());
                Assert.notNull(alarmLevel, "告警不存在");
                alarmLevel.setLevel1(level.getLevel1());
                alarmLevel.setLevel2(level.getLevel2());
                alarmLevel.setLevel3(level.getLevel3());
                alarmLevel.setLevel4(level.getLevel4());
                boolean result = alarmLevelRepository.update(alarmLevel);
                return result ? new BocloudResult<>(true, alarmLevel, "设置告警级别成功") : new BocloudResult<>(false, "设置告警级别失败");
            }
            if (null != level.getVendorId()) {
                CloudVendor vendor = cloudVendorRepository.query(level.getVendorId());
                Assert.notNull(vendor, "平台不存在!");
            }
            if (StringUtils.isEmpty(level.getAlarmMode())) {
                level.setAlarmMode("PERCENT");
            }
            alarmLevelRepository.create(level);
            return new BocloudResult<>(true, level, "设置告警级别成功");
        } catch (Exception e) {
            logger.error("set alarm level error:", e);
            return new BocloudResult<>(false, "设置告警级别失败");
        }
    }

}
