package com.file_upload.controller;

import com.file_upload.domain.AjaxResult;
import com.file_upload.domain.FileUrlList;
import com.file_upload.utils.AliyunOSSUtil;
import com.file_upload.utils.DatePattern;
import com.file_upload.utils.DateUtils;
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.stereotype.Component;
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.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 通用请求处理
 *
 */
@RestController
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    @Value("${oss.filepath}")
    private String filePath;
    @Value("${oss.filehost}")
    private String filehost;

    private String newFileHost = "https://cdn.uxianxin.com/";

    @Resource
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    OSSWebUpload upload;



    @GetMapping("/getSign")
    public AjaxResult getSign(String file){
        Map<String, String> signature = upload.createSignature(file);

        return AjaxResult.success(signature);
    }


    /**
     * 单个文件上传
     */
    @PostMapping("/common/uploadFiles")
    public AjaxResult uploadFiles(@RequestParam("file") MultipartFile file)throws Exception
    {
        try
        {
            log.info("文件上传");
            String fileName = file.getOriginalFilename();
            String uploadUrl = "";
            if (file != null) {
                if (!"".equals(fileName.trim())) {
                    File newFile = new File(fileName);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);

                    // 根据不同文件文件类型-不同日期生成不同文件夹
                    Date date = new Date();
                    String datePath = DateUtils.formatDateByStyle(date, DatePattern.CN_DATE_BASIC_STYLE4.getDatePattern());

                    String timeStamp = String.valueOf(System.currentTimeMillis());
                    fileName = timeStamp + fileName.substring(fileName.lastIndexOf("."), fileName.length());

                    String path;
                    if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png")) {
                        // images
                        path = filePath + "images/" + datePath + "/" + fileName;
                    } else if (fileName.endsWith(".mp4")) {
                        // video
                        path = filePath + "video/" + datePath + "/" + fileName;
                    } else {
                        path = filePath + "other/" + datePath + "/" + fileName;
                    }
                    // 上传到OSS
                    uploadUrl = aliyunOSSUtil.uploadFiles(newFile, path);
                    newFile.delete();
                    if (uploadUrl != null) {
//                        return uploadUrl;
                    }
                }
            }

            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", newFileHost+uploadUrl);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 文件批量上传文件上传
     */
    @PostMapping("/common/uploadBatchFiles")
    public AjaxResult uploadBatchFiles(@RequestParam("files") MultipartFile[] files)throws Exception
    {
        List<FileUrlList> fileUrlList = new ArrayList<>();
        for(MultipartFile file:files){
            FileUrlList fileUrlList1 = new FileUrlList();
            try
            {
                log.info("文件上传");
                String fileName = file.getOriginalFilename();
                String uploadUrl = "";
                if (file != null) {
                    if (!"".equals(fileName.trim())) {
                        File newFile = new File(fileName);
                        FileOutputStream os = new FileOutputStream(newFile);
                        os.write(file.getBytes());
                        os.close();
                        file.transferTo(newFile);

                        // 根据不同文件文件类型-不同日期生成不同文件夹
                        Date date = new Date();
                        String datePath = DateUtils.formatDateByStyle(date, DatePattern.CN_DATE_BASIC_STYLE4.getDatePattern());

                        String timeStamp = String.valueOf(System.currentTimeMillis());
                        fileName = timeStamp + fileName.substring(fileName.lastIndexOf("."), fileName.length());

                        String path;
                        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png")) {
                            // images
                            path = filePath + "images/" + datePath + "/" + fileName;
                        } else if (fileName.endsWith(".mp4")) {
                            // video
                            path = filePath + "video/" + datePath + "/" + fileName;
                        } else {
                            path = filePath + "other/" + datePath + "/" + fileName;
                        }
                        // 上传到OSS
                        uploadUrl = aliyunOSSUtil.uploadFiles(newFile, path);
                        newFile.delete();
                        if (uploadUrl != null) {
//                        return uploadUrl;
                        }
                    }
                }
                fileUrlList1.setFileUrl(newFileHost+uploadUrl);
                fileUrlList1.setFileName(fileName);
                fileUrlList.add(fileUrlList1);

            }
            catch (Exception e)
            {
                return AjaxResult.error(e.getMessage());
            }
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("fileUrlList",fileUrlList);
        return ajax;
    }
    @GetMapping("/text")
    public void text(@RequestParam("files") String files){
        System.out.println(files);
    }

}
