package com.qmth.distributed.print;

import com.alibaba.fastjson.JSONObject;
import com.qmth.boot.tools.signature.SignatureType;
import com.qmth.teachcloud.common.SignatureEntityTest;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.SyncFileTypeEnum;
import com.qmth.teachcloud.common.util.HttpKit;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class UploadCardTest {

    static String accessKey = "d81badf113d1450c9f554809e1282ae1";
    static String accessSecret = "dmILQXiRESNasxUylMNGl05R0JsaVb9t";

    @Test
    public void uploadCard() {
        File file = new File("C:\\Users\\xf520\\Desktop\\SOFT400227-操作系统.json");
        String examId = "230";
        String subjectCode = "202211160001A10";
        String hostUrl = "http://192.168.10.225:8000";

        SyncFileTypeEnum type = SyncFileTypeEnum.CARD;
        String fileUploadUrl = SystemConstant.CLOUD_MARK_FILE_UPLOAD_API;
        fileUploadUrl = fileUploadUrl.replace("{type}", type.name().toLowerCase());
        String postUrl = hostUrl.concat(fileUploadUrl);
        try {
            Map<String, String> files = new HashMap<>();
            if (file.exists()) {
                files.put(file.getName(), file.getPath());
            }
            //表单数据
            Map<String, Object> formText = new HashMap<>();
            formText.put("examId", examId);
            formText.put("subjectCode", subjectCode);
            String fileName = file.getName();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (type.equals(SyncFileTypeEnum.CARD)) {
                if (!"zip".equals(suffix) && !"json".equals(suffix)) {
                    throw ExceptionResultEnum.ERROR.exception("文件类型有误");
                }
            } else if (type.equals(SyncFileTypeEnum.PAPER) || type.equals(SyncFileTypeEnum.ANSWER)) {
                if (!"pdf".equals(suffix) && !"json".equals(suffix)) {
                    throw ExceptionResultEnum.ERROR.exception("文件类型有误");
                }
            } else {
                throw ExceptionResultEnum.ERROR.exception("请传入文件上传类型");
            }
            formText.put("format", suffix);
            formText.put("md5", DigestUtils.md5Hex(new FileInputStream(file)));

            String result = HttpKit.sendPost(postUrl, getHeaders(fileUploadUrl), formText, files, null, null);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.containsKey("success")) {
                String success = jsonObject.get("success").toString();
                if (Boolean.parseBoolean(success)) {
                    if (jsonObject.containsKey("url")) {
                        System.out.println(jsonObject.get("url").toString());
                    } else {
                        System.out.println(success);
                    }
                }
            }
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception(e.getMessage());
        } finally {
            if (file != null && file.exists()) {
                file.delete();
            }
        }
    }

    private Map<String, String> getHeaders(String url) {
        long time = System.currentTimeMillis();
        Map<String, String> header = new HashMap<>();
        header.put(SystemConstant.HEADER_AUTHORIZATION, createSign(time, url));
        header.put(SystemConstant.HEADER_TIME, String.valueOf(time));
        return header;
    }

    private String createSign(long time, String url) {
        return SignatureEntityTest.build(SignatureType.SECRET, "POST", url, time, accessKey, accessSecret);
    }
}
