package com.malk.yangu.controller;

/**
 * 错误抛出与拦截详见 CatchException
 */

import com.malk.server.common.McException;
import com.malk.server.common.McR;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilMap;
import com.malk.yangu.tencent.TXYInvoice;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

@Slf4j
@RestController
@RequestMapping
public class YGController {

    @Autowired
    private YDClient ydClient;

    @Autowired
    private TXYInvoice txyInvoice;

    /// url压缩转base64
    @SneakyThrows
    private String imageUrlConvertBase64(String imageUrl) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // scale(比例), outputQuality(质量)
        Thumbnails.fromURLs(Arrays.asList(new URL(imageUrl))).scale(0.5f).outputQuality(0.25f).toOutputStream(out);
        InputStream inputStream = new ByteArrayInputStream(out.toByteArray());
        //转换为base64
        byte[] bytes = IOUtils.toByteArray(inputStream);
        return Base64.getEncoder().encodeToString(bytes);
    }

    /// 优先获取字段, 新版本接口已支持字段返回
    private String findValue(List<Map> infos, String... names) {
        for (String name : names) {
            Optional optional = infos.stream().filter(info -> info.get("Name").equals(name)).findAny();
            if (optional.isPresent()) {
                return String.valueOf(((Map) optional.get()).get("Value"));
            }
        }
        return "";
    }

    /**
     * 名片识别
     */
    @PostMapping("card-mp")
    McR card_mp(@RequestBody Map<String, ?> data) throws TencentCloudSDKException {
        McException.assertParamException_Null(data, "url");
        String image = ydClient.convertTemporaryUrl(data.get("url").toString());
        log.info("名片识别, 免登地址, {}", image);
        // 非PDF, 且内存大于3M, 压缩后上传
        if (UtilMap.getFloat(data, "size") > 3.0f) {
            image = imageUrlConvertBase64(image);
        }
        List<Map> results = (List<Map>) txyInvoice.doBusinessCardOCR(image).get("BusinessCardInfos");

        // 数据字段拼接 [formData.put("textField_lki2ir0k", findValue(results, "手机", "电话"));]
        Map<String, String> compIds = (Map) data.get("compIds");
        Map formData = new HashMap();
        for (String compId : compIds.keySet()) {
            formData.put(compId, findValue(results, compIds.get(compId).split(", ")));
        }
        return McR.success(formData);
    }
}
