package com.jeeplus.modules.filePreview;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("${adminPath}/previewController")
public class PreviewController extends BaseController {





    /**
     * 删除信息
     *
     * @return
     */
    @RequestMapping("/deleteUrl")
    @ResponseBody
    public boolean deleteUrl(HttpServletRequest request) {
        String id = UserUtils.getUser().getId();
        String realPath = request.getSession().getServletContext().getRealPath("/");
        File f = new File(realPath + "/webpage/modules/web/" + id + "/");
        boolean flag = false;
        if (f.exists()) {
            flag = deleteDir(f);
        }
        return flag;
    }

    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }


//    @RequestMapping("/openexcel")
//    public String openexcel(HttpServletRequest request, HttpServletResponse response){
//        PageOfficeCtrl poCtrl=new PageOfficeCtrl(request);
//        request.setAttribute("poCtrl", poCtrl);
//        //设置服务页面
//        poCtrl.setServerPage(request.getContextPath()+"/poserver.zz");
//        //添加保存按钮
//        poCtrl.addCustomToolButton("保存并关闭","Save",1);
//        //设置保存页面
//        poCtrl.setSaveFilePage("/savefile.do");
//        //打开excel
//        poCtrl.webOpen("doc/test.xls", OpenModeType.xlsNormalEdit,"张三");
//        return "modules/workclientinfo/Excel";
//    }
//
//    @RequestMapping("/openword")
//    public String openword(@RequestParam(value = "fileUrl") String fileUrl,HttpServletRequest request, HttpServletResponse response){
//        PageOfficeCtrl poCtrl=new PageOfficeCtrl(request);
//        request.setAttribute("poCtrl", poCtrl);
//        //设置服务页面
//        poCtrl.setServerPage(request.getContextPath()+"/poserver.zz");
//        //添加保存按钮
//        poCtrl.addCustomToolButton("保存并关闭","Save",1);
//        //设置保存的action
//        poCtrl.setSaveFilePage("/savefile");
//        //打开word
//        poCtrl.webOpen(fileUrl,OpenModeType.docAdmin,"张三");
//        return "modules/workclientinfo/Word";
//    }
//
//    @RequestMapping("/savefile")
//    public  void  savefile(HttpServletRequest request, HttpServletResponse response){
//        FileSaver fs = new FileSaver(request, response);
//        fs.saveToFile(request.getSession().getServletContext().getRealPath("doc/") + "/" + fs.getFileName());
//        fs.close();
//    }

    @RequestMapping("/getDirectAccess")
    @ResponseBody
    public Map<Object, Object> getDirectAccess(HttpServletRequest request, HttpServletResponse response) {
        Map<Object, Object> respMap = new HashMap<Object, Object>();
        Date expiration = new Date();
        long expireTime = 365 * 10 * 24 * 3600;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;

        ///2050/1/1 许可到期时间
//
//        long expireTime = 600;
//        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
//        String host = Global.getAliyunUrl();
       String accessId = "LTAIzG5m63BhoGa7";
//        String accessKey = "J0mEs8AYtgGWrfC54cSGgUXHCOOjvS";
//        PolicyConditions policyConds = new PolicyConditions();
//        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
//        OSSClient client = new OSSClient(host, accessId, accessKey);
//        try {
//            Date expiration = new Date(expireEndTime);
//            String postPolicy = client.generatePostPolicy(expiration, policyConds);
//            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = "eyJleHBpcmF0aW9uIjoiMjA1MC0wMS0wMVQxMjowMDowMC4wMDBaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF1dfQ==";//BinaryUtil.toBase64String(binaryData);
            String postSignature = "Sa28845KJOv8TYDRyg2A/+A6RZk=";//client.calculatePostSignature(postPolicy);
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("expire", expireEndTime);
            respMap.put("host", Global.getAliyunUrl());
            return respMap;
//        }catch(Exception e)
//        {
//            return respMap;
//        }
    }
    @RequestMapping("/getAccess")
    @ResponseBody
    public Map<Object, Object> getAccess(HttpServletRequest request, HttpServletResponse response) {

        // 只有 RAM用户（子账号）才能调用 AssumeRole 接口
        // 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
        // 请首先在RAM控制台创建一个RAM用户，并为这个用户创建AccessKeys
        String accessKeyId =  "LTAIzG5m63BhoGa7";//Global.getAccessKeyId();
        String accessKeySecret = "J0mEs8AYtgGWrfC54cSGgUXHCOOjvS"; //Global.getAccessKeySecret();

        // RoleArn 需要在 RAM 控制台上获取
        String roleArn = "acs:ram::1251733816552326:role/stsrole";
        long durationSeconds = Long.parseLong("900");
        String policy = "{\n" +
                "    \"Version\": \"1\", \n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"oss:*\"\n" +
                "            ], \n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*:*:*\" \n" +
                "            ], \n" +
                "            \"Effect\": \"Allow\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
//        String policy = null;
        // RoleSessionName 是临时Token的会话名称，自己指定用于标识你的用户，主要用于审计，或者用于区分Token颁发给谁
        // 但是注意RoleSessionName的长度和规则，不要有空格，只能有'-' '_' 字母和数字等字符
        // 具体规则请参考API文档中的格式要求
        String roleSessionName = "alice-001";
        // 此处必须为 HTTPS
        ProtocolType protocolType = ProtocolType.HTTPS;
        try {
            final AssumeRoleResponse stsResponse = assumeRole(accessKeyId, accessKeySecret, roleArn, roleSessionName,
                    policy, protocolType, durationSeconds);

            Map<Object, Object> respMap = new HashMap<Object, Object>();
            respMap.put("status", "200");
            respMap.put("AccessKeyId", stsResponse.getCredentials().getAccessKeyId());
            respMap.put("AccessKeySecret", stsResponse.getCredentials().getAccessKeySecret());
            respMap.put("SecurityToken", stsResponse.getCredentials().getSecurityToken());
            respMap.put("Expiration", stsResponse.getCredentials().getExpiration());
            respMap.put("AliyunUrl", Global.getAliyunUrl());
            respMap.put("Bucket", Global.getBucketName());
            respMap.put("Endpoint", Global.getEndpoint());
            return respMap;
        } catch (ClientException e) {

            Map<Object, Object> respMap = new HashMap<Object, Object>();
            respMap.put("status", e.getErrCode());
            respMap.put("AccessKeyId", "");
            respMap.put("AccessKeySecret", "");
            respMap.put("SecurityToken", "");
            respMap.put("Expiration", "");
            respMap.put("AliyunUrl", "");
            respMap.put("Bucket", "");
            respMap.put("Endpoint", "");
            return respMap;
        }
    }

    public static String ReadJson(String path){
        //从给定位置获取文件
        File file = new File(path);
        BufferedReader reader = null;
        //返回值,使用StringBuffer
        StringBuffer data = new StringBuffer();
        //
        try {
            reader = new BufferedReader(new FileReader(file));
            //每次读取文件的缓存
            String temp = null;
            while((temp = reader.readLine()) != null){
                data.append(temp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭文件流
            if (reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data.toString();
    }

    public static final String REGION_CN_HANGZHOU = "cn-hangzhou";
    public static final String STS_API_VERSION = "2015-04-01";
    protected AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleArn,
                                            String roleSessionName, String policy, ProtocolType protocolType, long durationSeconds) throws ClientException
    {
        try {
            // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
            IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);

            // 创建一个 AssumeRoleRequest 并设置请求参数
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setVersion(STS_API_VERSION);
            request.setMethod(MethodType.POST);
            request.setProtocol(protocolType);

            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy);
            request.setDurationSeconds(durationSeconds);
            // 发起请求，并得到response
            final AssumeRoleResponse response = client.getAcsResponse(request);

            return response;
        } catch (ClientException e) {
            throw e;
        }
    }
    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();
    }
}
