package com.miaxis.app.controller.test;

import com.miaxis.common.constant.Constants;
import com.miaxis.common.core.controller.BaseController;
import com.miaxis.common.core.domain.Response;
import com.miaxis.common.sign.*;
import com.miaxis.news.domain.NewsInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.util.RequestUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

@RestController
@RequestMapping(Constants.OPEN_PREFIX+"/test")
@Api(tags={"【test-文件上传】"})
    public class TestController extends BaseController {
//        @Resource
//        private IQgptService qgptService;

    /**
     * 查询新闻(首页资讯、通知、公告相关)列表
     */
    @PostMapping("/testMethod" )
    @ApiOperation("文件上传" )
    public Response list(HttpServletRequest request,@RequestParam("s") String s, @RequestBody NewsInfo newsInfo) throws Exception {
       System.out.println( RequestUtil.getRequestURL(request));;
        System.out.println("d");
        return  null ;
    }

        /**
         * 查询新闻(首页资讯、通知、公告相关)列表
         */
        @PostMapping("/fileupload" )
        @ApiOperation("文件上传" )
        public Response list(@RequestPart("file") MultipartFile file) throws Exception {
//            File file =new File("F:/doc/img/gen-view.jpg");
            long timestamp = System.currentTimeMillis(); // 时间戳
            String sign_str = ""; // 签名
            /* 获取签名 */
            String path = getClass().getResource("/").getPath();
            java.io.File jarFile = new java.io.File(path);
            String propertiesfile = jarFile.getParentFile().getAbsolutePath().replace("%20", " ");
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            InputStream input = new FileInputStream(propertiesfile + PlatUtil.privateKeyUrl);
            keyStore.load(input, PlatUtil.keyPassword.toCharArray());
            Enumeration<String> aliases = keyStore.aliases();
            if (!aliases.hasMoreElements()) {
                throw new RuntimeException("HTTP接口协议签名获取失败: no alias found");
            }
            String alias = aliases.nextElement();
            PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, PlatUtil.keyPassword.toCharArray()); // 私钥
            ISign sign = new Sign();
            byte[] data = file.getBytes();
            sign_str = sign.sign(data, timestamp, privateKey);

            /* 验证签名 */
            X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
            String serialNumber = cert.getSerialNumber().toString(); // 证书序列号
            long snInteger = Long.parseLong(serialNumber);
            serialNumber = Long.toHexString(snInteger).toUpperCase();
            IVerify verify = new Verify();
            boolean ok = verify.verify(data, timestamp, sign_str, cert);
            System.out.println(ok);
           // MultipartFile multipartFile = fileToMultipartFile(file);
//        Map resultMap = qgptService.imageup(multipartFile);

//            Map resultMap = qgptService.imageup(PlatUtil.url_version, String.valueOf(System.currentTimeMillis()), serialNumber, sign_str,file);
//            System.out.println(resultMap);
            return Response.success();
        }

    public static MultipartFile fileToMultipartFile(File file) {
        String fieldName = "file";  //重点  这个名字需要和你对接的MultipartFil的名称一样
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "multipart/form-data", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }


}
