package com.dxhy.portrait.business.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.portrait.business.entity.ocr.OcrDiscAuthorize;
import com.dxhy.portrait.business.entity.ocr.OcrDiscGlobalInfo;
import com.dxhy.portrait.business.entity.ocr.OcrDiscernRequest;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author dxhy
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Service
@Slf4j
public class MixedScanOcrService {

    @Value("${ocrs.url}")
    private String url;

    @Value("${ocrs.appId}")
    private String appId;

    @Value("${ocrs.version}")
    private String version;

    @Value("${ocrs.enterpriseCode}")
    private String enterpriseCode;

    @Value("${ocrs.appKey}")
    private String appKey;

    @Value("${ocrs.appSce}")
    private String appSce;

    public Map<String, Object> discernInvoice(String userid, String uuid, String picBase64) {

        // 封装数据
        OcrDiscAuthorize authorize = new OcrDiscAuthorize();
        authorize.setAppKey(appKey);
        authorize.setAppSec(appSce);

        OcrDiscGlobalInfo globalInfo = new OcrDiscGlobalInfo();
        globalInfo.setAppId(appId);
        globalInfo.setVersion(version);
        globalInfo.setEnterpriseCode(enterpriseCode);
        globalInfo.setUserId(userid);
        globalInfo.setUuid(uuid);

        OcrDiscernRequest request = new OcrDiscernRequest();

        request.setAuthorize(authorize);
        request.setGlobalInfo(globalInfo);
        request.setPicture(picBase64);

        String requestStr = JSONObject.toJSONString(request);
        Map<String, Object> resultMap = new HashMap<>(3);
        try {
            if (log.isDebugEnabled()) {
                log.debug("url:{}  param:{}", url, requestStr);
            }

            String responseStr = HttpUtil.post(url, requestStr, 30000);
            if (responseStr.startsWith("{")) {
                JSONObject obj = JSONObject.parseObject(responseStr);
                log.info("返回的响应报文:{}", obj.toString());
                Map<String, String> returnStateInfo = (Map<String, String>)obj.get("returnStateInfo");
                JSONArray invoice = (JSONArray)obj.get("invoice");
                resultMap.putAll(returnStateInfo);
                resultMap.put("invoice", invoice.toString());
            } else {
                log.error("发票识别服务的接口调用返回信息不是json信息。返回信息:{}", responseStr);
                resultMap.put("returnCode", "9999");
                resultMap.put("returnMessage", responseStr);
            }
        } catch (Exception e) {
            resultMap.put("returnCode", "9999");
            resultMap.put("returnMessage", "报错了");

        }
        return resultMap;
    }
}
