package com.bocloud.ims.service.resource;

import java.util.Date;
import java.util.List;
import java.util.Map;

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

import com.bocloud.cmp.driver.storage.VolumeTemplateDriver;
import com.bocloud.cmp.entity.enums.CloudProvider;
import com.bocloud.cmp.model.VolumeTemplateModel;
import com.bocloud.cmp.model.powervc.PowervcConstant;
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.utils.GridHelper;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.Storage;
import com.bocloud.ims.entity.resource.Volume;
import com.bocloud.ims.entity.resource.VolumePool;
import com.bocloud.ims.entity.resource.VolumeTemplate;
import com.bocloud.ims.interfaces.resource.VolumeTemplateService;
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 com.bocloud.ims.repository.resource.VolumeTemplateRepository;
import com.bocloud.ims.service.transporter.vendor.PowervcTransporter;
import com.bocloud.ims.service.transporter.vendor.SmartxTransporter;

/**
 * 存储卷模板Service接口实现
 *
 * @author lkx007
 */
@Service("volumeTemplateService")
public class VolumeTemplateServiceImpl implements VolumeTemplateService {
	private static Logger logger = LoggerFactory.getLogger(VolumeTemplateServiceImpl.class);

	@Autowired
	private CloudVendorRepository cloudVendorRepository;
	@Autowired
	private StorageRepository storageRepository;
	@Autowired
	private VolumePoolRepository volumePoolRepository;
	@Autowired
	private VolumeRepository volumeRepository;
	@Autowired
	private VolumeTemplateRepository volumeTemplateRepository;
	@Autowired
	private PowervcTransporter powervcTransportor;
	@Autowired
	private VolumeTemplateDriver volumeTemplateDriver;
	@Autowired
	private SmartxTransporter smartTransporter;

