package com.bcxin.backend.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.bcxin.backend.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/document/signature")
public class DocumentSignatureController {

    @Value("${myapps.addin.exe}")
    String exepath;
    @Value("${myapps.this.ip}")
    String thisIp;
    @Value("${server.port}")
    String port;
    @Value("${myapps.domain.url}")
    String url;
    @Value("${myapps.storage.root}")
    String rootPath;

    @Autowired
    private Environment env;

    private static String jwtKey = "sdoDFyzfieqMrisd0H5o5t9weOl6GmSr";

    @RequestMapping("/multBrowser")
    public String multBrowser(HttpServletRequest request, Model model) throws URISyntaxException {
        String path = request.getParameter("documentPath");
        String business_no = request.getParameter("business_no");//签章业务编号
        String business_user_id = request.getParameter("business_user_id");//操作人:警号,姓名
        String use_seal_explain = request.getParameter("use_seal_explain");//用章事由
        if(StringUtils.isEmpty(path)||StringUtils.isEmpty(business_no)||StringUtils.isEmpty(business_user_id)){
            throw new RuntimeException("必要参数缺失！");
        }
        path = url.startsWith("http")?path:url+path;
        Map<String, Object> payload = new HashMap<>();
        payload.put("path",path);
        payload.put("business_no",business_no);
        payload.put("business_user_id",business_user_id);
        payload.put("use_seal_explain",use_seal_explain);
        String api = "http://"+thisIp+":"+port+"/document/signature/iWebPDFEditor/"+JWTUtil.createToken(payload,jwtKey.getBytes());
        model.addAttribute("exepath",exepath);
        model.addAttribute("apiHead",api);
        return "multBrowser";
    }
    @RequestMapping("/iWebPDFEditor/{token}")
    public String iWebPDFEditor(@PathVariable String token,HttpServletRequest request, Model model) {
        JWT jwt = JWTUtil.parseToken(token);
        //获取全部载荷信息
        JWTPayload ipayload = jwt.getPayload();
        String path = ipayload.getClaimsJson().get("path", String.class);
        String business_no = ipayload.getClaimsJson().get("business_no", String.class);
        String business_user_id = ipayload.getClaimsJson().get("business_user_id", String.class);
        String use_seal_explain = ipayload.getClaimsJson().get("use_seal_explain", String.class);
        //验证是否正确
        boolean verify = jwt.setKey(jwtKey.getBytes()).verify();
        if(!verify){
            throw new RuntimeException("参数异常！");
        }
        //验证是否过期
        boolean validate = jwt.validate(0);
        if(!validate){
            throw new RuntimeException("token过期！");
        }
        Map<String, Object> payload = new HashMap<>();
        payload.put("path",path);
        //原地址可能有中文，要做下转存，转存新地址给控件去打开操作
        String oidPath = rootPath+path.replace(url,"");
        File f = new File(oidPath);
        if (!f.exists()) {
            throw new RuntimeException("文件不存在！");
        }
        String name = f.getName();
        String type = FileUtil.getSuffix(f);
        String newName = IdUtil.randomUUID()+"."+type;
        String newPath = oidPath.replace(name,newName);
        FileUtil.copy(oidPath,newPath,true);
        model.addAttribute("path",path.replace(name,newName));
//        model.addAttribute("env",env.getProperty("spring.profiles.active"));
        String uploadApi = "http://"+thisIp+":"+port+"/document/signature/uploadBase64/"+JWTUtil.createToken(payload,jwtKey.getBytes());
        model.addAttribute("apiHead",uploadApi);
        model.addAttribute("business_no",business_no);
        model.addAttribute("business_user_id",business_user_id);
        model.addAttribute("use_seal_explain",use_seal_explain);
//        model.addAttribute("token", JWTUtil.createToken(payload,jwtKey.getBytes()));
        return "iWebPDFEditor";
    }

    @RequestMapping("/uploadBase64/{token}")
    public @ResponseBody Result uploadBase64(@PathVariable String token, HttpServletRequest request) {

        JWT jwt = JWTUtil.parseToken(token);
        //获取全部载荷信息
        JWTPayload payload = jwt.getPayload();
        String path = payload.getClaimsJson().get("path", String.class);
        String serverPath = rootPath+path.replace(url,"");
        //验证是否正确
        boolean verify = jwt.setKey(jwtKey.getBytes()).verify();
        if(!verify){
            return Result.fail("参数异常");
        }
        //验证是否过期
        boolean validate = jwt.validate(0);
        if(!validate){
            return Result.fail("token过期");
        }
//        serverPath = "D:"+serverPath;
//        String filename = "D://data//bbb.pdf";
        System.out.println(serverPath);
        File f = new File(serverPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        try(InputStream in = request.getInputStream();FileOutputStream fos = new FileOutputStream(f);) {
            byte[] b = new byte[1024];
            int n = 0;
            while ((n = in.read(b)) != -1) {
                fos.write(b, 0, n);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("ok");
    }

    public static void main(String[] args) {
        /*String oidPath = "D:\\data\\a9.pdf";
        File f = new File(oidPath);
        if (!f.exists()) {
            throw new RuntimeException("文件不存在！");
        }
        String name = f.getName();
        String type = FileUtil.getSuffix(f);
        String newName = IdUtil.randomUUID()+"."+type;
        String newPath = oidPath.replace(name,newName);
        FileUtil.copy(oidPath,newPath,true);*/
//        String oidPath = "D:\\data\\a9.pdf";
//        File f = new File(oidPath);
//        System.out.println(FileUtil.getName(f));
//        System.out.println(FileUtil.getType(f));
//        System.out.println(FileUtil.getPrefix(f));
//        System.out.println(FileUtil.getSuffix(f));

//        System.out.println(UUID.randomUUID().toString());
//        System.out.println(IdUtil.randomUUID());
    }
}
