package com.bocloud.ims.booter.controller.resource;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.model.VolBean;
import com.bocloud.common.annotations.Log;
import com.bocloud.common.enums.BoCloudService;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.JSONTools;
import com.bocloud.common.utils.ResultTools;
import com.bocloud.ims.entity.resource.CloudServer;
import com.bocloud.ims.entity.resource.Volume;
import com.bocloud.ims.interfaces.resource.FlashCopyService;
import com.bocloud.ims.interfaces.resource.MdiskVolumeService;
import com.bocloud.ims.interfaces.resource.ServerVolumeService;
import com.bocloud.ims.interfaces.resource.VolumeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(value = "卷信息管理", tags = "卷信息管理")
public class VolumeController {

	@Autowired
	private VolumeService volumeService;
	@Autowired
	private ServerVolumeService serverVolumeService;
	@Autowired
	private MdiskVolumeService mdiskVolumeService;
	@Autowired
	private FlashCopyService flashCopyService;

	/**
	 * 查询卷列表
	 * 
	 * @param pager
	 * @param action
	 * @param condition
	 * @param context
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "查询卷信息列表", httpMethod = "GET")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "查询卷列表")
	@GetMapping("/v1/volumes")
	public BocloudResult<GridBean<Volume>> list(Pager pager, @Value(Common.REQ_CONTEXT) RequestContext context) {
		// 分页查询volume
		return volumeService.list(pager, context);
	}

	/**
	 * 通过condition查询卷信息列表
	 *
	 * @param pager
	 * @param action
	 * @param condition
	 * @param context
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "通过condition查询卷信息列表", httpMethod = "GET")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "查询卷列表")
	@GetMapping("/v1/volumes/condition")
	public BocloudResult condition(Pager pager, @RequestParam(value = "action", required = false) String action,
			@RequestParam(value = Common.CONDITION, required = false) String condition,
			@Value(Common.REQ_CONTEXT) RequestContext context) {
		if (!StringUtils.isEmpty(condition)) {
			JSONObject object = JSONObject.parseObject(condition);
			action = object.getString("condition");
		}
		if (StringUtils.isEmpty(action) || "common".equals(action)) {
			// 分页查询volume
			return volumeService.list(pager, context);
		} else if ("listByMdisk".equals(action)) {
			// 按照Mdisk查询卷
			Map<String, Object> paramMap = new HashMap<>(8);
			if (pager.getParams() != null && pager.getParams().size() > 0) {
				for (Param param : pager.getParams()) {
					paramMap.putAll(param.getParam());
				}
			}
			if (!paramMap.containsKey("mdiskId")) {
				return new BocloudResult(false, "缺少参mdiskId");
			}
			long mdiskId = Long.parseLong(paramMap.get("mdiskId").toString());
			return mdiskVolumeService.listVolumeByMdisk(pager.getPage(), pager.getRows(), mdiskId, paramMap,
					pager.getSorter());
		} else if ("listFlashCopyTargetVolume".equals(action)) {
			// 按照原卷查询FlashCopy目标卷
			Map<String, Object> paramMap = new HashMap<>(8);
			if (pager.getParams() != null && pager.getParams().size() > 0) {
				for (Param param : pager.getParams()) {
					paramMap.putAll(param.getParam());
				}
			}
			if (!paramMap.containsKey("volumeId")) {
				return new BocloudResult(false, "缺少参volumeId");
			}
			long volumeId = Long.parseLong(paramMap.get("volumeId").toString());
			return flashCopyService.listTargetVolumeFromDB(pager.getPage(), pager.getRows(), volumeId, paramMap,
					pager.getSorter());
		} else if ("listforpowervcvmcreate".equals(action)) {
			// Powervc 创建虚拟机的时候，查询可使用的卷
			Map<String, Object> paramMap = new HashMap<>(8);
			if (pager.getParams() != null && pager.getParams().size() > 0) {
				for (Param param : pager.getParams()) {
					paramMap.putAll(param.getParam());
				}
			}
			if (!paramMap.containsKey(Common.VENDORID)) {
				return new BocloudResult(false, "缺少参vendorId");
			}
			long vendorId = Long.parseLong(paramMap.get(Common.VENDORID).toString());
			String keyword = paramMap.get("keyword") == null ? null : paramMap.get("keyword").toString();
			return volumeService.listForPowervcVMCreate(pager.getPage(), pager.getRows(), keyword, vendorId);
		} else if ("listforpowervcvmattach".equals(action)) {
			// Powervc 创建虚拟机的时候，查询可使用的卷
			Map<String, Object> paramMap = new HashMap<>(8);
			if (pager.getParams() != null && pager.getParams().size() > 0) {
				for (Param param : pager.getParams()) {
					paramMap.putAll(param.getParam());
				}
			}
			if (!paramMap.containsKey(Common.VENDORID)) {
				return new BocloudResult(false, "缺少参vendorId");
			}
			if (!paramMap.containsKey("vmId")) {
				return new BocloudResult(false, "缺少参vmId");
			}
			long vendorId = Long.parseLong(paramMap.get(Common.VENDORID).toString());
			long vmId = Long.parseLong(paramMap.get("vmId").toString());
			String keyword = paramMap.get("keyword") == null ? null : paramMap.get("keyword").toString();
			return volumeService.listForPowervcVMAttach(pager.getPage(), pager.getRows(), keyword, vendorId, vmId);
		} else if ("listforpowervcimagecreate".equals(action)) {
			// Powervc 创建虚拟机的时候，查询可使用的卷
			Map<String, Object> paramMap = new HashMap<>(8);
			if (pager.getParams() != null && pager.getParams().size() > 0) {
				for (Param param : pager.getParams()) {
					paramMap.putAll(param.getParam());
				}
			}
			if (!paramMap.containsKey(Common.VENDORID)) {
				return new BocloudResult(false, "缺少参vendorId");
			}
			long vendorId = Long.parseLong(paramMap.get(Common.VENDORID).toString());
			String keyword = paramMap.get("keyword") == null ? null : paramMap.get("keyword").toString();
			return volumeService.listForPowervcImageCreate(pager.getPage(), pager.getRows(), keyword, vendorId);
		} else if ("listByStatus".equalsIgnoreCase(action)) {
			return volumeService.listByStatus(condition, context);
		} else if ("listBackupResources".equalsIgnoreCase(action)) {
			return volumeService.listBackupResources(condition, context);
		} else if ("listbyvendor".equalsIgnoreCase(action)) {
			JSONObject object = JSONObject.parseObject(condition);
			return volumeService.listByVendor(object.getLong(Common.VENDORID));
		} else if ("listbyimage".equalsIgnoreCase(action)) {
			JSONObject object = JSONObject.parseObject(condition);
			return volumeService.listByImage(object.getLong("imageId"));
		} else if ("listInSyncedSet".equalsIgnoreCase(action)) {
			Map<String, Object> paramMap = new HashMap<>(8);
			if (pager.getParams() != null && pager.getParams().size() > 0) {
				for (Param param : pager.getParams()) {
					paramMap.putAll(param.getParam());
				}
			}
			return volumeService.listInSyncedSet(pager.getPage(), pager.getRows(), paramMap, pager.getSorter());
		} else if ("listNotInSyncedSet".equalsIgnoreCase(action)) {
			Map<String, Object> paramMap = new HashMap<>(8);
			if (pager.getParams() != null && pager.getParams().size() > 0) {
				for (Param param : pager.getParams()) {
					paramMap.putAll(param.getParam());
				}
			}
			return volumeService.listNotInSyncedSet(pager.getPage(), pager.getRows(), paramMap, pager.getSorter());
		} else if ("listByHostForXsky".equalsIgnoreCase(action)) {
			Map<String, Object> paramMap = new HashMap<>(8);
			if (pager.getParams() != null && pager.getParams().size() > 0) {
				for (Param param : pager.getParams()) {
					paramMap.putAll(param.getParam());
				}
			}
			if (!paramMap.containsKey("hostId")) {
				return new BocloudResult(false, "缺少参hostId");
			}
			long hostId = Long.parseLong(paramMap.get("hostId").toString());
			return volumeService.listByHost(pager.getPage(), pager.getRows(), hostId, paramMap, pager.getSorter());
		} else if ("listByCondition".equalsIgnoreCase(action)) {
			return volumeService.listByCondition(JSONObject.parseObject(condition), context);
		} else if ("listByVmId".equalsIgnoreCase(action)) {
			return volumeService.listByVmId(JSONObject.parseObject(condition));
		} else if ("vmDisks".equalsIgnoreCase(action)) {
			return volumeService.listDataDisks(JSONObject.parseObject(condition));
		}
		return new BocloudResult<>(false, "查询类型不支持");
	}

	/**
	 * 根据storage查询卷
	 *
	 * @param params
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "根据storage查询卷", httpMethod = "POST")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "根据storage查询卷")
	@PostMapping("/volume/listbystorage")
	public BocloudResult<List<Volume>> listByStorage(@RequestParam(value = Common.PARAMS) String params) {
		JSONObject object = JSONTools.isJSONObj(params);
		if (null != object) {
			return volumeService.listByStorage(object.getLong("storageId"));
		} else {
			return ResultTools.formatErrResult();
		}
	}

	/**
	 * 根据存储器模板查询卷
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "根据存储器模板查询卷", httpMethod = "GET")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "根据存储器模板查询卷")
	@GetMapping("/v1/storages/templates/{id}/volumes")
	public BocloudResult<List<Volume>> listByTemplate(@PathVariable(value = Common.ID) Long id) {
		return volumeService.listByTemplate(id);
	}

	/**
	 * 详情
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "查看卷详情", httpMethod = "GET")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "查看卷详情")
	@GetMapping("/v1/volumes/{id}")
	public BocloudResult<Volume> detail(@PathVariable(value = Common.ID) Long id) {
		return volumeService.detail(id);
	}

	/**
	 * 创建
	 *
	 * @param params
	 * @param context
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "创建卷", httpMethod = "POST")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "创建卷")
	@PostMapping("/v1/volumes")
	public BocloudResult<String> create(@RequestBody Volume volume, @Value(Common.REQ_CONTEXT) RequestContext context) {
		return volumeService.create(volume, context);
	}

	/**
	 * 删除
	 *
	 * @param id
	 * @param context
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "删除卷", httpMethod = "DELETE")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "删除卷")
	@DeleteMapping("/v1/volumes/{id}")
	public BocloudResult<String> remove(@RequestParam(value = Common.PARAMS, required = false) String params,
			@PathVariable(value = Common.ID) Long id, @Value(Common.REQ_CONTEXT) RequestContext context) {
		return volumeService.remove(id, params, context);
	}

	/**
	 * 修改
	 *
	 * @param bean
	 * @param id
	 * @param context
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "修改卷", httpMethod = "PUT")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "修改卷")
	@PutMapping("/v1/volumes/{id}")
	public BocloudResult<String> modify(@RequestBody VolBean bean, @PathVariable(value = Common.ID) Long id,
			@Value(Common.REQ_CONTEXT) RequestContext context) {
		if (bean.getId() == null) {
			bean.setId(id);
		}
		return volumeService.modify(bean, context);
	}

	/**
	 * 挂载
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "挂载卷", httpMethod = "PATCH")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "挂载卷")
	@PatchMapping("/v1/volumes/{id}")
	public BocloudResult attach(@PathVariable(value = Common.ID) Long id,
			@Value(Common.REQ_CONTEXT) RequestContext context, @RequestBody VolBean volBean) {
		volBean.setId(id);
		return volumeService.operations(volBean, context);
	}

	/**
	 * 查看主机列表
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "查看主机列表", httpMethod = "GET")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "查看主机列表")
	@GetMapping("/v1/volumes/{id}/vms")
	public BocloudResult<List<CloudServer>> servers(@PathVariable(value = Common.ID) Long id,
			@RequestParam(value = Common.CONDITION, required = false) String condition,
			@Value(Common.REQ_CONTEXT) RequestContext context) {
		if (StringUtils.isEmpty(condition)) {
			return volumeService.servers(id);
		} else if ("powervc".equals(condition)) {
			return serverVolumeService.listServerByVolume(id);
		}
		return new BocloudResult(false, "不支持的condition参数值");
	}

	/**
	 * 批量删除卷
	 *
	 * @param params
	 * @param context
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "批量删除卷", httpMethod = "DELETE")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "批量删除卷")
	@DeleteMapping("/v1/volumes")
	public BocloudResult<String> batchRemove(@RequestBody List<Long> ids,
			@Value(Common.REQ_CONTEXT) RequestContext context) {
		return volumeService.batchRemove(ids, context);
	}

	/**
	 * 上传镜像
	 *
	 * @param params
	 * @param context
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "上传镜像", httpMethod = "POST")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "上传镜像")
	@PostMapping("/v1/volumes/{id}/images")
	public BocloudResult<String> uploadToImage(@PathVariable(value = Common.ID) Long id,
			@RequestParam(value = Common.PARAMS) String params, @Value(Common.REQ_CONTEXT) RequestContext context) {
		JSONObject object = JSONTools.isJSONObj(params);
		if (null != object) {
			return volumeService.uploadToImage(params, context);
		} else {
			return ResultTools.formatErrResult();
		}
	}

	/**
	 * 汇总卷数量
	 *
	 * @param userId
	 * @param projectId
	 * @param tenantId
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "汇总卷数量", httpMethod = "GET")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "汇总卷数量")
	@PostMapping("/volume/count")
	public BocloudResult<Integer> count(@RequestParam(value = "userId") Long userId,
			@RequestParam(value = "projectId") Long projectId, @RequestParam(value = Common.TENANTID) Long tenantId) {
		return volumeService.count(userId, projectId, tenantId);
	}

	/**
	 * 管理存储上现有受支持的卷
	 *
	 * @param params
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "管理存储上现有受支持的卷", httpMethod = "POST")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "管理存储上现有受支持的卷")
	@PostMapping("/v1/storages/{id}/volumes")
	public BocloudResult<String> onboard(@RequestParam(value = Common.PARAMS) String params,
			@PathVariable(value = Common.ID) Long id, @Value(Common.REQ_CONTEXT) RequestContext context) {
		JSONObject object = JSONTools.isJSONObj(params);
		if (null != object) {
			return volumeService.onboard(params, context);
		} else {
			return ResultTools.formatErrResult();
		}
	}

	/**
	 * 取消管理存储上的卷
	 *
	 * @param params
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "取消管理存储上的卷", httpMethod = "DELETE")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "取消管理存储上的卷")
	@DeleteMapping("/v1/storages/{id}/volumes")
	public BocloudResult<String> unmanage(@RequestParam(value = Common.PARAMS) String params,
			@PathVariable(value = Common.ID) Long id, @Value(Common.REQ_CONTEXT) RequestContext context) {
		JSONObject object = JSONTools.isJSONObj(params);
		if (null != object) {
			return volumeService.unmanage(context, object.getLong(Common.VENDORID), object.getLong("storageId"),
					JSONObject.parseArray(object.getString("volumeIds"), Long.class));
		} else {
			return ResultTools.formatErrResult();
		}
	}

	/**
	 * 卷移入卷组
	 *
	 * @param params
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "卷移入卷组", httpMethod = "POST")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "卷移入卷组")
	@PostMapping("/v1/volumes/{id}/groups")
	public BocloudResult addGroups(@RequestParam(value = Common.PARAMS) String params,
			@PathVariable(value = Common.ID) Long id, @Value(Common.REQ_CONTEXT) RequestContext context) {
		return volumeService.addGroups(id, params, context);
	}

	/**
	 * 卷移出卷组
	 *
	 * @param params
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "卷移出卷组", httpMethod = "DELETE")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "卷移出卷组")
	@DeleteMapping("/v1/volumes/{id}/groups")
	public BocloudResult removeGroups(@RequestParam(value = Common.PARAMS) String params,
			@PathVariable(value = Common.ID) Long id, @Value(Common.REQ_CONTEXT) RequestContext context) {
		return volumeService.removeGroups(id, params, context);
	}

	/**
	 * 卷迁移
	 *
	 * @param bean
	 * @param id
	 * @param context
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "卷迁移", httpMethod = "POST")
	@Log(module = BoCloudService.IMS, target = "卷", operation = "卷迁移")
	@PostMapping("/v1/volumes/{id}/migrate")
	public BocloudResult migrateVolume(@RequestBody Volume bean, @PathVariable(value = Common.ID) Long id,
			@Value(Common.REQ_CONTEXT) RequestContext context) {
		bean.setId(id);
		return volumeService.migrateVolume(bean, context);
	}
}
