package com.bs.web.controller.common;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;
import javax.annotation.Resource;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bs.BsApplication;
import com.bs.cm.domain.CmAttach;
import com.bs.cm.service.ICmAttachService;
import com.bs.cm.vo.CmAttachVO;
import com.bs.common.exception.ServiceException;
import com.bs.ct.domain.CtGalleryImages;
import com.bs.ct.service.ICtGalleryImagesService;
import com.bs.ct.utils.UUIDUtils;
import io.swagger.annotations.ApiOperation;
import org.aspectj.util.FileUtil;
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.boot.SpringApplication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.bs.common.config.BsConfig;
import com.bs.common.constant.Constants;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.utils.StringUtils;
import com.bs.common.utils.file.FileUploadUtils;
import com.bs.common.utils.file.FileUtils;
import com.bs.framework.config.ServerConfig;

import static cn.hutool.core.img.ImgUtil.getWriter;

/**
 * 通用请求处理
 *
 * @author bs
 */
@RestController
@RequestMapping("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    @Value("${bs.profile}")
    private  String profile;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ICmAttachService cmAttachService;
    @Resource
    private ICtGalleryImagesService ctGalleryImagesService;
    public static final String SEPARATOR = "/";
//    public static final String SUFFIX = RESOURCE_PREFIX;

    private static final String FILE_DELIMETER = ",";
    public static void clockwise90(File file, File outputFile, String formatName) {
        try {
            // 原图片
            BufferedImage image = ImageIO.read(file);
            int width = image.getWidth();
            int height = image.getHeight();

            // 新生成的图片
            BufferedImage imageNew = new BufferedImage(height, width, image.getType());
            // 把原图顺时针旋转后，像素存入新图片。
            // 算法实现方式：
            //    把原图片的最后一行，转变为新图片的第1列.
            //    把原图片的倒数第2行，转变为新图片的第2列.
            //    ......
            // 以此类推，进行变换。代码中行数列数从0开始计算。
            int maxY = height - 1;
            for (int y = maxY; y >= 0; y--) {
                for (int x = 0; x < width; x++) {
                    int rgb = image.getRGB(x, y);
                    imageNew.setRGB(maxY - y, x, rgb);
                }
            }
            // 把图片输出到硬盘上。
            ImageIO.write(imageNew, formatName, outputFile);
            // 检查输出文件的父目录是否存在，如果不存在则创建
            File parentDir = outputFile.getParentFile();
            if (parentDir != null &&!parentDir.exists()) {
                if (!parentDir.mkdirs()) {
                    System.err.println("无法创建输出文件的父目录: " + parentDir.getAbsolutePath());
                    return;
                }
            }
            // 把图片输出到硬盘上。
            if (!ImageIO.write(imageNew, formatName, outputFile)) {
                System.err.println("无法保存图片到: " + outputFile.getAbsolutePath());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ImageWriter getWriter(BufferedImage im, String formatName) {
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatName);
        if (writers.hasNext()) {
            return writers.next();
        }
        return null;
    }

    public static BufferedImage rotateImage90DegreesClockwise(BufferedImage originalImage) {
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        BufferedImage rotatedImage = new BufferedImage(height, width, originalImage.getType());
        Graphics2D g2d = rotatedImage.createGraphics();
        g2d.rotate(Math.toRadians(90), height / 2.0, width / 2.0);
        g2d.translate((height - width) / 2, (width - height) / 2);
        g2d.drawImage(originalImage, 0, 0, null);
        g2d.dispose();

        return rotatedImage;
    }

    public static void clockwise180(File file, File outputFile, String formatName) {
        try {
            // 原图片
            BufferedImage image = ImageIO.read(file);
            int width = image.getWidth();
            int height = image.getHeight();
            // 新生成的图片
            BufferedImage imageNew = new BufferedImage(width, height, image.getType());

            // 把原图片顺时针旋转180度后，像素存入新图片。
            // 算法实现方式：
            //    原图片第1行转变为新图片倒数第1行。并且旧行中像素的顺序，在新行倒转了过来。
            //    原图片第2行转变为新图片倒数第2行。并且旧行中像素的顺序，在新行倒转了过来。
            //    ......
            // 以此类推，进行变换。代码中行数列数从0开始计算。
            int maxX = width - 1;
            int maxY = height - 1;
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int rgb = image.getRGB(x, y);
                    imageNew.setRGB(maxX - x, maxY - y, rgb);
                }
            }

            // 把图片输出到硬盘上。
            ImageIO.write(imageNew, formatName, outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void anticlockwise90(File file, File outputFile, String formatName) {
        try {
            // 原图片
            BufferedImage image = ImageIO.read(file);
            int width = image.getWidth();
            int height = image.getHeight();

            // 新生成的图片
            BufferedImage imageNew = new BufferedImage(height, width, image.getType());

            // 把原图逆时针旋转后，像素存入新图片。
            // 算法实现方式：
            //    把原图片第1行，转变为新图片第1列。并且旧行中第1个像素是新列中最后1个像素.
            //    把原图片第2行，转变为新图片第2列。并且旧行中第1个像素是新列中最后1个像素.
            //    ......
            // 以此类推，进行变换。代码中行数列数从0开始计算。
            int maxX = width - 1;
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int rgb = image.getRGB(x, y);
                    imageNew.setRGB(y, maxX - x, rgb);
                }
            }

            // 把图片输出到硬盘上。
            ImageIO.write(imageNew, formatName, outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = BsConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    @ApiOperation("下载文件")
    @GetMapping("/file/download/{attachId}")
    public void download(@PathVariable String attachId, HttpServletRequest request, HttpServletResponse response) {
        if (org.apache.commons.lang3.StringUtils.isBlank(attachId) || "null".equals(attachId)) {
            throw new ServiceException("附件ID不能为空");
        }
        try {
            Map<Object, Object> param = new HashMap<>();
            param.put("attachId", attachId);
            //CmAttach cmAttach = cmAttachMapper.selectByAttachId(param);
            CmAttach vwAttach = cmAttachService.getById(attachId);
            String attachFileurl = vwAttach.getAttachFileUrl();
            if (Validator.isNotEmpty(attachFileurl) && attachFileurl.contains(Constants.RESOURCE_PREFIX)) {
                attachFileurl = attachFileurl.replace("/profile", "");
            }
            File file = new File(profile + attachFileurl);
            boolean exists = file.exists();
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            com.bs.web.controller.utils.FileUtil.downloadFile(request, response, file, false);
        } catch (Exception e) {
            throw new ServiceException("下载失败：" + e.getMessage());
        }
    }

    @ApiOperation("修改附件")
    @PutMapping("/editFile")
    public AjaxResult edit(@RequestBody CmAttachVO attachVo) throws Exception {
        Long id = attachVo.getId();
        String attachFileUrl = attachVo.getAttachFileUrl();
        String attachUrl = attachVo.getAttachFileUrl().replace("/profile", "");
        String filePath = profile + attachUrl;
        String formatName = FileUtils.getName(filePath);
        String fileName = UUIDUtils.generatorUUID() + formatName;
        String newAttachUrl = attachUrl.substring(0, attachUrl.lastIndexOf(SEPARATOR)) + SEPARATOR +  fileName;
        String outFilePath = profile + newAttachUrl;
        File inputFile = new File(filePath);
        File outputFile = new File(outFilePath);
        formatName = "jpeg";
        if ("90".equals(attachVo.getAngle())) {
            // 旋转90度
            //BufferedImage rotated90Image = rotateImage(inputImage, 90);
            clockwise90(inputFile, outputFile, formatName);
        } else if ("180".equals(attachVo.getAngle())) {
            // 旋转180度
            clockwise180(inputFile, outputFile, formatName);
        } else if ("270".equals(attachVo.getAngle())) {
            anticlockwise90(inputFile, outputFile, formatName);
        }
        List<CmAttach> list = cmAttachService.list(new LambdaQueryWrapper<CmAttach>()
                .eq(CmAttach::getFileId, attachVo.getFileId()));
        List<CtGalleryImages> ctGalleryImages = ctGalleryImagesService.list(new LambdaQueryWrapper<CtGalleryImages>()
                .eq(CtGalleryImages::getFileId, attachVo.getFileId()));
        if (null != list && list.size() > 0) {
            for (CmAttach cmAttach : list) {
                cmAttach.setOldName(attachVo.getOldName());
                System.out.println(newAttachUrl);
                String attachUrlNew = "/profile" + newAttachUrl;
                cmAttach.setAttachFileUrl(attachUrlNew);
            }
            cmAttachService.updateBatchById(list);
        }
        if (null != ctGalleryImages && ctGalleryImages.size() > 0) {
            for (CtGalleryImages ctGalleryImage : ctGalleryImages) {
                String attachUrlNew = "/profile" + newAttachUrl;
                ctGalleryImage.setImagePath(attachUrlNew);
            }
            ctGalleryImagesService.updateBatchById(ctGalleryImages);
        }
        return AjaxResult.success();
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file, String fileId) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = BsConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            String newFileName = FileUtils.getName(fileName);
            String originalFilename = file.getOriginalFilename();
            CmAttach cmAttach = new CmAttach();
            cmAttach.setFileId(fileId);
            cmAttach.setFileSort(1L);
            cmAttach.setAttachName(newFileName);
            cmAttach.setAttachContentType(file.getContentType());
            cmAttach.setAttachFileSize(file.getSize());
            cmAttach.setAttachFileUrl(fileName);
            cmAttach.setOldName(originalFilename);
            cmAttach.setVersionNo("1");
            cmAttach.setRemark("");
            boolean save = cmAttachService.save(cmAttach);
            if (save) {
                Long id = cmAttach.getId();
                AjaxResult ajax = AjaxResult.success();
                ajax.put("cmAttach", cmAttach);
                return ajax;
            }
            return null;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = BsConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = BsConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}
