package com.bocloud.ims.service.resource;

import com.bocloud.common.model.*;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.Storage;
import com.bocloud.ims.entity.resource.VolumePool;
import com.bocloud.ims.interfaces.resource.VolumePoolService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.StorageRepository;
import com.bocloud.ims.repository.resource.VolumePoolRepository;
import com.bocloud.ims.repository.resource.VolumeRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author luyanchao
 * @since 2019/3/4 14:07
 */
@Service("volumePoolService")
public class VolumePoolServiceImpl implements VolumePoolService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private ApplicationContext applicationContext;
	@Autowired
	private VolumePoolRepository poolRepository;
	@Autowired
	private StorageRepository storageRepository;
	@Autowired
	private CloudVendorRepository vendorRepository;
	@Autowired
	private VolumeRepository volumeRepository;

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

			List<VolumePool> list = poolRepository.list(page, rows, params, sorter);
			if (null != simple && simple) {
				GridBean gridBean = new GridBean(1, Integer.MAX_VALUE, list.size(), list);
				return new BocloudResult<>(true, gridBean, "查询成功！");
			}
			DecimalFormat decimalFormat = new DecimalFormat("######0.00");
			for (VolumePool pool : list) {
				Optional.ofNullable(pool.getCapacity()).map(decimalFormat::format).map(Double::valueOf)
						.ifPresent(pool::setCapacity);
				Optional.ofNullable(pool.getUsedCapacity()).map(decimalFormat::format).map(Double::valueOf)
						.ifPresent(pool::setUsedCapacity);
				pool.setVolumes(volumeRepository.listByPoolId(pool.getId()));
			}
			int total = poolRepository.count(params);
			GridBean gridBean = new GridBean(page, rows, total, list);
			return new BocloudResult<>(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("Get error message：", e);
			return new BocloudResult<>(false, "查询失败");
		}
	}

	@Override
	public BocloudResult<List<VolumePool>> listByStorage(long storageId) {
		try {
			List<VolumePool> volumePools = poolRepository.listByStorage(storageId);
			return new BocloudResult<>(true, volumePools, "查询成功");
		} catch (Exception e) {
			logger.error("查询失败：", e);
			return new BocloudResult<>(false, "查询失败");
		}
	}

	@Override
	public BocloudResult<String> create(VolumePool pool, RequestContext context) {
		try {
			CloudVendor cloudVendor = null;
			if (pool.getVendorId() != null) {
				cloudVendor = vendorRepository.query(pool.getVendorId());
			} else if (pool.getStorageId() != null) {
				Storage storage = storageRepository.get(pool.getStorageId());
				if (storage == null || storage.getDeleted()) {
					return new BocloudResult<>(false, "未找到存储或该存储已经被删除");
				}
				cloudVendor = vendorRepository.query(storage.getVendorId());
			}
			if (cloudVendor == null || cloudVendor.getDeleted()) {
				return new BocloudResult<>(false, "未找到平台或该平台已经被删除");
			}
			VolumePoolService service = applicationContext.getBean(
					cloudVendor.getType().toLowerCase() + VolumePoolService.class.getSimpleName(),
					VolumePoolService.class);
			return service.create(pool, context);
		} catch (Exception e) {
			logger.error("创建失败：", e);
			return new BocloudResult<>(false, "创建失败：" + e.getMessage());
		}
	}

	@Override
	public BocloudResult<String> modify(VolumePool pool, RequestContext context) {
		try {
			if (pool.getId() == null) {
				return new BocloudResult<>(false, "需要参数id");
			}
			VolumePool oldPool = poolRepository.get(pool.getId());
			if (oldPool == null || oldPool.getDeleted()) {
				return new BocloudResult<>(false, "未找到存储池或该存储池已经被删除");
			}
			CloudVendor cloudVendor = vendorRepository.query(oldPool.getVendorId());
			if (cloudVendor == null || cloudVendor.getDeleted()) {
				return new BocloudResult<>(false, "未找到平台或该平台已经被删除");
			}
			VolumePoolService service = applicationContext.getBean(
					cloudVendor.getType().toLowerCase() + VolumePoolService.class.getSimpleName(),
					VolumePoolService.class);
			return service.modify(pool, context);
		} catch (Exception e) {
			logger.error("创建失败：", e);
			return new BocloudResult<>(false, "创建失败：" + e.getMessage());
		}
	}

	@Override
	public BocloudResult<String> remove(long poolId, boolean force, RequestContext context) {
		try {
			VolumePool oldPool = poolRepository.get(poolId);
			if (oldPool == null || oldPool.getDeleted()) {
				return new BocloudResult<>(false, "未找到存储池或该存储池已经被删除");
			}
			CloudVendor cloudVendor = vendorRepository.query(oldPool.getVendorId());
			if (cloudVendor == null || cloudVendor.getDeleted()) {
				return new BocloudResult<>(false, "未找到平台或该平台已经被删除");
			}
			VolumePoolService service = applicationContext.getBean(
					cloudVendor.getType().toLowerCase() + VolumePoolService.class.getSimpleName(),
					VolumePoolService.class);
			return service.remove(poolId, force, context);
		} catch (Exception e) {
			logger.error("创建失败：", e);
			return new BocloudResult<>(false, "创建失败：" + e.getMessage());
		}
	}

	@Override
	public BocloudResult addMember(long poolId, List<Long> memberIds, RequestContext context) {
		try {
			VolumePool oldPool = poolRepository.get(poolId);
			if (oldPool == null || oldPool.getDeleted()) {
				return new BocloudResult<>(false, "未找到存储池或该存储池已经被删除");
			}
			CloudVendor cloudVendor = vendorRepository.query(oldPool.getVendorId());
			if (cloudVendor == null || cloudVendor.getDeleted()) {
				return new BocloudResult<>(false, "未找到平台或该平台已经被删除");
			}
			VolumePoolService service = applicationContext.getBean(
					cloudVendor.getType().toLowerCase() + VolumePoolService.class.getSimpleName(),
					VolumePoolService.class);
			return service.addMember(poolId, memberIds, context);
		} catch (Exception e) {
			logger.error("创建失败：", e);
			return new BocloudResult<>(false, "创建失败：" + e.getMessage());
		}
	}

	@Override
	public BocloudResult removeMember(long poolId, List<Long> memberIds, RequestContext context) {
		try {
			VolumePool oldPool = poolRepository.get(poolId);
			if (oldPool == null || oldPool.getDeleted()) {
				return new BocloudResult<>(false, "未找到存储池或该存储池已经被删除");
			}
			CloudVendor cloudVendor = vendorRepository.query(oldPool.getVendorId());
			if (cloudVendor == null || cloudVendor.getDeleted()) {
				return new BocloudResult<>(false, "未找到平台或该平台已经被删除");
			}
			VolumePoolService service = applicationContext.getBean(
					cloudVendor.getType().toLowerCase() + VolumePoolService.class.getSimpleName(),
					VolumePoolService.class);
			return service.removeMember(poolId, memberIds, context);
		} catch (Exception e) {
			logger.error("创建失败：", e);
			return new BocloudResult<>(false, "创建失败：" + e.getMessage());
		}
	}

	@Override
	public BocloudResult<VolumePool> detail(long poolId) {
		try {
			VolumePool pool = poolRepository.get(poolId);
			return new BocloudResult<>(true, pool, "查询成功");
		} catch (Exception e) {
			logger.error("查询失败：", e);
			return new BocloudResult<>(false, "查询失败");
		}
	}
}