	@Override
	public BocloudResult<GridBean<VolumeTemplate>> list(Pager pager, RequestContext context) {

		try {
			Integer page = pager.getPage();
			Integer rows = pager.getRows();
			List<Param> params = pager.getParams();
			Map<String, String> sorter = pager.getSorter();
			boolean simple = pager.getSimple();

			int total = volumeTemplateRepository.count(params);
			List<VolumeTemplate> list = volumeTemplateRepository.list(page, rows, params, sorter);
			GridBean gridBean = GridHelper.getBean(page, rows, total, list);
			return new BocloudResult<>(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("查询失败：", e);
			return new BocloudResult<>(false, "查询失败");
		}
	}

	@Override
	public BocloudResult<List<VolumeTemplate>> listByStorage(Long storageId) {
		try {
			List<VolumeTemplate> list = volumeTemplateRepository.listByStorage(storageId);
			return new BocloudResult<>(true, list, "根据storageId查询存储卷模板成功");
		} catch (Exception e) {
			logger.error("根据storageId查询存储卷模板异常：", e);
			return new BocloudResult<>(false, "根据storageId查询存储卷模板失败");
		}
	}

	@Override
	public BocloudResult<List<VolumeTemplate>> listByVendor(Long vendorId) {
		try {
			List<VolumeTemplate> list = volumeTemplateRepository.listByVendor(vendorId);
			return new BocloudResult<>(true, list, "根据vendorId查询存储卷模板成功");
		} catch (Exception e) {
			logger.error("根据vendorId查询存储卷模板异常：", e);
			return new BocloudResult<>(false, "根据vendorId查询存储卷模板失败");
		}
	}

	@Override
	public BocloudResult<VolumeTemplate> create(VolumeTemplate template, RequestContext context) {
		try {
			long userId = context.getTarget();
			CloudVendor cloudVendor = cloudVendorRepository.query(template.getVendorId());
			if (cloudVendor == null) {
				return new BocloudResult<>(false, "未找到平台");
			}
			VolumeTemplateModel model = new VolumeTemplateModel();
			model.setName(template.getName());
			if (CloudProvider.SMARTX.name().equals(cloudVendor.getType())) {
				model.setDescription(template.getDescription());
				model.setReplicaNum(template.getReplicaNum());
				model.setThin(template.getThin());
				model.setWhitelist(template.getWhitelist());
				model.setStripeSize(template.getStripeSize());
				model.setStripeNum(template.getStripeNum());
			} else if (CloudProvider.POWERVC.name().equals(cloudVendor.getType())) {
				VolumeTemplate templateByName = volumeTemplateRepository.getByOriginName(template.getName(), cloudVendor.getId());
				if (templateByName != null) {
					return new BocloudResult<>(false, "该名称已作为其他存储器模板的初始名称存在");
				}
				VolumePool mainPool = volumePoolRepository.get(template.getPoolId());
				if (mainPool == null) {
					return new BocloudResult<>(false, "未找到存储池");
				}
				Storage storage = storageRepository.get(mainPool.getStorageId());
				if (storage == null) {
					return new BocloudResult<>(false, "未找到存储服务器");
				}
				model.setStorageName(storage.getHost());
				model.setPoolName(mainPool.getName());

				if (PowervcConstant.VOLUME_TEMPLATE_TYPE_COMMON.equals(template.getType())) {
					model.setCapacityPercent(-1F);
					model.setWarningPercent(0F);
					model.setCompress(false);
					model.setAutoExpand(false);
				} else if (PowervcConstant.VOLUME_TEMPLATE_TYPE_SIMPLE.equals(template.getType())) {
					model.setCapacityPercent(PowervcConstant.VOLUME_TEMPLATE_CAPACITY_PERCENT);
					model.setWarningPercent(PowervcConstant.VOLUME_TEMPLATE_WARNING_PERCENT);
					model.setCompress(false);
					model.setAutoExpand(true);
					model.setGrainsize(PowervcConstant.VOLUME_TEMPLATE_GRAINSIZE);
				} else if (PowervcConstant.VOLUME_TEMPLATE_TYPE_COMPRESS.equals(template.getType())) {
					model.setCapacityPercent(PowervcConstant.VOLUME_TEMPLATE_CAPACITY_PERCENT);
					model.setWarningPercent(PowervcConstant.VOLUME_TEMPLATE_WARNING_PERCENT);
					model.setCompress(true);
					model.setAutoExpand(true);
				} else {
					return new BocloudResult<>(false, "未找到卷类型");
				}
			}

			BocloudResult bocloudResult = volumeTemplateDriver.create(cloudVendor.getUuid(), model);
			if (bocloudResult.isFailed()) {
				return bocloudResult;
			}
			if (CloudProvider.POWERVC.name().equals(cloudVendor.getType())) {
				model = (VolumeTemplateModel) bocloudResult.getData();
				template = powervcTransportor.insertOrUpdate(cloudVendor, model, userId);
			} else if (CloudProvider.SMARTX.name().equals(cloudVendor.getType())) {
				model = (VolumeTemplateModel) bocloudResult.getData();
				VolumeTemplate entity = new VolumeTemplate();
				smartTransporter.convert(model, entity);
				entity.setVendorId(cloudVendor.getId());
				entity.setCreatorId(userId);
				entity.setGmtCreate(new Date());
				volumeTemplateRepository.save(entity);
			}
			return new BocloudResult<>(true, template, "创建成功");
		} catch (Exception e) {
			logger.error("创建失败：", e);
			return new BocloudResult<>(false, "创建失败");
		}
	}

	@Override
	public BocloudResult<VolumeTemplate> modify(VolumeTemplate template, RequestContext context) {
		try {
			long userId = context.getTarget();
			VolumeTemplate templateOld = volumeTemplateRepository.get(template.getId());
			if (templateOld == null) {
				return new BocloudResult<>(false, "未找到数据");
			}
			CloudVendor cloudVendor = cloudVendorRepository.query(templateOld.getVendorId());
			if (cloudVendor == null) {
				return new BocloudResult<>(false, "未找到平台");
			}

			VolumeTemplateModel model = new VolumeTemplateModel();
			model.setUuid(templateOld.getUuid());
			model.setName(template.getName());

			if (CloudProvider.POWERVC.name().equals(cloudVendor.getType())) {
				VolumePool mainPool = volumePoolRepository.get(template.getPoolId());
				if (mainPool == null) {
					return new BocloudResult<>(false, "未找到存储池");
				}
				Storage storage = storageRepository.get(mainPool.getStorageId());
				if (storage == null) {
					return new BocloudResult<>(false, "未找到存储服务器");
				}
				model.setStorageName(storage.getHost());
				model.setPoolName(mainPool.getName());
				if (PowervcConstant.VOLUME_TEMPLATE_TYPE_COMMON.equals(template.getType())) {
					model.setCapacityPercent(-1F);
					model.setWarningPercent(0F);
					model.setCompress(false);
					model.setAutoExpand(false);
				} else if (PowervcConstant.VOLUME_TEMPLATE_TYPE_SIMPLE.equals(template.getType())) {
					model.setCapacityPercent(PowervcConstant.VOLUME_TEMPLATE_CAPACITY_PERCENT);
					model.setWarningPercent(PowervcConstant.VOLUME_TEMPLATE_WARNING_PERCENT);
					model.setCompress(false);
					model.setAutoExpand(true);
					model.setGrainsize(PowervcConstant.VOLUME_TEMPLATE_GRAINSIZE);
				} else if (PowervcConstant.VOLUME_TEMPLATE_TYPE_COMPRESS.equals(template.getType())) {
					model.setCapacityPercent(PowervcConstant.VOLUME_TEMPLATE_CAPACITY_PERCENT);
					model.setWarningPercent(PowervcConstant.VOLUME_TEMPLATE_WARNING_PERCENT);
					model.setCompress(true);
					model.setAutoExpand(true);
				} else {
					return new BocloudResult<>(false, "未找到卷类型");
				}
			} else if (CloudProvider.SMARTX.name().equals(cloudVendor.getType())) {
				model.setDescription(template.getDescription());
				model.setWhitelist(template.getWhitelist());
			}
			BocloudResult bocloudResult = volumeTemplateDriver.modify(cloudVendor.getUuid(), model);
			if (bocloudResult.isFailed()) {
				return bocloudResult;
			}

			if (CloudProvider.POWERVC.name().equals(cloudVendor.getType())) {
				model = (VolumeTemplateModel) bocloudResult.getData();
				template = powervcTransportor.insertOrUpdate(cloudVendor, model, userId);
			} else {
				templateOld.setName(template.getName());
				templateOld.setDescription(template.getDescription());
				templateOld.setWhitelist(template.getWhitelist());
				volumeTemplateRepository.update(templateOld);
			}
			return new BocloudResult<>(true, template, "修改成功");
		} catch (Exception e) {
			logger.error("修改失败：", e);
			return new BocloudResult<>(false, "修改失败");
		}
	}

	@Override
	public BocloudResult<String> remove(long id, RequestContext context) {
		try {
			VolumeTemplate template = volumeTemplateRepository.get(id);
			if (template == null) {
				return new BocloudResult<>(false, "未找到数据");
			}
			CloudVendor cloudVendor = cloudVendorRepository.query(template.getVendorId());
			if (cloudVendor == null) {
				return new BocloudResult<>(false, "未找到平台");
			}
			if (CloudProvider.POWERVC.name().equals(cloudVendor.getType())) {
				List<Volume> volumes = volumeRepository.listByTemplateId(template.getId());
				if (volumes != null && volumes.size() > 0) {
					return new BocloudResult<>(false, "无法删除存储器模板" + template.getName() + "，因为存在正在使用此模板的存储卷");
				}
			}
			BocloudResult bocloudResult = volumeTemplateDriver.remove(template.getUuid(), cloudVendor.getUuid());
			if (bocloudResult.isFailed()) {
				return bocloudResult;
			}
			volumeTemplateRepository.remove(template.getId());
			return new BocloudResult<>(true, "删除成功");
		} catch (Exception e) {
			logger.error("删除失败：", e);
			return new BocloudResult<>(false, "删除失败");
		}
	}

	@Override
	public BocloudResult<VolumeTemplate> detail(long id) {
		try {
			VolumeTemplate template = volumeTemplateRepository.get(id);
			return new BocloudResult<>(true, template, "查询存储模板详情成功");
		} catch (Exception e) {
			logger.error("查询存储模板详情异常：", e);
			return new BocloudResult<>(false, "查询存储模板详情失败");
		}
	}
}
