package com.bocloud.ims.service.resource.f5;

import java.util.*;
import java.util.concurrent.TimeUnit;

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 com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.f5.F5MonitorDriver;
import com.bocloud.cmp.model.f5.MonitorModel;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.ims.entity.middleware.Kvs;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.f5.BiMonitor;
import com.bocloud.ims.entity.resource.f5.BiPartition;
import com.bocloud.ims.interfaces.resource.f5.F5BiMonitorService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.f5.F5BiMonitorRepository;
import com.bocloud.ims.repository.resource.f5.F5BiPartitionRepository;
import com.bocloud.ims.service.utils.BigIpHelper;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Service("f5BiMonitorService")
public class F5BiMonitorServiceImpl implements F5BiMonitorService {

    private static final Logger logger = LoggerFactory.getLogger(F5BiMonitorServiceImpl.class);
    @Autowired
    private F5BiMonitorRepository f5BiMonitorRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private F5MonitorDriver f5MonitorDriver;
    @Autowired
    private F5BiPartitionRepository f5BiPartitionRepository;

    @Override
    public BocloudResult<GridBean<BiMonitor>> list(Pager pager) {
        GridBean gridBean = null;
        try {
            int page = pager.getPage();
            int rows = pager.getRows();
            List<Param> params = pager.getParams();
            Map<String, String> sorter = pager.getSorter();
            boolean simple = pager.getSimple();

            if (params == null) {
                params = Lists.newArrayList();
            }
            if (sorter == null) {
                sorter = Maps.newHashMap();
            }
            sorter.put("gmtCreate", Common.ONE);
            // 获取到前端传入的vendorId
            Long vendorId = null;
            List<String> typeList = Lists.newArrayList();
            Param dataParam = null;
            Iterator<Param> iterator = params.iterator();
            while (iterator.hasNext()) {
                Param param = (Param)iterator.next();
                Map<String, Object> paramData = param.getParam();
                if (paramData.containsKey("partitionId")) {
                    Long partitionId = Long.valueOf(paramData.get("partitionId").toString());
                    BiPartition partition = f5BiPartitionRepository.query(partitionId);
                    if (0 == partitionId) {
                        paramData.remove("partitionId");
                    } else if (!partition.getName().equals(BigIpHelper.EnumHelper.Common.name())) {
                        BiPartition commonPartition = f5BiPartitionRepository
                            .queryByName(BigIpHelper.EnumHelper.Common.name(), partition.getVendorId());
                        paramData.remove("partitionId");
                        HashMap<String, Object> queryDataMap = Maps.newHashMap();
                        queryDataMap.put("partitionId",
                            new StringBuilder().append(partitionId).append(",").append(commonPartition.getId()));
                        dataParam = new Param();
                        dataParam.setParam(queryDataMap);
                        dataParam.setSign(Sign.IN);
                    }
                }
                if (paramData.containsKey("vendorId")) {
                    vendorId = Long.valueOf(String.valueOf(paramData.get("vendorId")));
                    paramData.remove("vendorId");
                }
                // 处理monitorType
                if (paramData.containsKey("monitorType")) {
                    String[] monitorTypes = String.valueOf(paramData.get("monitorType")).split(",");
                    for (String type : monitorTypes) {
                        typeList.add(type.replace("_", "-"));
                    }
                    iterator.remove();
                    rows = Integer.MAX_VALUE;
                }
            }
            if (null != dataParam) {
                params.add(dataParam);
            }
            int total = this.f5BiMonitorRepository.count(params, vendorId, typeList);
            // 递归获取https_443所有相关的数据
            List<BiMonitor> https443TypeMonitors = Lists.newArrayList();
            if (!typeList.isEmpty()) {
                // 为node加入monitor时特殊查询处理
                if (5 == typeList.size()) {
                    BiPartition partition =
                        f5BiPartitionRepository.queryByName(BigIpHelper.EnumHelper.Common.name(), vendorId);
                    BiMonitor monitor = f5BiMonitorRepository.queryByName("https_443", vendorId, partition.getId());
                    monitor.setPartitionName(partition.getName());
                    https443TypeMonitors.add(monitor);
                    queryRecursiveData(monitor.getId(), vendorId, https443TypeMonitors);
                    total += https443TypeMonitors.size();
                }
            }
            if (simple) {
                List<SimpleBean> beans = this.f5BiMonitorRepository.list(params, sorter, vendorId);
                gridBean = new GridBean(1, 1, total, beans);
            } else {
                List<BiMonitor> biMonitors =
                    this.f5BiMonitorRepository.list(page, rows, params, sorter, vendorId, typeList);
                if (!typeList.isEmpty()) {
                    biMonitors.addAll(https443TypeMonitors);
                }
                gridBean = GridHelper.getBean(page, rows, total, biMonitors);
            }
            return new BocloudResult(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("Query BiMonitor list fail:", e);
            return new BocloudResult(false, "查询失败");
        }
    }

    /**
     * 递归获取相关的数据
     *
     * @param id
     */
    private void queryRecursiveData(Long id, Long vendorId, List<BiMonitor> https443TypeMonitors) {
        try {
            List<BiMonitor> biMonitors = f5BiMonitorRepository.queryByParentId(id, vendorId);
            https443TypeMonitors.addAll(biMonitors);
            for (BiMonitor biMonitor : biMonitors) {
                queryRecursiveData(biMonitor.getId(), vendorId, https443TypeMonitors);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    @Override
    public BocloudResult create(BiMonitor biMonitor, Long userId, MonitorModel monitorModel) {
        String path = Kvs.class.getSimpleName() + "_" + biMonitor.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            // 云平台id
            Long vendorId = biMonitor.getVendorId();
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            if (null == vendor) {
                logger.error("get cloudVendor failure!");
                return new BocloudResult(false, "云平台不存在!");
            }
            Boolean isExists =
                f5BiMonitorRepository.existName(biMonitor.getName(), vendorId, biMonitor.getPartitionId());
            if (isExists) {
                return new BocloudResult(false, "添加失败：该名称已存在");
            }
            biMonitor.setMenderId(userId);
            biMonitor.setCreatorId(userId);
            biMonitor.setGmtCreate(new Date());
            biMonitor.setReserved(false);
            BiPartition partition = f5BiPartitionRepository.query(biMonitor.getPartitionId());
            logger.info("create Monitor start...");
            // 数据转换
            BocloudResult<MonitorModel> BocloudResult = convertData(biMonitor, vendorId, monitorModel, partition);
            if (BocloudResult.isFailed()) {
                logger.error(BocloudResult.getMessage());
                return new BocloudResult(false, null, BocloudResult.getMessage());
            }
            MonitorModel monitor = BocloudResult.getData();
            BocloudResult bocloudResult = f5MonitorDriver.create(vendor.getUuid(), monitor, biMonitor.getType());
            if (bocloudResult.isSuccess()) {
                try {
                    // 将Configuration保存到数据库
                    f5BiMonitorRepository.save(biMonitor);
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    return new BocloudResult(false, null, "创建失败");
                }
                return new BocloudResult(true, "添加成功");
            } else {
                logger.error(bocloudResult.getMessage());
                return new BocloudResult(false, null, bocloudResult.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new BocloudResult(false, "添加失败");
        }
    }

    private BocloudResult<MonitorModel> convertData(BiMonitor biMonitor, Long vendorId, MonitorModel monitorModel,
        BiPartition partition) throws CloneNotSupportedException {
        monitorModel.setName(biMonitor.getName());
        monitorModel.setPartition(partition.getName());
        monitorModel.setDescription(biMonitor.getRemark());
        try {
            if (null != biMonitor.getParentMonitorId()) {
                if (0L != biMonitor.getParentMonitorId()) {
                    BiMonitor parentMonitor = this.f5BiMonitorRepository.query(biMonitor.getParentMonitorId());
                    if (null == parentMonitor) {
                        logger.error("get parent Monitor failure!");
                        return new BocloudResult<MonitorModel>(false, "获取关联数据失败");
                    }
                    BiPartition biPartition = f5BiPartitionRepository.query(parentMonitor.getPartitionId());
                    monitorModel
                        .setDefaultsFrom(BigIpHelper.jointPartition(biPartition.getName(), parentMonitor.getName()));
                } else {
                    BiPartition biPartition =
                        f5BiPartitionRepository.queryByName(BigIpHelper.EnumHelper.Common.name(), vendorId);
                    BiMonitor monitor = f5BiMonitorRepository.queryByName(biMonitor.getType().replace("-", "_"),
                        vendorId, biPartition.getId());
                    if (null != monitor) {
                        biMonitor.setParentMonitorId(monitor.getId());
                        monitorModel.setDefaultsFrom(biMonitor.getType());
                    } else {
                        biMonitor.setParentMonitorId(0L);
                        monitorModel.setDefaultsFrom(biMonitor.getType());
                    }
                }
            }
        } catch (Exception e) {
            logger.warn("data does not exist !");
            return new BocloudResult<MonitorModel>(false, "获取关联数据失败");
        }
        // 处理monitor的configuration
        // 数据库不在保存pssword 因为需要先备份一次Configuration，对password等数据进行处理
        MonitorModel configuration = new MonitorModel();
        configuration = (MonitorModel)monitorModel.clone();
        if (null != configuration.getPassword()) {
            configuration.setPassword("");
        }
        biMonitor.setConfiguration(JSONObject.toJSONString(configuration));
        switch (biMonitor.getType()) {
            case "http":
            case "https":
            case "tcp":
                // 处理创建monitor的参数
                if ("* All Addresses".equals(monitorModel.getAliasAddress())) {
                    monitorModel.setAliasAddress("*");
                }
                // 拼接别名地址+端口
                monitorModel.setDestination(monitorModel.getAliasAddress() + ":" + monitorModel.getAliasServicePort());
                monitorModel.setAliasAddress(null);
                monitorModel.setAliasServicePort(null);
                monitorModel.setPortType(null);
                // 处理password
                if (null != monitorModel.getPassword()) {
                    if ("".equals(monitorModel.getPassword())) {
                        monitorModel.setPassword(null);
                    }
                }
                monitorModel.setReverse("no".equals(monitorModel.getReverse()) ? "disabled" : "enabled");
                monitorModel.setTransparent("no".equals(monitorModel.getTransparent()) ? "disabled" : "enabled");
                break;
            case "icmp":
                // 处理创建monitor的参数
                if ("* All Addresses".equals(monitorModel.getAliasAddress())) {
                    monitorModel.setAliasAddress("*");
                }
                monitorModel.setTransparent("no".equals(monitorModel.getTransparent()) ? "disabled" : "enabled");
                monitorModel.setDestination(monitorModel.getAliasAddress());
                monitorModel.setAliasAddress(null);
                break;
            case "soap":
                // 处理password
                if (null != monitorModel.getPassword()) {
                    if ("".equals(monitorModel.getPassword())) {
                        monitorModel.setPassword(null);
                    }
                }
                break;
            default:
                break;
        }
        return new BocloudResult<MonitorModel>(true, monitorModel, "");
    }

    @Override
    public BocloudResult modify(BiMonitor biMonitor, Long userId, MonitorModel monitorModel) {
        String path = Kvs.class.getSimpleName() + "_" + biMonitor.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            BiMonitor object = this.f5BiMonitorRepository.query(biMonitor.getId());
            if (null == object) {
                logger.warn("data does not exist!");
                return new BocloudResult(false, "数据不存在");
            }
            CloudVendor vendor = cloudVendorRepository.query(biMonitor.getVendorId());
            if (null == vendor) {
                logger.error("get cloudVendor failure");
                return new BocloudResult(false, "云平台不存在，修改失败");
            }
            biMonitor.setMenderId(userId);
            biMonitor.setGmtModify(new Date());
            biMonitor.setReserved(false);
            biMonitor.setDeleted(false);
            BiPartition partition = f5BiPartitionRepository.query(biMonitor.getPartitionId());
            logger.info("update Monitor start...");
            // 数据转换
            BocloudResult<MonitorModel> BocloudResult = convertData(biMonitor, vendor.getId(), monitorModel, partition);
            if (BocloudResult.isFailed()) {
                logger.error(BocloudResult.getMessage());
                return new BocloudResult(false, null, "更新失败：" + BocloudResult.getMessage());
            }
            MonitorModel monitor = BocloudResult.getData();
            BocloudResult bocloudResult = f5MonitorDriver.modify(vendor.getUuid(), monitor, biMonitor.getType());
            if (bocloudResult.isSuccess()) {
                try {
                    f5BiMonitorRepository.update(biMonitor);
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    return new BocloudResult(false, null, e.getMessage());
                }
                return new BocloudResult(true, "更新成功");
            } else {
                logger.error(bocloudResult.getMessage());
                return new BocloudResult(false, null, bocloudResult.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new BocloudResult(false, "修改失败");
        }
    }

    @Override
    public BocloudResult remove(Long id, Long userId) {
        String path = Kvs.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            BiMonitor biMonitor = this.f5BiMonitorRepository.query(id);
            if (null == biMonitor) {
                return new BocloudResult(false, "请求内容不存在");
            }
            CloudVendor vendor = cloudVendorRepository.query(biMonitor.getVendorId());
            if (null == vendor) {
                logger.error("get Monitor failure!");
                return new BocloudResult(false, "删除失败!");
            }
            BiPartition partition = f5BiPartitionRepository.query(biMonitor.getPartitionId());
            logger.info("remove Monitor start...");
            BocloudResult result = f5MonitorDriver.remove(vendor.getUuid(),
                BigIpHelper.partitionCode(partition.getName(), biMonitor.getName()), biMonitor.getType());
            if (result.isSuccess()) {
                try {
                    f5BiMonitorRepository.remove(id, userId);
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    new BocloudResult(false, null, result.getMessage());
                }
                return new BocloudResult(true, "删除成功");
            } else {
                logger.error(result.getMessage());
                return new BocloudResult(false, null, result.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new BocloudResult(false, "删除失败");
        }
    }

    @Override
    public BocloudResult<BiMonitor> detail(Long id) {
        try {
            BiMonitor biMonitor = this.f5BiMonitorRepository.query(id);
            if (null == biMonitor) {
                logger.warn("Get data dose not exist");
                return new BocloudResult(false, "请求内容不存在");
            }
            if (0L != biMonitor.getParentMonitorId()) {
                BiMonitor parentMonitor = this.f5BiMonitorRepository.query(biMonitor.getParentMonitorId());
                BiPartition partition = f5BiPartitionRepository.query(parentMonitor.getPartitionId());
                biMonitor
                    .setParentMonitorName(BigIpHelper.jointPartition(partition.getName(), parentMonitor.getName()));
            } else {
                BiPartition partition = f5BiPartitionRepository.query(biMonitor.getPartitionId());
                biMonitor.setParentMonitorName(BigIpHelper.jointPartition(partition.getName(), biMonitor.getName()));
            }
            return new BocloudResult(true, biMonitor, "查询成功");
        } catch (Exception e) {
            logger.error("Get BiMonitor error:", e);
            return new BocloudResult(false, "查询失败");
        }
    }

}