package com.heyu.api.baidu.handle.convert;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.heyu.api.baidu.BaiduBaseHandle;
import com.heyu.api.baidu.request.convert.BTextreviewRequest;
import com.heyu.api.baidu.response.convert.BTextreviewResp;
import com.heyu.api.data.utils.SpringContextUtils;
import com.heyu.api.data.utils.StringUtils;
import com.heyu.api.oss.OssFileUploadService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/***
 * https://console.bce.baidu.com/support/?_=1740667714316&timestamp=1740672614231#/api?product=AI&project=%E6%96%87%E5%AD%97%E8%AF%86%E5%88%AB&parent=%E6%99%BA%E8%83%BD%E6%96%87%E6%A1%A3%E5%88%86%E6%9E%90&api=file%2F2.0%2Fbrain%2Fonline%2Fv1%2Ftextreview%2Ftask%2Fquery&method=post
 *合同审查-提交请求
 *
 */
@Component
@Slf4j
public class BTextreviewHandle extends BaiduBaseHandle<BTextreviewRequest, BTextreviewResp> {

    public static Map<String, Object> suport = Maps.newHashMap();

    static {
        suport.put("Sales_PartyA_V2", "买卖合同-买方");
        suport.put("Sales_PartyB_V2", "买卖合同-卖方");
        suport.put("Lease_PartyA_V2", "租赁合同-出租方");
        suport.put("Lease_PartyB_V2", "租赁合同-承租方");
        suport.put("TechDev_PartyA_V2", "技术开发合同-委托方");
        suport.put("TechDev_PartyB_V2", "技术开发合同-受托方");
        suport.put("Labor_PartyA_V2", "劳动合同-用人单位");
        suport.put("Labor_PartyB_V2", "劳动合同-劳动者");
        suport.put("Entrustment_PartyA_V2", "委托合同-委托方");
        suport.put("Entrustment_PartyB_V2", "委托合同-受托方");
        suport.put("Work-for-hire_PartyA_V2", "承揽合同-定作人");
        suport.put("Work-for-hire_PartyB_V2", "承揽合同-承揽人");
        suport.put("LaborDispatch_PartyA_V2", "劳务派遣合同-用工单位");
        suport.put("LaborDispatch_PartyB_V2", "劳务派遣合同-劳务派遣单位");
        suport.put("RealtySvcs_PartyA_V2", "物业服务合同-业主");
        suport.put("RealtySvcs_PartyB_V2", "物业服务合同-物业服务人");
        suport.put("EquipPur_PartyA_V2", "设备采购合同-买方");
        suport.put("EquipPur_PartyB_V2", "设备采购合同-卖方");
        suport.put("FinLease_PartyA_V2", "融资租赁合同-出租方");
        suport.put("FinLease_PartyB_V2", "融资租赁合同-承租方");
        suport.put("DebtAssign_PartyA_V2", "债权转让合同-转让方");
        suport.put("DebtAssign_PartyB_V2", "债权转让合同-受让方");
        suport.put("CISG_PartyA_V2", "国际货物贸易合同-买方");
        suport.put("CISG_PartyB_V2", "国际货物贸易合同-卖方 ");
        suport.put("GUAR_PartyA_V2", "保证合同-保证方 ");
        suport.put("GUAR_PartyA_V2", "保证合同-债权方 ");
        suport.put("CG_PartyA_V2", "货运合同-承运方 ");
        suport.put("CG_PartyB_V2", "货运合同-托运方 ");
        suport.put("Factoring_PartyA_V2", "保理合同-保理商 ");
        suport.put("Factoring_PartyB_V2", "保理合同-卖方 ");
        suport.put("Brokerage_PartyA_V2", "中介合同-委托人 ");
        suport.put("Brokerage_PartyB_V2", "中介合同-中介人 ");
        suport.put("TradingTrust_PartyA_V2", "行纪合同-委托人 ");
        suport.put("TradingTrust_PartyB_V2", "行纪合同-行纪人 ");
        suport.put("PNRship_V2", "合伙合同 ");
        suport.put("PT/PAT_PartyA_V2", "专利（申请）权转让合同-受让方 ");
        suport.put("PT/PAT_PartyB_V2", "专利（申请）权转让合同-转让方");
        suport.put("TST_PartyA_V2", "技术秘密转让合同-受让方");
        suport.put("TST_PartyB_V2", "技术秘密转让合同-转让");
    }

    public final List<String> list = Arrays.asList("normal", "major", "all");

    @Override
    public String getUri() {
        return "/file/2.0/brain/online/v1/textreview/task/query";
    }

    @Override
    public String check(BTextreviewRequest bTextreviewRequest) {
        if (StringUtils.isBlank(bTextreviewRequest.getFileURL())
                && bTextreviewRequest.getFileBase64() == null) {
            return "fileURL 和file 不能同时为空 ";
        }
        if(StringUtils.isNotBlank(bTextreviewRequest.getFileBase64())){
            OssFileUploadService ossFileUploadService = SpringContextUtils.getBean(OssFileUploadService.class);

            //下面对图片大小，格式做判断是否符合要求，不符合要求直接返回提示
            String base64;
            if (bTextreviewRequest.getFileBase64().startsWith("data")) {
                base64 = bTextreviewRequest.getFileBase64().substring(bTextreviewRequest.getFileBase64().indexOf("base64,") + 7);
            } else {
                base64 = bTextreviewRequest.getFileBase64();
            }
            if (!base64.startsWith("/9j/")) {
                log.info("图片格式错误，只支持jpg格式");
                return "图片格式错误，只支持jpg格式";
            }

            String url = ossFileUploadService.uploadFileContentByBase64(bTextreviewRequest.getFileBase64(), "jpg");
            if (StringUtils.isBlank(url)) {
                log.error(" oss file upload is null");
                return "你的base64内容有误";
            }
            bTextreviewRequest.setFileURL(url);
        }

        if (!suport.containsKey(bTextreviewRequest.getTemplateName())) {
            return " templateName 必须为 " + StringUtils.printMap(suport);
        }
        if (!list.contains(bTextreviewRequest.getCommentRiskLevel())) {
            return " commentRiskLevel 必须为 " + list;
        }
        return null;
    }


    @Override
    public Request createRequest(String content) {
        BTextreviewRequest bTextreviewRequest = JSONObject.parseObject(content, BTextreviewRequest.class);
        MediaType mediaType = MediaType.parse("multipart/form-data");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("fileURLList", bTextreviewRequest.getFileURL())
                .addFormDataPart("templateName", bTextreviewRequest.getTemplateName())
                .addFormDataPart("commentRiskLevel", bTextreviewRequest.getCommentRiskLevel())
                .build();

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/" + getUri() + "?access_token=" + getBaiduAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "multipart/form-data")
                .build();
        return request;
    }

    @Override
    public String getContent(BTextreviewRequest bTextreviewRequest) {

        return JSON.toJSONString(bTextreviewRequest);
    }
}
