package org.jeecg.module.custom.ocr.api.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.module.custom.ocr.api.PrevailCloudApi;
import org.jeecg.module.custom.ocr.api.entity.FormRecord;
import org.jeecg.module.custom.ocr.api.entity.PictureSourceParameter;
import org.jeecg.module.custom.ocr.base.constant.PrevailCloudConstant;
import org.jeecg.module.custom.ocr.common.entity.ApiPage;
import org.jeecg.module.custom.ocr.common.entity.RequestData;
import org.jeecg.module.custom.ocr.common.entity.ResultData;
import org.jeecg.module.custom.ocr.config.ApiConfig;
import org.jeecg.module.custom.ocr.dataobject.OcrPrevailCloudLog;
import org.jeecg.module.custom.ocr.service.OcrPrevailCloudLogService;
import org.jeecg.module.custom.ocr.utils.ApiHelper;
import org.jeecg.module.custom.ocr.utils.httputil.HttpClient;
import org.jeecg.module.custom.ocr.utils.httputil.HttpMethod;
import org.jeecg.module.custom.ocr.utils.httputil.HttpParamers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图片数据接口实现类
 *
 * @author hugh(shuli.yao) 1397940314@qq.com
 * @version 1.0
 * @date 2024/3/14 10:16
 */
@Service("ocrPrevailCloudApiImpl")
public class PrevailCloudApiImpl implements PrevailCloudApi {

    private static Logger logger = LoggerFactory.getLogger(PrevailCloudApiImpl.class);

    /**
     * 注入api 配置信息
     */
    @Autowired
    private ApiConfig apiConfig;

    @Resource
    private OcrPrevailCloudLogService ocrPrevailCloudLogService;


    @Override
    public ApiPage<FormRecord> pullPictureSourceAll(PictureSourceParameter pictureSourceParameter) throws Exception {
        //1.检查api配置是否正常
        if (!apiConfig.checkConfig()) {
            throw new Exception("api config 配置错误!");
        }

        OcrPrevailCloudLog prevailCloudLog = new OcrPrevailCloudLog();
        prevailCloudLog.setType(PrevailCloudConstant.PULL_PICTURE_SOURCE_All);
        prevailCloudLog.setRequestParam(JSONUtil.toJsonStr(pictureSourceParameter));

        //2.对象转map
        Map<String, Object> queryParam = BeanUtil.beanToMap(pictureSourceParameter);
        Map<String, String> queryParamStr = new HashMap<>();
        //map值转string 注意对日期类型进行操作,加密包要求值全部为string
        for (String key : queryParam.keySet()) {
            if (queryParam.get(key) != null) {
                if(key.equals("startTime") || key.equals("endTime")){
                    Date date = (Date) queryParam.get(key);
                    queryParamStr.put(key,String.valueOf(date.getTime()));
                }else{
                    queryParamStr.put(key, queryParam.get(key).toString());
                }
            }
        }

        //加密请求参数
        String tenantNo = pictureSourceParameter.getTenantNo().toString();
        String json = JSONObject.toJSONString(queryParam);
        RequestData requestData = ApiHelper.buildRequest(tenantNo, apiConfig.getAccessKey(), apiConfig.getAccessCode(), json);
        //组装请求参数
        String url = apiConfig.getInterfaceDomain() + apiConfig.getPictureSourceAllUrl();
        String requestBodyJson = JSONObject.toJSONString(requestData);
        //入参
        HttpParamers httpParamers = new HttpParamers(HttpMethod.POST);
        httpParamers.setJsonParamer(requestBodyJson);
        //发起请求
        String responseJsonStr = HttpClient.doPost(url, httpParamers, null, apiConfig.getConnectTimeout(), apiConfig.getReadTimeout());
        ResultData<String> resultData = JSONUtil.toBean(responseJsonStr, ResultData.class);
        prevailCloudLog.setResponseParam("msg:"+resultData.getMessage()+",status:"+resultData.getStatus());
        prevailCloudLog.setStatus(resultData.getStatus());
        //定义返回对象
        ApiPage<FormRecord> resultApiPage = null;
        //解密请求数据
        if (resultData.getStatus() == 100) {
            //解析基础数据
            String data = ApiHelper.decryptResponse(apiConfig.getAccessCode(), resultData);
            ApiPage<String> apiPage = JSONUtil.toBean(data, ApiPage.class);
            //日志增加拉取数量
            prevailCloudLog.setResponseParam(prevailCloudLog.getResponseParam()+",拉取数量:"+apiPage.getTotal());
            if(apiPage.getTotal()!=0){
                //解析数据结果为List
                List<FormRecord> listResult = JSONUtil.toList(JSONObject.toJSONString(apiPage.getRecords()), FormRecord.class);
                resultApiPage = new ApiPage<>();
                resultApiPage.setPageNo(apiPage.getPageNo());
                resultApiPage.setPageSize(apiPage.getPageSize());
                resultApiPage.setTotal(apiPage.getTotal());
                resultApiPage.setRecords(listResult);
            }
        } else {
            logger.error("请求图片接口数据失败,参数:{},返回值:{}", json, responseJsonStr);
        }
        ocrPrevailCloudLogService.save(prevailCloudLog);
        return resultApiPage;
    }
}
