package com.artfess.cqxy.projectManagement.controller;


import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.controller.BaseController;
import com.artfess.base.exception.BaseException;
import com.artfess.base.model.CommonResult;
import com.artfess.cqxy.universal.manager.AccessoryManager;
import com.artfess.cqxy.universal.model.Accessory;
import com.artfess.redis.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;


/**
 * APP管理 前端控制器
 *
 * @company 阿特菲斯信息技术有限公司
 * @author baseli
 * @since 2022-01-05
 */
@RestController
@Slf4j
@RequestMapping("/bizAPP/v1/")
@Api(tags = "APP管理")
@ApiGroup(group = {ApiGroupConsts.GROUP_BIZ})
public class AppController extends BaseController<AccessoryManager, Accessory> {


    @Resource
    private RedisUtil redisUtil;

    /**
     * 项目根目录
     */
    public static final String ROOT_PATH = System.getProperty("user.dir");

    /**
     * app存放目录名
     */
    public static final String DATA_TEMP_FILE = "appFile";

    /**
     * app存放全目录
     */
    public static final String TEMP_DATA_EXCEL = ROOT_PATH + File.separator + DATA_TEMP_FILE;

    /**
     * APP文件名称
     */
    public static String FILE_NNAME = "H5_XYPM_APP_V1.0.apk";

    /**
     * APP文件存放全路径
     */
    public static String FILE_PATH = TEMP_DATA_EXCEL + File.separator + FILE_NNAME;


    @PostMapping("/appUpload")
    @ApiOperation(value = "app上传", httpMethod = "POST", notes = "app上传")
    public CommonResult<String> minioDrawingUpload(@RequestParam("file") MultipartFile file) throws  Exception{
        if (file.isEmpty()) {
            throw new BaseException("上传文件不能空！");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(FILE_PATH);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);
        return new CommonResult<>("APP上传成功");
    }


    @RequestMapping("/appDownload")
    @ApiOperation(value = "app下载", httpMethod = "POST", notes = "app下载")
//    @AnonymousPostMapping(value = "/appDownload")
    public void minioUpload(HttpServletResponse response, HttpServletRequest request) throws Exception {
//        LocalDate date = LocalDate.now();
//        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
//        String strDate = dtf.format(date);
        OutputStream outp = response.getOutputStream();
        String ip = getVisitorIp(request);
        String key = "BIZ:APP:DOWNLOAD:"+ip;
        Object obj = redisUtil.get(key);
        int num = 1;
        if(obj != null) {
            num = (int) obj;
        }
        if(num > 3){
//            throw new BaseException("您刚刚已下载过一次，请两分钟后再试！");
            response.setHeader("content-type", "text/html;charset=utf-8");
            outp.write("<h1 style='font-size: 2vh;color: #f30707;font-weight: 600;'>您刚刚已下载过了，请两分钟后再次尝试下载！!</h1>".getBytes("utf-8"));
        }else {
            num = num + 1;
            redisUtil.set(key, num, 120);
//            HttpUtil.downLoadFile(response, FILE_PATH, FILE_NNAME);
            String fullPath = FILE_PATH;
            String fileName = FILE_NNAME;
            File file = new File(fullPath);
            if (file.exists()) {
                response.setContentType("application/x-download");
                response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
                if (System.getProperty("file.encoding").equals("GBK")) {
                    response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
                } else {
                    //response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
                    response.addHeader("Content-Disposition", "attachment;filename="+fileName+";filename*=utf-8''"+URLEncoder.encode(fileName,"utf-8") );
                }
                try (FileInputStream in = new FileInputStream(fullPath);){
                    IOUtils.copy(in, outp);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (outp != null) {
                        outp.close();
                        outp = null;
                        response.flushBuffer();
                    }
                }
            } else {
                response.setHeader("content-type", "text/html;charset=utf-8");
                outp.write("<h1 style='font-size: 2vh;color: #f30707;font-weight: 600;'>文件不存在!</h1>".getBytes("utf-8"));
            }
        }
    }

    public String getVisitorIp(HttpServletRequest request){
        // 优先取 X-Real-IP
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
            if ("0:0:0:0:0:0:0:1".equals(ip))
            {
                ip = "unknown";
            }
        }
        if ("unknown".equalsIgnoreCase(ip)){
            ip = "unknown";
            return ip;
        }
        int index = ip.indexOf(',');
        if (index >= 0){
            ip = ip.substring(0, index);
        }
        return ip;
    }

}
