package com.jeeplus.modules.sys.web;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.web.BaseController;
import junit.framework.Assert;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by admin on 2017/12/20.
 */
/**
 * 返回OSS直传所需的policy
 * @author fgy
 * @version 2017-12-20
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "${adminPath}/sys/ossUpload")
public class OSSUploadController extends BaseController {

    private static final long serialVersionUID = 8207235581947269241L;

    @RequestMapping("getPolicy")
    protected String getPolicy(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String endpoint = Global.getEndpoint();
        String accessId = Global.getAccessKeyId();
        String accessKey = Global.getAccessKeySecret();
        String bucket = Global.getBucketName();
        String dir = Global.getWorkFullSupervisorsheet();
        String host = "http://" + bucket + "." + endpoint;
        OSSClient client = new OSSClient(endpoint, accessId, accessKey);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            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);
            System.err.println(ja1.toString());
//            response.setHeader("content-type:application","json;charset=utf8");
//            response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET,POST");
            setResponse(request, response, ja1.toString());

        } catch (Exception e) {
            Assert.fail(e.getMessage());
        }
        return "1";
    }

    private void setResponse(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);//响应码200
        response.flushBuffer();
    }

}
