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

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.f5.F5ProfileDriver;
import com.bocloud.cmp.model.f5.ProfileModel;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.JSONTools;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.f5.BiDnsResolvers;
import com.bocloud.ims.entity.resource.f5.BiIRules;
import com.bocloud.ims.entity.resource.f5.BiPartition;
import com.bocloud.ims.entity.resource.f5.BiProfile;
import com.bocloud.ims.interfaces.resource.f5.F5BiProfileService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.f5.F5BiDnsResolversRepository;
import com.bocloud.ims.repository.resource.f5.F5BiIRulesRepository;
import com.bocloud.ims.repository.resource.f5.F5BiPartitionRepository;
import com.bocloud.ims.repository.resource.f5.F5BiProfileRepository;
import com.bocloud.ims.service.utils.BigIpHelper;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.api.client.util.Lists;
import com.google.api.client.util.Maps;
import com.googlecode.ipv6.IPv6NetworkMask;
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.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("f5BiProfileService")
public class F5BiProfileServiceImpl implements F5BiProfileService {

    private static final Logger logger = LoggerFactory.getLogger(F5BiProfileServiceImpl.class);
    @Autowired
    private F5BiProfileRepository f5BiProfileRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private F5ProfileDriver f5ProfileDriver;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private F5BiDnsResolversRepository f5BiDnsResolversRepository;
    @Autowired
    private F5BiIRulesRepository f5BiIRulesRepository;
    @Autowired
    private F5BiPartitionRepository f5BiPartitionRepository;

    @Override
    public BocloudResult list(Pager pager) {
        GridBean gridBean = null;
        int page = pager.getPage();
        int rows = pager.getRows();
        List<Param> params = pager.getParams();
        Map<String, String> sorter = pager.getSorter();
        boolean simple = pager.getSimple();
        try {
            if (null == params) {
                params = Lists.newArrayList();
            }
            if (null == sorter) {
                sorter = Maps.newHashMap();
            }
            sorter.put("gmtCreate", Common.ONE);
            // 获取到前端传入的vendorId
            Long vendorId = null;
            String category = null;
            String protocolProfileServerCategory = null;
            Boolean isFallbackPersistence = null;
            Param dataParam = null;
            Param name = null;
            Iterator<Param> iterator = params.iterator();
            while (iterator.hasNext()) {
                Param param = iterator.next();
                Map<String, Object> paramData = param.getParam();
                if (paramData.containsKey("vendorId")) {
                    vendorId = Long.valueOf(String.valueOf(paramData.get("vendorId")));
                    iterator.remove();
                }
                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");
                        Map<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("name")) {
                    Map<String, Object> queryDataMap = Maps.newHashMap();
                    queryDataMap.put("name", paramData.get("name"));
                    name = new Param();
                    name.setParam(queryDataMap);
                    name.setSign(Sign.LK);
                }
                // 处理monitorType
                if (paramData.containsKey("category")) {
                    category = String.valueOf(paramData.get("category"));
                }

                // 新增vs时 Protocol Profile (Server)需要特殊处理
                if (paramData.containsKey("protocolProfileServer")) {
                    protocolProfileServerCategory = String.valueOf(paramData.get("protocolProfileServer"));
                }

                // 特殊处理Fallback Persistence Profile
                if (paramData.containsKey("isFallbackPersistence")) {
                    isFallbackPersistence = Boolean.valueOf((boolean) paramData.get("isFallbackPersistence"));
                }
            }
            if (null != dataParam) {
                params.add(dataParam);
            }
            if (null != name) {
                params.add(name);
            }
            int total = this.f5BiProfileRepository.count(params, vendorId, category, protocolProfileServerCategory,
                    isFallbackPersistence);
            if (simple) {
                List<SimpleBean> beans = this.f5BiProfileRepository.list(params, sorter, vendorId, category,
                        protocolProfileServerCategory, isFallbackPersistence);
                gridBean = new GridBean(1, 1, total, beans);
            } else {
                List<BiProfile> listBiProfile = this.f5BiProfileRepository.list(page, rows, params, sorter, vendorId, category,
                        protocolProfileServerCategory, isFallbackPersistence);
                gridBean = GridHelper.getBean(page, rows, total, listBiProfile);
            }
            return new BocloudResult(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("Query BiProfile error:", e);
            return new BocloudResult(false, "查询失败");
        }
    }

