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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.module.custom.ocr.api.entity.BaseResult;
import org.jeecg.module.custom.ocr.api.entity.FormConfigResult;
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.controller.dto.FormSyncRequest;
import org.jeecg.module.custom.ocr.dataDao.FormConfigMapper;
import org.jeecg.module.custom.ocr.dataobject.FormConfig;
import org.jeecg.module.custom.ocr.service.FormConfigService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Slf4j
@Service
public class FormConfigServiceImpl extends ServiceImpl<FormConfigMapper, FormConfig> implements FormConfigService {

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

    @Transactional(rollbackFor = Exception.class)
    @SneakyThrows
    @Override
    public BaseResult<FormConfigResult> sync(FormSyncRequest request) {
        //2.对象转map
        Map<String, Object> queryParam = BeanUtil.beanToMap(request);

        //加密请求参数
        String tenantNo = request.getTenantNo().toString();
        String json = JSONObject.toJSONString(queryParam);
        RequestData requestData = ApiHelper.buildRequest(tenantNo, apiConfig.getAccessKey(), apiConfig.getAccessCode(), json);
        //组装请求参数
        String url = apiConfig.getInterfaceDomain() + apiConfig.getFormConfigUrl();
        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);
        //定义返回对象
        FormConfigResult formConfigResult = null;
        BaseResult<FormConfigResult> baseResult = null;
        //解密请求数据
        if (resultData.getStatus() == 100) {
            //解析基础数据
            String data = ApiHelper.decryptResponse(apiConfig.getAccessCode(), resultData);
            baseResult = JSONUtil.toBean(data, BaseResult.class);
            if ("200".equals(baseResult.getStatus())) {
                formConfigResult = baseResult.getData();
                FormConfig formConfig = FormConfig.builder()
                        .status(baseResult.getStatus())
                        .message(baseResult.getMessage())
                        .timestamp(baseResult.getTimeStamp())
                        .signature(baseResult.getSignature())
                        .data(JSONObject.toJSONString(baseResult.getData()))
                        .tenantNo(formConfigResult.getTenantNo())
                        .accountNo(formConfigResult.getAccountNo())
                        .projectNo(formConfigResult.getProjectNo())
                        .taskFormNo(formConfigResult.getTaskFormNo())
                        .fieldList(JSONObject.toJSONString(formConfigResult.getFieldList()))
                        .type(formConfigResult.getType())
                        .fieldCode(formConfigResult.getFieldCode())
                        .fieldName(formConfigResult.getFieldName())
                        .parentFileCode(formConfigResult.getParentFileCode())
                        .level(formConfigResult.getLevel())
                        .build();
                this.save(formConfig);
            }

        } else {
            log.error("请求图片接口数据失败,参数:{},返回值:{}", json, responseJsonStr);
        }

        return baseResult;
    }
}
