package com.jeequan.jeepay.mgr.ctrl.common;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.ContentType;
import com.google.zxing.WriterException;
import com.jeequan.jeepay.components.oss.config.OssYmlConfig;
import com.jeequan.jeepay.components.oss.model.OssFileConfig;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.thirdparty.util.CodeImgUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

/*
* 静态文件下载/预览 ctrl
*
* @author terrfly
*
* @date 2021/6/8 17:08
*/
@Controller
public class StaticController extends CommonCtrl {

    @Autowired private OssYmlConfig ossYmlConfig;

    /** 图片预览 **/
    @GetMapping("/api/anon/localOssFiles/**/*.*")
    public ResponseEntity<InputStreamResource> imgView() {

        try {

            String pathAndFileName = cleanPath(request.getRequestURI().substring(24));

            //查找图片文件
            File imgFile = new File(ossYmlConfig.getOss().getFilePublicPath() + File.separator + pathAndFileName);
            if(!imgFile.isFile() || !imgFile.exists()) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }

            //输出文件流（图片格式）
            HttpHeaders httpHeaders = new HttpHeaders();
            String mediaType = FileUtil.getMimeType(imgFile.getPath());

            // 如果获取不到文件类型， 则使用流的形式进行下载。
            if(StringUtils.isEmpty(mediaType)){
                httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                httpHeaders.setContentDisposition(ContentDisposition.attachment().filename(imgFile.getName()).build());
            }else{
                httpHeaders.setContentType(MediaType.parseMediaType(mediaType));
            }

            return new ResponseEntity<>(new InputStreamResource(FileUtil.getInputStream(imgFile)), httpHeaders, HttpStatus.OK);

        } catch (Exception e) {
            logger.error("static file error", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 渠道订单号条形码图片预览
     * @return
     */
    @RequestMapping("/api/anon/localOssFiles/bar/{content}")
    @ResponseBody
    public void couponCode(@PathVariable("content") String content) throws IOException, WriterException {

        int width = getValIntegerDefault("width", 230);
        int height = getValIntegerDefault( "height", 75);
        CodeImgUtil.writeBarCode(response.getOutputStream(), content, width, height);
    }

    /** 地址过滤： 1. 非法路径过滤 2.特殊字符过滤。   **/
    private String cleanPath(String pathAndFileName){

        if(pathAndFileName == null){
            return null;
        }

        // 获取到文件路径地址
        String[] fileAndPathArray = pathAndFileName.split("\\/");

        // 安全验证是否和读取该文件
        if(fileAndPathArray.length < 1 || OssFileConfig.getOssFileConfigByBizType(fileAndPathArray[0]) == null){
            throw new BizException("路径不合法");
        }

        pathAndFileName = pathAndFileName.replaceAll("\\.\\.", "");

        String result = "";
        for (int i = 0 ; i < pathAndFileName.length(); i++ ){
            result += cleanChar(pathAndFileName.charAt(i));
        }

        return result;
    }

    private char cleanChar(char ac){

        for(int i = 48; i < 58; i++ ){
            if(ac == i){
                return (char) i;
            }
        }

        for(int i = 65; i < 91;  i++ ){
            if(ac == i){
                return (char) i;
            }
        }

        for(int i = 97; i < 123;  i++ ){
            if(ac == i){
                return (char) i;
            }
        }

        switch (ac){
            case '/': return '/';
            case '.': return '.';
            case '-': return '-';
            case '_': return '_';
            default: return '?';
        }
    }



    public static void main(String[] args) {
        System.out.println(ContentType.build("jpg", Charset.defaultCharset()));
    }


}