    @Override
    public BocloudResult create(BiProfile biProfile, Long userId, ProfileModel profileModel) {
        String path = BiProfile.class.getSimpleName() + "_" + biProfile.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            Long vendorId = biProfile.getVendorId();
            Boolean isExists = f5BiProfileRepository.existName(biProfile.getName(), vendorId, biProfile.getPartitionId());
            if (isExists) {
                return new BocloudResult(false, "添加失败：该名称已存在");
            }
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            if (null == vendor) {
                logger.error("get cloudVendor failure!");
                return new BocloudResult(false, "云平台不存在!");
            }
            Long parentProfileId = biProfile.getParentProfileId();
            BiProfile parentbiProfile = null;
            if (null != parentProfileId) {
                parentbiProfile = f5BiProfileRepository.query(parentProfileId);
                if (null == parentbiProfile) {
                    logger.error("get ProfileId failure!");
                    return new BocloudResult(false, "父节点不存在");
                }
            }
            biProfile.setCreatorId(userId);
            biProfile.setMenderId(userId);
            BiPartition profilePartition = f5BiPartitionRepository.query(biProfile.getPartitionId());
            logger.info("create profile start...");
            // 数据转换
            BocloudResult<ProfileModel> baseResult = convertData(biProfile, parentbiProfile, vendorId, profileModel,
                    vendor.getVersion(), profilePartition);
            if (baseResult.isFailed()) {
                logger.error(baseResult.getMessage());
                return new BocloudResult(false, null, baseResult.getMessage());
            }
            ProfileModel model = baseResult.getData();
            // 处理profile类型
            String categroy = StringUtils.substringBefore(biProfile.getCategory(), "-") + "/"
                    + StringUtils.substringAfter(biProfile.getCategory(), "-");
            BocloudResult bocloudResult = f5ProfileDriver.create(vendor.getUuid(), model, categroy);
            if (bocloudResult.isSuccess()) {
                try {
                    f5BiProfileRepository.save(biProfile);
                } 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("create BiProfile error", e);
            return new BocloudResult(false, "添加失败");
        }
    }

