package com.bocloud.ims.service.resource;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.bocloud.cmp.driver.network.GwQosDriver;
import com.bocloud.cmp.model.GwQosModel;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.GridBean;
import com.bocloud.common.model.Pager;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.model.SimpleBean;
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.QosPolicy;
import com.bocloud.ims.entity.resource.QosPolicyRules;
import com.bocloud.ims.interfaces.resource.QosPolicyRulesService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.QosPolicyRepository;
import com.bocloud.ims.repository.resource.QosPolicyRulesRepository;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * qos policy rules service impl
 * 
 * @author ymh
 * @时间 2019年11月13日
 */
@Service("qosPolicyRulesService")
public class QosPolicyRulesServiceImpl implements QosPolicyRulesService {

	private static Logger logger = LoggerFactory.getLogger(QosPolicyRulesServiceImpl.class);
	@Autowired
	private LockFactory lockFactory;
	@Autowired
	private QosPolicyRulesRepository qosPolicyRulesRepository;
	@Autowired
	private GwQosDriver gwQosDriver;
	@Autowired
	private CloudVendorRepository cloudVendorRepository;
	@Autowired
	private QosPolicyRepository qosPolicyRepository;

	@Override
	public BocloudResult<GridBean<QosPolicyRules>> list(Pager pager) {
		List<QosPolicyRules> list = Lists.newArrayList();
		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("gmtCreate", Common.ONE);
			Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
			Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);
			int total = qosPolicyRulesRepository.count(params);
			if (simple) {
				List<SimpleBean> beans = qosPolicyRulesRepository.list(params, sorter);
				gridBean = new GridBean(1, 1, total, beans);
			} else {
				list = qosPolicyRulesRepository.list(page, rows, params, sorter);
				gridBean = GridHelper.getBean(page, rows, total, list);
			}
			return new BocloudResult<>(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("list qosPolicy failure:", e);
			return new BocloudResult<>(false, "查询失败", null, null);
		}

	}

	@Override
	public BocloudResult<String> create(QosPolicyRules qosPolicyRules, RequestContext context) {
		try {
			CloudVendor cloudVendor = cloudVendorRepository.query(qosPolicyRules.getVendorId());
			if (null == cloudVendor) {
				return new BocloudResult<>(false, "云平台不存在！");
			}
			QosPolicy qosPolicy = qosPolicyRepository.query(qosPolicyRules.getId());
			if (null == qosPolicy) {
				return new BocloudResult<>(false, "策略不存在！");
			}
			GwQosModel gwQosModel = new GwQosModel();
			BeanUtils.copyProperties(qosPolicyRules, gwQosModel);
			qosPolicyRules.setId(null);
			gwQosModel.setPolicyUuid(qosPolicy.getPolicyUuid());
			BocloudResult qosRulesCreate = gwQosDriver.qosRulesCreate(gwQosModel, cloudVendor.getUuid());
			if (qosRulesCreate.isSuccess()) {
				GwQosModel model = (GwQosModel) qosRulesCreate.getData();
				QosPolicyRules rule = new QosPolicyRules();
				BeanUtils.copyProperties(model, rule);
				rule.setPolicyId(qosPolicy.getId());
				rule.setMenderId(context.getTarget());
				rule.setPolicyUuid(qosPolicy.getPolicyUuid());
				rule.setVendorId(qosPolicy.getVendorId());
				rule.setCreatorId(context.getTarget());
				qosPolicyRulesRepository.save(rule);
				return new BocloudResult<>(true, "新建成功！");
			} else {
				return new BocloudResult<>(false, qosRulesCreate.getMessage());
			}
		} catch (Exception e) {
			logger.error("新建失败：" + e.getMessage());
			return new BocloudResult<>(false, "新建失败：" + e.getMessage());
		}
	}

	@Override
	public BocloudResult<String> modify(QosPolicyRules qosPolicyRules, Long userId) {
		String path = QosPolicyRules.class.getSimpleName() + "_" + qosPolicyRules.getId();
		try (BocloudACLock lock = lockFactory.getACLock(path)) {
			Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
			QosPolicyRules policyRules = qosPolicyRulesRepository.query(qosPolicyRules.getId());
			if (null == policyRules) {
				return new BocloudResult<>(false, "数据不存在！");
			}
			CloudVendor cloudVendor = cloudVendorRepository.query(policyRules.getVendorId());
			if (null == cloudVendor) {
				return new BocloudResult<>(false, "云平台不存在！");
			}
			GwQosModel gwQosModel = new GwQosModel();
			BeanUtils.copyProperties(qosPolicyRules, gwQosModel);
			BocloudResult qosRulesModify = gwQosDriver.qosRulesModify(gwQosModel, cloudVendor.getUuid());
			if (qosRulesModify.isSuccess()) {
				GwQosModel model = (GwQosModel) qosRulesModify.getData();
				BeanUtils.copyProperties(model, policyRules);
				qosPolicyRulesRepository.update(policyRules);
				return new BocloudResult<>(true, "编辑成功！");
			} else {
				return new BocloudResult<>(false, qosRulesModify.getMessage());
			}
		} catch (Exception e) {
			logger.error("编辑失败：" + e.getMessage());
			return new BocloudResult<>(false, "编辑失败：" + e.getMessage());
		}
	}

	@Override
	public BocloudResult<String> remove(Long id, RequestContext context) {
		try {
			QosPolicyRules qosPolicyRules = qosPolicyRulesRepository.query(id);
			if (null == qosPolicyRules) {
				return new BocloudResult<>(false, "删除失败");
			}
			CloudVendor cloudVendor = cloudVendorRepository.query(qosPolicyRules.getVendorId());
			if (null == cloudVendor) {
				return new BocloudResult<>(false, "云平台不存在！");
			}
			QosPolicy qosPolicy = qosPolicyRepository.query(qosPolicyRules.getPolicyId());
			if (null == qosPolicy) {
				return new BocloudResult<>(false, "策略数据异常！");
			}
			GwQosModel gwQosModel = new GwQosModel();
			gwQosModel.setRuleUuid(qosPolicyRules.getRuleUuid());
			gwQosModel.setPolicyUuid(qosPolicy.getPolicyUuid());
			BocloudResult qosRulesRemove = gwQosDriver.qosRulesRemove(gwQosModel, cloudVendor.getUuid());
			if (qosRulesRemove.isSuccess()) {
				qosPolicyRulesRepository.remove(id, context.getTarget());
				return new BocloudResult<>(true, "删除成功！");
			} else {
				return new BocloudResult<>(false, qosRulesRemove.getMessage());
			}
		} catch (Exception e) {
			logger.error("删除失败：" + e.getMessage());
			return new BocloudResult<>(false, "删除失败：" + e.getMessage());
		}
	}

	@Override
	public BocloudResult<QosPolicyRules> detail(Long id) {
		try {
			QosPolicyRules qosPolicyRules = qosPolicyRulesRepository.query(id);
			if (null == qosPolicyRules) {
				return new BocloudResult<>(false, "删除失败");
			}
			return new BocloudResult<>(true, qosPolicyRules, "success!");
		} catch (Exception e) {
			logger.error("查询失败：" + e.getMessage());
			return new BocloudResult<>(false, "查询失败：" + e.getMessage());
		}
	}

}
