package com.shkj.wms.controller.jmreport;

import com.alibaba.fastjson.JSONObject;
import com.shkj.common.config.ShkjConfig;
import com.shkj.common.core.controller.BaseController;
import com.shkj.common.core.domain.Result;
import com.shkj.common.utils.SecurityUtils;
import com.shkj.framework.config.ServerConfig;
import com.shkj.wms.bo.PrintHtmlBo;
import com.shkj.wms.service.IJimuReportTypeConfigService;
import com.shkj.wms.domain.JimuReportTypeConfig;
import com.shkj.wms.utils.PdfConvertHtmlUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.*;

/**
 * 公共方法
 *
 * @author lch
 * @menu 公共方法
 * @date 2022-03-19
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/wms/jmreport/")
public class JmReportController extends BaseController {

    @Value("${server.port}")
    private String port;


    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IJimuReportTypeConfigService jimuReportTypeConfigService;

    /**
     * 获取报表的html地址
     *
     * @param printHtmlBo
     * @return
     */
    @PostMapping("/getHtmlUrl")
    public Result<String> getHtmlUrl(@Valid @RequestBody PrintHtmlBo printHtmlBo) {
        logger.info("printHtmlBo = {}", printHtmlBo);
        if (printHtmlBo.getParams() == null) {
            printHtmlBo.setParams(new HashMap<>());
        }

        List<JimuReportTypeConfig> list = jimuReportTypeConfigService.getReportTypeByTypeAndBranchId(printHtmlBo.getReportType(), SecurityUtils.getCurrentBranchId());
        if (CollectionUtils.isEmpty(list)) {
            return Result.err().msg("报表类型错误、请先配置报表类型");
        }

        JimuReportTypeConfig config = list.stream().filter(x -> x.getBranchId().equals(SecurityUtils.getCurrentBranchId())).findFirst().orElse(null);
//        JmReportTypeEnum typeEnum = JmReportTypeEnum.getJmReportTypeEnum(printHtmlBo.getReportType());
        if (config == null) {
            config = list.stream().filter(x -> x.getBranchId().equals(0L)).findFirst().orElse(null);
            if (config == null) {
                return Result.err().msg("没有当前仓库设置的报表类型");
            }
        }
        String excelConfigId = config.getExcelConfigId();

        RestTemplate restTemplate = new RestTemplate();
        //创建url路径
        String url = serverConfig.getUrl() + "/jmreport/exportPdf";
        Map<String, Object> map = new HashMap<>();

        //此处为示例，需要传递api和sql的正确参数值
//        object.put("name", "张三");
        //queryParam中有个特殊属性 dpi每英寸点数,windows是96，可不用传
//        object.put("dpi", "96");
        map.put("excelConfigId", excelConfigId);


        map.put("queryParam", printHtmlBo.getParams());
        HttpHeaders headers = new HttpHeaders();
        //如果有字典需要传token
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map, headers);
        try {
            String apiResult = restTemplate.postForObject(url, httpEntity, String.class);
            JSONObject jsonObject = JSONObject.parseObject(apiResult);
            Object code = jsonObject.get("code");
            if (null != code && !"".equals(String.valueOf(code)) && "200".equals(String.valueOf(code))) {
                JSONObject result = jsonObject.getJSONObject("result");
                //文件byte64字符串
                String file = result.getString("file");
                //转换成byte
                byte[] buffer = Base64Utils.decodeFromString(file);

                InputStream inputStream = new ByteArrayInputStream(buffer);
                BufferedImage bufferedImage = PdfConvertHtmlUtil.pdfStreamToPng(inputStream);
                String base64_png = PdfConvertHtmlUtil.bufferedImageToBase64(bufferedImage);
                String baseDir = ShkjConfig.getUploadPath();
                String fileName = UUID.randomUUID().toString();
                String htmlPath = baseDir + File.separator + fileName + ".html";
                PdfConvertHtmlUtil.createHtmlByBase64(base64_png, htmlPath);

                return Result.ok().data(ShkjConfig.getUrlPre() + htmlPath);

            }
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return Result.err().msg("系统错误");
    }

    /**
     * 获取报表的html地址 集合形式
     *
     * @param printHtmlBos
     * @return
     */
    @PostMapping("/getHtmlUrlList")
    public Result<List<String>> getHtmlUrlList(@Valid @RequestBody List<PrintHtmlBo> printHtmlBos) {
        List<String> stringList = new ArrayList<>();
        for (PrintHtmlBo printHtmlBo : printHtmlBos) {
            Result<String> result = getHtmlUrl(printHtmlBo);
            if (!Result.isOk(result)) {
                return Result.err().msg(result.getMsg());
            }
            String data = result.getData();
            stringList.add(data);
        }
        return Result.ok().data(stringList);
    }

}
