package com.miaxis.system.controller.common;

import com.miaxis.common.annotation.Log;
import com.miaxis.common.config.MiaxisConfig;
import com.miaxis.common.constant.Constants;
import com.miaxis.common.core.domain.Response;
import com.miaxis.common.enums.BusinessTypeEnum;
import com.miaxis.common.enums.FileUploadTypeEnum;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.EnumUtils;
import com.miaxis.common.utils.StringUtils;
import com.miaxis.common.utils.file.FileUtils;
import com.miaxis.file.domain.FileInfo;
import com.miaxis.file.service.IFileInfoService;
import com.miaxis.framework.config.ServerConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;

/**
 * 通用请求处理
 *
 * @author miaxis
 */
@RestController
@Api(tags={"【系统-通用请求处理】"})
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IFileInfoService fileInfoService;

    @Value("${cos.bucketName}")
    private String bucketName;
    @Value("${cos.path}")
    private String path;
    @Value("${cos.preffix}")
    private String preffix;

    @Autowired
    COSClient  cosClient;



    /**
     * 上传文件
     */
    @Log(title = "上传文件", businessType = BusinessTypeEnum.INSERT)
    @PostMapping(Constants.OPEN_PREFIX+"/common/file")
    @ApiOperation("通用上传请求")
    public Response<FileInfo> updateload(MultipartFile file,
                                         @ApiParam(name = "remark", value = "备注，非必传") @RequestParam("remark") String remark,
                                         @ApiParam(name = "fileType", value = "业务类型:98-音视频文件、1-商户logo、99-其他")
        @RequestParam("fileType") Integer fileType) throws IOException {
        FileUploadTypeEnum fileUploadTypeEnum = getPathByType(fileType);
        String originalFilename = file.getOriginalFilename();
        //获取最后一个.的位置
        int lastIndexOf = originalFilename.lastIndexOf(".");
        //获取文件的后缀名
        String suffix = originalFilename.substring(lastIndexOf);
        if (!validateFileSuffix(suffix,fileUploadTypeEnum)){
            throw new CustomException("文件类型不合法");
        }

        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        String bucketName = this.bucketName;
        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
        // 大文件上传请参照 API 文档高级 API 上传
        File localFile = null;
        localFile = File.createTempFile("temp",null);
        file.transferTo(localFile);
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month=cal.get(Calendar.MONTH)+ 1;
        int day=cal.get(Calendar.DATE);
        //存储的文件名
        String storagefileName = System.currentTimeMillis() + suffix;
        // 指定要上传到 COS 上的路径
        String key = null;
        if (FileUploadTypeEnum.OTHERS.getCode()!= fileType){
            key = "/"+this.preffix+"/"+fileUploadTypeEnum.getFileType()+"/"+year+"/"+month+"/"+day+"/"+storagefileName;
        }else{
            key = "/"+this.preffix+"/"+fileUploadTypeEnum.getFileType()+"/"+storagefileName;
        }

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        String fileUrl=this.path + putObjectRequest.getKey();

        FileInfo fileInfo = new FileInfo();
        fileInfo.setFileType(fileUploadTypeEnum.getFileType());
        fileInfo.setFilePath(key);
        fileInfo.setFileUrl(fileUrl);
        //fileInfo.setRemark(remark);
        fileInfoService.save(fileInfo);
        return Response.success(fileInfo);
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(
            @ApiParam(name = "name", value = "文件名称")
            @RequestParam(name = "name", required = true) String name,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception
    {
        // 本地资源路径
        String localPath = MiaxisConfig.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(name, Constants.RESOURCE_PREFIX);
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }


    private Boolean validateFileSuffix(String originalFilenamefile, FileUploadTypeEnum fileUploadTypeEnum) {
        if (fileUploadTypeEnum == null){
            throw new CustomException("fileType参数不合法");
        }
        if (StringUtils.isEmpty(originalFilenamefile)){
            throw new CustomException("文件名不合法");
        }
        String[] allowSuffixs = fileUploadTypeEnum.getSuffix();
        for(String suffix : allowSuffixs){
            String fileSuffix = "."+suffix;
            if (originalFilenamefile.equals(fileSuffix)){
                return true;
            }
        }
        return false;

    }

    private FileUploadTypeEnum getPathByType(Integer fileType) {
        if (fileType == null){
            throw new CustomException("文件类型不能为空");
        }
        return (FileUploadTypeEnum) EnumUtils.getEnumEntityByCode(FileUploadTypeEnum.class, fileType);

    }

}
