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

import com.alibaba.fastjson.JSONObject;
import com.bocloud.common.annotations.Log;
import com.bocloud.common.enums.BoCloudService;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.GridBean;
import com.bocloud.common.model.Pager;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.Common;
import com.bocloud.ims.entity.resource.CloudBill;
import com.bocloud.ims.interfaces.resource.CloudBillService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/v1/cloud/bills")
@Api(value = "账单管理", tags = "账单管理")
public class CloudBillController {

	@Autowired
	private CloudBillService cloudBillService;

	/**
	 * 查询资源类型
	 *
	 * @param cloudBill
	 * @param context
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "查询资源类型", httpMethod = "GET")
	@Log(module = BoCloudService.IMS, target = "账单管理", operation = "查询资源类型")
	@GetMapping("/queryTypeList")
	public BocloudResult<List<Map<String, String>>> queryTypeList(@RequestParam(value = Common.VENDORID) Long vendorId,
			@Value(Common.REQ_CONTEXT) RequestContext context) {
		return cloudBillService.listTypes(context, vendorId);
	}

	/**
	 * 查询Heat列表
	 *
	 * @param pager
	 * @param context
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "账单列表查询", httpMethod = "GET")
	@Log(module = BoCloudService.IMS, target = "Heat管理", operation = "查询Heat列表")
	@GetMapping
	public BocloudResult<GridBean<CloudBill>> list(Pager pager, @Value(Common.REQ_CONTEXT) RequestContext context) {
		return cloudBillService.list(pager, context);
	}

	@ApiOperation(tags = { "CMC", "CSC" }, value = "同步账单数据", produces = MediaType.APPLICATION_JSON_VALUE)
	@Log(module = BoCloudService.IMS, target = "账单管理", operation = "同步账单数据")
	@PostMapping
	public BocloudResult synchronizeData(@RequestParam(value = Common.CONDITION, required = false) String condition,
			@Value(Common.REQ_CONTEXT) RequestContext context) {
		return cloudBillService.synchronizeData(context);
	}

	@ApiOperation(tags = { "CMC", "CSC" }, value = "账单列表导入", httpMethod = "POST")
	@Log(module = BoCloudService.IMS, target = "账单", operation = "账单列表导入")
	@PostMapping("/import")
	public BocloudResult importBill(@RequestParam("file") MultipartFile file, @RequestBody CloudBill cloudBill,
			@Value(Common.REQ_CONTEXT) RequestContext context) {
		return cloudBillService.importBill(file, cloudBill, context);
	}

	/**
	 * 导出
	 *
	 * @param cloudBill
	 * @param context
	 * @param response
	 * @param request
	 * @return
	 */
	@ApiOperation(tags = { "CMC", "CSC" }, value = "导出账单列表", httpMethod = "GET")
	@Log(module = BoCloudService.IMS, target = "账单", operation = "导出账单列表")
	@GetMapping("/export")
	public BocloudResult export(Pager pager, @Value(Common.REQ_CONTEXT) RequestContext context,
			HttpServletResponse response, HttpServletRequest request) {
		BocloudResult bocloudResult = cloudBillService.download(pager, context);
		if (bocloudResult.isSuccess()) {
			String content;
			try {
				@SuppressWarnings("unchecked")
				Map<String, Object> result = JSONObject.parseObject(JSONObject.toJSONString(bocloudResult.getData()),
						HashMap.class);
				String fileName = result.get("fileName").toString();
				if (fileName.contains("pdf")) {
					response.setContentType("application/pdf");
				} else {
					response.setContentType("application/vnd.ms-excel");
				}
				final String userAgent = request.getHeader("user-agent").toLowerCase();
				if (userAgent.contains("trident") || userAgent.contains("edge")) {
					fileName = URLEncoder.encode(fileName, "UTF-8");
				} else {
					fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
				}
				response.setCharacterEncoding("utf-8");
				response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
				OutputStream outputStream = response.getOutputStream();
				content = (String) result.get("data");
				if (content != null) {
					byte[] bytes = Base64.getDecoder().decode(content);
					outputStream.write(bytes);
					outputStream.close();
				}
			} catch (Exception e) {
				return new BocloudResult(false, "内部错误");
			}
		}
		return bocloudResult;
	}

}
