package com.neusoft.smart.pos.gateway.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.*;
import com.neusoft.smart.pos.framework.dto.ResponseData;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/unionService/AliOSS")
public class OssController {
	
	@Value("${smart.pos.constant.oss.endpoint}")
	private String endpoint;
	
	@Value("${smart.pos.constant.oss.accessId}")
	private String accessId;
	
	@Value("${smart.pos.constant.oss.accessKey}")
	private String accessKey;
	
	@Value("${smart.pos.constant.oss.host}")
	private String host;
	
	@PostMapping(value = "/signature")
	public ResponseData<JSONObject> save(String dir, HttpServletRequest request, HttpServletResponse response) throws IOException {
		OSSClient client = new OSSClient(endpoint, accessId, accessKey);
		long expireTime = 30;
		long expireEndTime = System.currentTimeMillis() + expireTime * 1000 * 60;
		Date expiration = new Date(expireEndTime);
		PolicyConditions policyConds = new PolicyConditions();
		policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
		switch (dir) {
			case "media":
				policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, "media");
				break;
			case "config":
				policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, "config");
				break;
			case "codeLib":
				policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, "codeLib");
				break;
			case "img":
				policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, "img");
				break;
			default:
				policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
		}
		String postPolicy = client.generatePostPolicy(expiration, policyConds);
		byte[] binaryData = postPolicy.getBytes("utf-8");
		String encodedPolicy = BinaryUtil.toBase64String(binaryData);
		String postSignature = client.calculatePostSignature(postPolicy);
		
		Map<String, String> respMap = new LinkedHashMap<String, String>();
		respMap.put("accessid", accessId);
		respMap.put("policy", encodedPolicy);
		respMap.put("signature", postSignature);
		// respMap.put("expire", formatISO8601Date(expiration));
		//respMap.put("dir", dir);
		respMap.put("host", host);
		respMap.put("expire", String.valueOf(expireEndTime / 1000));
		JSONObject ja1 = JSONObject.fromObject(respMap);
		//response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET, POST");
//			response(request, response, ja1.toString());
		return new ResponseData<>(ja1);
	}

	private void response(HttpServletRequest request, HttpServletResponse response, String results) throws IOException {
		String callbackFunName = request.getParameter("callback");
		if (callbackFunName == null || callbackFunName.equalsIgnoreCase(""))
			response.getWriter().println(results);
		else
			response.getWriter().println(callbackFunName + "( " + results + " )");
		response.setStatus(HttpServletResponse.SC_OK);
		response.flushBuffer();
	}
	
	@Value("${smart.pos.constant.oss.url.media}")
	private String mediaURL;
	
	@GetMapping("/mediaResource/oss/url")
	@ApiOperation(value = "获取广告资源下载OSS地址接口", notes = "获取广告资源下载OSS地址接口")
	public ResponseData<String> getMediaOSSUrl() {
		return new ResponseData<>(mediaURL);
	}
	
	
	@Value("${smart.pos.constant.oss.url.codeLib}")
	private String codeLibURL;
	
//	@Value("${smart.pos.constant.oss.url.img}")
//	private String imgURL;
	
	@GetMapping("/deviceConfig/oss/url")
	@ApiOperation(value = "获取配置OSS地址接口", notes = "获取配置OSS地址接口")
	public ResponseData<Map<String, String>> getConfigOSSUrl() {
		Map<String, String> map = new HashMap<>();
		map.put("codeLibURL4OSS", codeLibURL);
//		map.put("imgURL4OSS", imgURL);
		return new ResponseData<>(map);
	}
	
	
	@Value("${smart.pos.constant.oss.url.ota}")
	private String packageURL;
	
	@GetMapping("/upgradePackage/oss/url")
	@ApiOperation(value = "获取更新包OSS地址接口", notes = "获取更新包OSS地址接口")
	public ResponseData<String> getPackageOSSUrl() {
		return new ResponseData<>(packageURL);
	}
	
	@Value("${smart.pos.constant.oss.url.qrCode}")
	private String qrCodeURL;
	
	@GetMapping("/trade/oss/url")
	@ApiOperation(value = "获取支付二维码OSS地址接口", notes = "获取支付二维码OSS地址接口")
	public ResponseData<String> getQrCodeOSSUrl() {
		return new ResponseData<>(qrCodeURL);
	}
	
	@Value("${smart.pos.constant.oss.url.storeLogo}")
	private String storeLogo;
	
	@GetMapping("/store/logo/oss/url")
	@ApiOperation(value = "获取商品logo的OSS地址接口", notes = "获取商品logo的OSS地址接口")
	public ResponseData<String> getStoreLogoOSSUrl() {
		return new ResponseData<>(storeLogo);
	}

	@Value("${smart.pos.constant.oss.url.img}")
	private String imgURL;
	
	@GetMapping("/goods/oss/url")
	@ApiOperation(value = "获取商品图片OSS地址接口", notes = "获取商品图片OSS地址接口")
	public ResponseData<String> getGoodsOSSUrl() {
			return new ResponseData<>(imgURL);
	}
	
	@Value("${smart.pos.constant.oss.url.apk}")
	private String apkURL;
	
	@GetMapping("/apk/oss/url")
	@ApiOperation(value = "获取APK的OSS地址接口", notes = "获取APK的OSS地址接口")
	public ResponseData<String> getApkOSSUrl() {
		return new ResponseData<>(apkURL);
	}

}
