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

import com.alibaba.fastjson.JSON;
import com.bocloud.cmp.driver.secuirty.FirewallDriver;
import com.bocloud.cmp.model.FirewallModel;
import com.bocloud.cmp.model.sangfor.SangForServerGroupModel;
import com.bocloud.cmp.model.sangfor.SangforFirewallRuleModel;
import com.bocloud.cmp.model.sangfor.SangforServerModel;
import com.bocloud.cmp.params.Sangfor.SangforFireWallParams;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.Firewall;
import com.bocloud.ims.entity.resource.FirewallRule;
import com.bocloud.ims.entity.resource.SangforServerGroup;
import com.bocloud.ims.interfaces.resource.sangfor.SangforFireWallService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.FirewallRepository;
import com.bocloud.ims.repository.resource.FirewallRuleRepository;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;

@Service("sangforFireWallService")
public class SangforFireWallServiceImpl implements SangforFireWallService {
    @Autowired
    private FirewallRepository firewallRepository;
    @Autowired
    private FirewallDriver firewallDriver;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private FirewallRuleRepository firewallRuleRepository;

    @Override
    public BocloudResult<GridBean<Firewall>> list(Pager pager, RequestContext context) {
//        List<SangforServerGroup> list = Lists.newArrayList();
//        int total = 0;
//        GridBean gridBean = null;
//        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);
//            sorter.put("id", Common.ONE);
//            Long vendorId = null;
//            for (Param param: params) {
//                Map<String, Object> paramMap = param.getParam();
//                if (paramMap.containsKey("vendorId")){
//                    vendorId = Long.valueOf(String.valueOf(paramMap.get("vendorId")));
//                    paramMap.remove("vendorId");
//                }
//            }
//            Integer page = pager.getPage();
//            Integer rows = pager.getRows();
//            sorter.put("id", Common.ONE);
//            total = firewallRepository.stCount(params,vendorId);
//            list = firewallRepository.stList(page, rows, params, sorter,vendorId);
//            gridBean = GridHelper.getBean(page, rows, total, list);
//            return new BocloudResult<>(true, gridBean, "查询成功");
//        }catch (Exception e){
//            return new BocloudResult<>(false, "查询成功");
//        }
        return null;
    }

    @Override
    public BocloudResult<GridBean<FirewallRule>> create(Pager pager, RequestContext context, FirewallRule firewallRule) {
        try{
            CloudVendor vendor = cloudVendorRepository.listById(firewallRule.getVendorId());
            SangforFireWallParams model = new SangforFireWallParams();
            model.setName(firewallRule.getName());
            model.setNetworkType(firewallRule.getNetworkType());
            model.setAzId(firewallRule.getAzId());
            model.setSangforProjectId(firewallRule.getSangforProjectId());
            model.setPolicyType(firewallRule.getPolicyType());
            BocloudResult result = firewallDriver.createV68(vendor.getUuid(), null, model);
            if (result.isSuccess()){
                List<SangforFireWallParams> serverGroupModels = JSON.parseArray(JSON.toJSON(result.getData()).toString(), SangforFireWallParams.class);
                for (SangforFireWallParams ruleModel :serverGroupModels){
                    FirewallRule newFire = new FirewallRule();
                    BeanUtils.copyProperties(ruleModel,newFire);
                    newFire.setPolicyType(ruleModel.getPolicyType());
                    newFire.setAzId(ruleModel.getAzId());
                    newFire.setSangforProjectId(ruleModel.getSangforProjectId());
                    newFire.setSangforPolicyId(ruleModel.getSangforPolicyId());
                    newFire.setRuleIds("[\"" + String.join("\",\"", ruleModel.getRuleIds()) + "\"]");
                    newFire.setNetworkType(ruleModel.getNetworkType());
                    newFire.setVpcId(ruleModel.getVpcId());
                    newFire.setVendorId(vendor.getId());
                    newFire.setCreatorId(context.getTarget());
                    newFire.setGmtCreate(new Date());
                    newFire.setIsDefault(false);
                    firewallRuleRepository.save(newFire);
                }
                return new BocloudResult<>(true,"创建防火墙规则成功");
            }else {
                return new BocloudResult<>(false,result.getMessage());
            }
        }catch (Exception e){
            e.printStackTrace();
            return new BocloudResult<>(false,"防火墙规则创建失败");
        }
    }

    @Override
    public BocloudResult<GridBean<FirewallRule>> remove(RequestContext context, Long id) {
        try {
            FirewallRule firewallRule = firewallRuleRepository.listById(id);
            Assert.notNull(firewallRule,"没有找到该条防火墙规则");
            CloudVendor vendor = cloudVendorRepository.listById(firewallRule.getVendorId());
            Assert.notNull(vendor,"该平台暂无");
            BocloudResult result = firewallDriver.remove(firewallRule.getSangforPolicyId(), vendor.getUuid(), null);
            if (result.isSuccess()){
                firewallRuleRepository.removeById(id);
                return new BocloudResult<>(true,"删除成功");
            }else {
                return new BocloudResult<>(false, result.getMessage());
            }
        }catch (Exception e){
            e.printStackTrace();
            return new BocloudResult<>(false,"删除失败");

        }

    }

    @Override
    public BocloudResult<GridBean<FirewallRule>> update(Pager pager, RequestContext context, Long id,FirewallRule firewallRule) {
        try {
            FirewallRule rule = firewallRuleRepository.listById(id);
            Assert.notNull(rule,"没有找到该条防火墙规则");
            CloudVendor vendor = cloudVendorRepository.listById(rule.getVendorId());
            Assert.notNull(vendor,"该平台暂无");
            SangforFireWallParams model = new SangforFireWallParams();
            model.setName(firewallRule.getName());
            model.setSangforPolicyId(rule.getSangforPolicyId());
            BocloudResult result = firewallDriver.updateV68(vendor.getUuid(), null, model);
            if (result.isSuccess()){
                List<SangforFireWallParams> firewallRuleModels = JSON.parseArray(JSON.toJSON(result.getData()).toString(), SangforFireWallParams.class);
                for (SangforFireWallParams ruleModel : firewallRuleModels){
                    FirewallRule rules = new FirewallRule();
                    BeanUtils.copyProperties(ruleModel,rules);
                    rules.setId(rule.getId());
                    rules.setGmtCreate(rule.getGmtCreate());
                    rules.setMenderId(context.getTarget());
                    rules.setGmtModify(new Date());
                    rules.setVendorId(rule.getVendorId());
                    rules.setDeleted(false);
                    firewallRuleRepository.update(rules);
                }
                return new BocloudResult<>(true,"更新成功");
            }else {
                return new BocloudResult<>(false, result.getMessage());
            }
        }catch (Exception e){
            e.printStackTrace();
            return new BocloudResult<>(false,"更新失败");

        }
    }
}
