package com.heketai.website.web;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.heketai.website.config.AliyunOssProperties;
import com.heketai.website.common.result.BaseResult;
import com.heketai.website.common.result.HttpCode;
import com.heketai.website.service.aliyun.AliyunOssService;
import com.heketai.website.common.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;


@RestController
@RequestMapping("/oss")
@Api(value = "阿里云存储接口管理",tags = "阿里云存储接口")
@Slf4j
public class AliyunOSSController{

    @Autowired
    private AliyunOssService aliyunOssService;

    @Autowired
    private AliyunOssProperties aliyunOssProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    private String fKey = "91BE52B4B262DC8BCA6D2DC0D2F1F17D";

    /**
     * 上传文件到阿里云OSS存储
     *
     * @return
     */
    @RequestMapping("/fileUpload")
    @ApiImplicitParam(name = "file", value = "上传的文件", required = true, paramType = "form", dataType = "__file")
    @ApiOperation(value = "上传文件到阿里云OSS存储", notes = "上传文件到阿里云OSS存储")
    public BaseResult fileUpload(@RequestParam("file") MultipartFile file) {
        try {
            String folderName = aliyunOssService.getFolderName(file.getOriginalFilename());
            OSSClient ossClient = new OSSClient(aliyunOssProperties.getEndpoint(), aliyunOssProperties.getAccessKeyId(), aliyunOssProperties.getAccessKeySecret());
            String url = aliyunOssService.uploadByFile(ossClient, file, folderName);
            redisTemplate.delete(fKey);
            return BaseResult.successWithData(url);
        } catch (Exception ex) {
            ex.printStackTrace();
            return BaseResult.fail(HttpCode.FAIL.getCode());
        }
    }

    @RequestMapping("/fileUploadWithPath")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "上传的文件", paramType = "form", dataType = "__file", required = true),
            @ApiImplicitParam(name = "path", value = "文件路径", paramType = "form", required = true),
    })
    @ApiOperation(value = "上传文件到阿里云OSS存储", notes = "上传文件到阿里云OSS存储")
    public BaseResult fileUpload(@RequestParam("file") MultipartFile file, @RequestParam("path") String path) {
        try {
            String folderName = aliyunOssService.getFolderName(file.getOriginalFilename());
            folderName = path +"/" + folderName  ;

            OSSClient ossClient = new OSSClient(aliyunOssProperties.getEndpoint(), aliyunOssProperties.getAccessKeyId(), aliyunOssProperties.getAccessKeySecret());
            String url = aliyunOssService.uploadByFile(ossClient, file, folderName);
            redisTemplate.delete(fKey);
            return BaseResult.successWithData(url);
        } catch (Exception ex) {
            ex.printStackTrace();
            return BaseResult.fail(HttpCode.FAIL.getCode());
        }
    }


    /**
     * 删除阿里云OSS存储文件
     *
     * @return
     */
    @RequestMapping("/removeFile")
    @ApiOperation(value = "删除阿里云OSS存储文件", notes = "删除阿里云OSS存储文件")
    @ApiImplicitParam(name = "fileName", value = "文件名", required = true, paramType = "query")
    public BaseResult removeFile(@RequestParam("fileName") String url) {
        try {
            OSSClient ossClient = new OSSClient(aliyunOssProperties.getEndpoint(), aliyunOssProperties.getAccessKeyId(), aliyunOssProperties.getAccessKeySecret());
            String fileName = url.substring(url.indexOf("hkt/"));
            boolean flag = aliyunOssService.deleteFile(ossClient, fileName);
            if (!flag) {
                return BaseResult.fail(HttpCode.FAIL.getCode());
            }
            redisTemplate.delete(fKey);
            return BaseResult.success();
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("删除文件失败");
            return BaseResult.fail(HttpCode.FAIL.getCode());
        }
    }

    @RequestMapping("/strUpload")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "str", value = "上传的字符内容", required = true, paramType = "query"),
            @ApiImplicitParam(name = "folder", value = "上传到阿里云的文件名", required = true, paramType = "query")
    })
    @ApiOperation(value = "上传字符到阿里云OSS存储", notes = "上传字符到阿里云OSS存储")
    public BaseResult<String> strUpload(@RequestParam("str") String str, @RequestParam("folder") String folder) {
        File file = FileUtil.saveTxtFile(str);
        try {
            OSSClient ossClient = new OSSClient(aliyunOssProperties.getEndpoint(), aliyunOssProperties.getAccessKeyId(), aliyunOssProperties.getAccessKeySecret());
            String url = aliyunOssService.uploadByFile(ossClient, FileUtil.fileToMultipartFile(file), folder);
            redisTemplate.delete(fKey);
            return BaseResult.successWithData(url);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info(ex.toString());
        } finally {
            //删除临时文件
            file.delete();
        }
        return BaseResult.fail(HttpCode.FAIL.getCode());
    }


    @ApiOperation(value = "通过url获取txt文件内容", notes = "通过url获取txt文件内容")
    @ApiImplicitParam(name = "url", value = "文件路径", required = true, paramType = "query")
    @RequestMapping("/getTxtMsg")
    public BaseResult<String> getTxtMsg(@RequestParam("url") String url) {
        String fileName = url.substring(url.indexOf("hkt/"));
        String key = "3F2333BA-181C-14EB-2FF0-4B504F6F56A3";
        try {
            Object o = redisTemplate.boundHashOps(fKey).get(key);
            if (null != o){
                String msg = JSON.parseObject(o.toString(), String.class);
                return BaseResult.successWithData(msg);
            }
            OSSClient ossClient = new OSSClient(aliyunOssProperties.getEndpoint(), aliyunOssProperties.getAccessKeyId(), aliyunOssProperties.getAccessKeySecret());
            String msg = aliyunOssService.getTxtMsg(ossClient, fileName);
            redisTemplate.boundHashOps(fKey).put(key,msg);
            return BaseResult.successWithData(msg);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info(ex.toString());
        }
        return BaseResult.fail(HttpCode.FAIL.getCode());
    }
}