package com.jeeplus.test.oss.controller;

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.aop.logging.annotation.ApiLog;
import com.jeeplus.common.utils.FileUtils;
import com.jeeplus.sys.utils.FileKit;
import com.jeeplus.test.oss.service.OSSClientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import liquibase.pro.packaged.S;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api(tags ="oss")
@RestController
@RequestMapping(value = "/oss/oss")
public class OssController {

    private static final String DIRECTORY = "/attachment-file";

    private static final String ALIYUNURL = "http://oss.gangwaninfo.com";

    private static final String ALIYUNDOWNLOADURL = "";

    @Value("${config.accessory.aliyun.bucketName}")
    private String bucketName;

    @Value("${config.accessory.aliyun.endpoint}")
    private String endpoint;

    @Autowired
    private OSSClientService ossClientService;

    /**
     * 文件上传
     * @param storeAs
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public ResponseEntity<String> upload(@RequestParam String storeAs, @RequestParam("file") MultipartFile file) throws Exception {
        //取得上传文件
        if (file != null && !file.isEmpty()) {
            // 文件保存路径
            String realPath =DIRECTORY.replace("/","")+"/"+storeAs+ossClientService.datePath()+"/"+ System.currentTimeMillis();
            //文件原名称
            String newName = file.getOriginalFilename();
            ossClientService.uploadFile2OSS(file.getInputStream(),realPath,newName);
            String filepath = ALIYUNURL + "/" + realPath + newName;
            return ResponseEntity.ok (filepath);
        }
        return ResponseEntity.ok(null);
    }

    @PostMapping("/getAccess")
    @ApiOperation(value = "文件上传(前端调用)")
    public Map<Object, Object> getAccess() {
        // 只有 RAM用户（子账号）才能调用 AssumeRole 接口
        // 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
        // 请首先在RAM控制台创建一个RAM用户，并为这个用户创建AccessKeys
        String accessKeyId =  "LTAI5tBBnQdpZapU28Ds89fb";
        String accessKeySecret = "A37CuoALjoxCjPolzRm3ct5o8UHILF";
        // RoleArn 需要在 RAM 控制台上获取
        String roleArn = "acs:ram::1132186699724035:role/yf";
        long durationSeconds = Long.parseLong("3600");
        String policy = "{\n" +
                "  \"Version\": \"1\",\n" +
                "  \"Statement\": [\n" +
                "    {\n" +
                "      \"Effect\": \"Allow\",\n" +
                "      \"Action\": [\n" +
                "        \"oss:*\"\n" +
                "      ],\n" +
                "      \"Resource\": [\n" +
                "        \"acs:oss:*:*:*\"\n" +
                "      ],\n" +
                "      \"Condition\": {}\n" +
                "    }\n" +
                "  ]\n" +
                "}";
        // RoleSessionName 是临时Token的会话名称，自己指定用于标识你的用户，主要用于审计，或者用于区分Token颁发给谁
        // 但是注意RoleSessionName的长度和规则，不要有空格，只能有'-' '_' 字母和数字等字符
        // 具体规则请参考API文档中的格式要求
        String roleSessionName = "yf";
        // 此处必须为 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",ALIYUNDOWNLOADURL);
            respMap.put("Bucket", bucketName);
            respMap.put("Endpoint", endpoint);
            return respMap;
        } catch (ClientException e) {
            log.error("调用ali获取临时token报错，错误信息：" + e.getMessage());
            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 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;
        }
    }

    /**
     * 根据url删除文件
     * @param url
     * @return
     */
    @ApiOperation("根据url删除文件")
    @GetMapping("/deleteByUrl")
    public ResponseEntity delFileByUrl(@RequestParam String url) {
        String id = FileKit.getFileDir(url);
        if(FileUtils.delFile(id)){
            return ResponseEntity.ok ("删除文件成功");
        }else{
            return ResponseEntity.badRequest().body ("删除文件失败");
        }

    }
}