    @SuppressWarnings("null")
    private BocloudResult<ProfileModel> convertData(BiProfile biProfile, BiProfile parentbiProfile, Long vendorId,
                                                    ProfileModel profileModel, String version, BiPartition profilePartition) throws Exception {
        // profile名称
        profileModel.setName(biProfile.getName());
        // 分区
        profileModel.setPartition(profilePartition.getName());
        // 代理模式
        profileModel.setProxyType(biProfile.getProxyMode());
        BiPartition parentPartition = null;
        // 来源文件
        if (null != parentbiProfile) {
            parentPartition = f5BiPartitionRepository.query(parentbiProfile.getPartitionId());
            profileModel
                    .setDefaultsFrom(BigIpHelper.jointPartition(parentPartition.getName(), parentbiProfile.getName()));
        } else {
            BiPartition partition = f5BiPartitionRepository.queryByName(BigIpHelper.EnumHelper.Common.name(), vendorId);
            parentbiProfile.setPartitionId(partition.getId());
        }
        if ("V13".equals(version)) {
            String prefixLength = biProfile.getPrefixLength();
            if (null != prefixLength) {
                if ("none".equals(prefixLength)) {
                    profileModel.setMask("none");
                } else {
                    switch (biProfile.getPrefixLengthType()) {
                        case "IPv6":
                            if (0 == biProfile.getPrefixLengthValue()) {
                                profileModel.setMask("none");
                            } else {
                                IPv6NetworkMask mask = IPv6NetworkMask
                                        .fromPrefixLength(biProfile.getPrefixLengthValue().intValue());
                                profileModel.setMask(String.valueOf(mask.asAddress()));
                            }
                            break;
                        case "IPv4":
                            if (0 == biProfile.getPrefixLengthValue()) {
                                profileModel.setMask("none");
                            } else {
                                String iPv4Mask = getIPv4Mask(biProfile.getPrefixLengthValue());
                                profileModel.setMask(iPv4Mask);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        try {
            ProfileModel configuration = (ProfileModel) profileModel.clone();
            biProfile.setConfiguration(JSONObject.toJSONString(configuration));
            switch (biProfile.getCategory()) {
                case "profile-http":
                    switch (biProfile.getProxyMode()) {
                        case "reverse":
                            String reverseName = "http";
                            if (null != parentbiProfile.getName()) {
                                reverseName = parentbiProfile.getName();
                            }
                            BiPartition partition = f5BiPartitionRepository.queryByName(parentPartition.getName(), vendorId);
                            BiProfile httpprofile = f5BiProfileRepository.queryByName(reverseName, vendorId, partition.getId());
                            biProfile.setParentProfileId(httpprofile.getId());
                            break;
                        case "explicit":
                            String explicitName = "http-explicit";
                            if (null != parentbiProfile.getName()) {
                                explicitName = parentbiProfile.getName();
                            }
                            BiPartition biPartition = f5BiPartitionRepository.queryByName(parentPartition.getName(), vendorId);
                            BiProfile explicitProfile = f5BiProfileRepository.queryByName(explicitName, vendorId, biPartition.getId());
                            biProfile.setParentProfileId(explicitProfile.getId());
                            profileModel.setDefaultsFrom("http-explicit");
                            BiDnsResolvers dnsResolvers = f5BiDnsResolversRepository.query(profileModel.getDnsResolverId());
                            profileModel.setDnsResolverId(null);
                            BiPartition dnsResolversPartition = f5BiPartitionRepository.query(dnsResolvers.getPartitionId());
                            Map<String, Object> explicitProxy = Maps.newHashMap();
                            explicitProxy.put("dnsResolver",
                                    BigIpHelper.jointPartition(dnsResolversPartition.getName(), dnsResolvers.getName()));
                            profileModel.setExplicitProxy(explicitProxy);
                            break;
                        case "transparent":
                            String transparentName = "http-transparent";
                            if (null != parentbiProfile.getName()) {
                                transparentName = parentbiProfile.getName();
                            }
                            BiPartition transparentPartition = f5BiPartitionRepository.queryByName(parentPartition.getName(),
                                    vendorId);
                            BiProfile transparentProfile = f5BiProfileRepository.queryByName(transparentName, vendorId,
                                    transparentPartition.getId());
                            biProfile.setParentProfileId(transparentProfile.getId());
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    if (null != profileModel.getRuleId()) {
                        BiIRules rule = f5BiIRulesRepository.query(profileModel.getRuleId());
                        BiPartition rulePartition = f5BiPartitionRepository.query(rule.getPartitionId());
                        profileModel.setRule(BigIpHelper.jointPartition(rulePartition.getName(), rule.getName()));
                        profileModel.setRuleId(null);
                    }
                    break;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return new BocloudResult<ProfileModel>(true, profileModel, "");
    }

    /**
     * 获取IPv4的mask
     *
     * @param num
     * @return
     */
    public String getIPv4Mask(Long num) {
        int ip = 0xFFFFFFFF << (32 - num);
        String binaryStr = Integer.toBinaryString(ip);
        StringBuffer buffer = new StringBuffer();
        for (int j = 0; j < 4; j++) {
            int beginIndex = j * 8;
            buffer.append(Integer.parseInt(binaryStr.substring(beginIndex, beginIndex + 8), 2)).append(".");
        }
        return buffer.substring(0, buffer.length() - 1);
    }

    @Override
    public BocloudResult modify(BiProfile biProfile, Long userId, ProfileModel profileModel) {
        String path = BiProfile.class.getSimpleName() + "_" + biProfile.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            CloudVendor vendor = cloudVendorRepository.query(biProfile.getVendorId());
            if (null == vendor) {
                logger.error("get cloudVendor failure");
                return new BocloudResult(false, "云平台不存在，修改失败");
            }
            BiProfile object = this.f5BiProfileRepository.query(biProfile.getId());
            if (null == object) {
                logger.warn("data does not exist!");
                return new BocloudResult(false, "数据不存在");
            }
            Long parentProfileId = biProfile.getParentProfileId();
            BiProfile parentbiProfile = null;
            if (null != parentProfileId) {
                parentbiProfile = f5BiProfileRepository.query(parentProfileId);
                if (null == parentbiProfile) {
                    logger.error("get ProfileId failure!");
                    return new BocloudResult(false, "父节点不存在");
                }
            }
            biProfile.setMenderId(userId);
            BiPartition profilePartition = f5BiPartitionRepository.query(biProfile.getPartitionId());
            logger.info("update profile start...");
            // 数据转换
            BocloudResult<ProfileModel> baseResult = convertData(biProfile, parentbiProfile, vendor.getId(), profileModel,
                    vendor.getVersion(), profilePartition);
            if (baseResult.isFailed()) {
                logger.error(baseResult.getMessage());
                return new BocloudResult(false, null, "更新失败：" + baseResult.getMessage());
            }
            ProfileModel model = baseResult.getData();
            // 处理profile类型
            String categroy = StringUtils.substringBefore(biProfile.getCategory(), "-") + "/"
                    + StringUtils.substringAfter(biProfile.getCategory(), "-");
            BocloudResult bocloudResult = f5ProfileDriver.modify(vendor.getUuid(), model, categroy);
            if (bocloudResult.isSuccess()) {
                try {
                    f5BiProfileRepository.update(biProfile);
                } 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("Modify BiProfile fail:", e);
            return new BocloudResult(false, "修改失败");
        }
    }

    @Override
    public BocloudResult remove(Long id, Long userId) {
        String path = BiProfile.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            BiProfile biProfile = this.f5BiProfileRepository.query(id);
            if (null == biProfile) {
                return new BocloudResult(false, "请求数据不存在");
            }
            BiPartition profilePartition = f5BiPartitionRepository.query(biProfile.getPartitionId());
            CloudVendor vendor = cloudVendorRepository.query(biProfile.getVendorId());
            if (null == vendor) {
                logger.error("get cloudVendor failure!");
                return new BocloudResult(false, "删除失败!");
            }
            // 处理profile类型
            String categroy = StringUtils.substringBefore(biProfile.getCategory(), "-") + "/"
                    + StringUtils.substringAfter(biProfile.getCategory(), "-");
            BocloudResult result = f5ProfileDriver.remove(vendor.getUuid(),
                    BigIpHelper.partitionCode(profilePartition.getName(), biProfile.getName()), categroy);
            if (result.isSuccess()) {
                try {
                    f5BiProfileRepository.remove(id, userId);
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    new BocloudResult(false, null, e.getMessage());
                }
                return new BocloudResult(true, "删除成功");
            } else {
                logger.error(result.getMessage());
                return new BocloudResult(false, null, result.getMessage());
            }
        } catch (Exception e) {
            logger.error("Remove BiProfile error:", e);
            return new BocloudResult(false, "删除失败");
        }
    }

    @Override
    public BocloudResult detail(Long id) {
        try {
            BiProfile biProfile = this.f5BiProfileRepository.query(id);
            if (null == biProfile) {
                return new BocloudResult(false, "数据不存在");
            }
            // 获取配置的rule信息
            String configuration = biProfile.getConfiguration();
            Long ruleId = JSONTools.isJSONObj(configuration).getLong("ruleId");
            if (null != ruleId) {
                BiIRules biIRules = f5BiIRulesRepository.query(ruleId);
                BiPartition biIRulesPartition = f5BiPartitionRepository.query(biIRules.getPartitionId());
                biProfile.setRuleName(BigIpHelper.jointPartition(biIRulesPartition.getName(), biIRules.getName()));
            }
            // 获取关联信息
            Long parentProfileId = biProfile.getParentProfileId();
            if (null != parentProfileId) {
                if (0 == parentProfileId) {
                    biProfile.setParentProfileName(
                            BigIpHelper.jointPartition(BigIpHelper.EnumHelper.Common.name(), biProfile.getName()));
                } else {
                    BiProfile profile = f5BiProfileRepository.query(parentProfileId);
                    BiPartition profilePartition = f5BiPartitionRepository.query(profile.getPartitionId());
                    biProfile.setParentProfileName(
                            BigIpHelper.jointPartition(profilePartition.getName(), profile.getName()));
                }
            }
            Long dnsResolverId = JSONTools.isJSONObj(configuration).getLong("dnsResolverId");
            if (null != dnsResolverId) {
                BiDnsResolvers dnsResolver = f5BiDnsResolversRepository.query(dnsResolverId);
                BiPartition dnsResolverPartition = f5BiPartitionRepository.query(dnsResolver.getPartitionId());
                biProfile.setDnsResolverName(
                        BigIpHelper.jointPartition(dnsResolverPartition.getName(), dnsResolver.getName()));
            }
            return new BocloudResult(true, biProfile, "查询成功");
        } catch (Exception e) {
            logger.error("Get BiProfile error：", e);
            return new BocloudResult(false, "查询详情失败");
        }
    }

}
