package com.esv.freight.file.module.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.esv.freight.file.BaseTestController;
import com.esv.freight.file.common.response.ECode;
import com.esv.freight.file.common.util.DateUtils;
import com.esv.freight.file.module.file.form.WaterMarkForm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Base64;

/**
 * @description:
 * @project: freight-file-service
 * @name: com.esv.freight.file.module.file.controller.WatermarkControllerTest
 * @author: 黄朝斌
 * @email: huangchaobin@esvtek.com
 * @createTime: 2020/05/28 14:59
 * @version:1.0
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class WatermarkControllerTest extends BaseTestController {

    @Test
    public void a1_imageWithWatermark_success_test() throws Exception {
        String url = "/upload/imageWithWatermark";

        // 构造数据
        String filepath = "D:\\test\\市府广场-1.jpg";
        File file = new File(filepath);
        InputStream input = new FileInputStream(file);

        WaterMarkForm form = new WaterMarkForm();
        form.setFileData(Base64.getEncoder().encodeToString(IOUtils.toByteArray(input)));
        form.setFileName("图片水印合成"+System.currentTimeMillis()+".jpg");
        form.setText("沈阳市沈河区青年大街1号|" + DateUtils.getSysdateStr());

        MvcResult mvcResult = this.getMockMvc().perform(MockMvcRequestBuilders.post(url)
                .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
                .content(form.toString()))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn();

        String responseStr = mvcResult.getResponse().getContentAsString();
        log.info(responseStr);

        JSONObject result = JSONObject.parseObject(responseStr);
        Assert.assertEquals(ECode.SUCCESS.code(), result.getIntValue("code"));
        Assert.assertTrue(result.getJSONObject("data").containsKey("id"));
        Assert.assertTrue(result.getJSONObject("data").containsKey("url"));
    }
}
