package yem.wm.cm.csrm.thirdapi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.qing.util.MapUtils;
import com.kingdee.util.StringUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDBizException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.apache.commons.codec.digest.DigestUtils;
import yem.base.common.utils.HttpHelper;
import yem.wm.cm.sys.utils.CommonUtils;
import yem.wm.cm.sys.utils.ConstantUtils;

import java.util.*;

/**
 * 企查查
 *
 * @Author yunshuaiwei
 * @Date 2024/5/28 9:23
 * @Version 1.0
 **/
public class QccApiImpl implements ThirdPartyApi {

    Log log = LogFactory.getLog(QccApiImpl.class);

    @Override
    public Map<String, String> accessTokenMd5(Long schemeId) {
        String timeSpan = String.valueOf(System.currentTimeMillis() / 1000);
        DynamicObject thirdApiConfig = BusinessDataServiceHelper.loadSingle("yem_third_inter_info",
                "id,number,name,yem_entryentity", new QFilter[]{new QFilter("id", QCP.equals, schemeId)});
        if (thirdApiConfig == null) {
            throw new KDBizException("第三方接口配置信息为空");
        }
        //参数配置
        DynamicObjectCollection entryEntity = thirdApiConfig.getDynamicObjectCollection("yem_entryentity");
        Map<String, Object> params = new HashMap<>();
        for (DynamicObject object : entryEntity) {
            params.put(object.getString("yem_paramkey"), object.getString("yem_paramvalue"));
        }
        String appKey = (String) params.get("appKey");
        String appSecret = (String) params.get("appSecret");
        if (StringUtils.isEmpty(appKey) || StringUtils.isEmpty(appSecret)) {
            throw new KDBizException("appKey和appSecret不能为空");
        }
        Map<String, String> res = new HashMap<>();
        res.put("Token", DigestUtils.md5Hex(appKey.concat(timeSpan).concat(appSecret)).toUpperCase());
        res.put("Timespan", timeSpan);
        return res;
    }


    @Override
    public String getMethod(DynamicObject apiInfo, DynamicObject apiRegister, Map<String, String> params) {
        String stringJson = "";
        String Message = "";
        String Status = "";
        String OrderNumber = "";
        Object schemeId = apiInfo.get("id");
        Map<String, Object> argument = new HashMap<>();
        DynamicObjectCollection entryEntity = apiInfo.getDynamicObjectCollection("yem_entryentity");
        for (DynamicObject object : entryEntity) {
            argument.put(object.getString("yem_paramkey"), object.getString("yem_paramvalue"));
        }
        String appKey = (String) argument.get("appKey");
        String appSecret = (String) argument.get("appSecret");
        Map<String, String> objectMap = accessTokenMd5((Long) schemeId);
        String address = apiRegister.getString("yem_textaddress");
        String name = apiRegister.getString("name");
        String number = apiRegister.getString("number");
        StringBuilder reqUri = new StringBuilder();
        reqUri.append(address).append("?key=").append(appKey);
        if (MapUtils.isNotEmpty(params)) {
            for (String s : params.keySet()) {
                reqUri.append(String.format("&%s=%s", s, params.get(s)));
            }
        }
        try {
            log.info("调用【企查查】接口入参 url=：{},query={}", reqUri, JSON.toJSONString(params));
            stringJson = HttpHelper.httpGet(reqUri.toString(), objectMap);
            log.info("调用【企查查】接口返回值：{}", stringJson);
            JSONObject json = JSONObject.parseObject(stringJson);
            if (json != null && !StringUtils.isEmpty(stringJson)) {
                Status = json.getString("Status");
                OrderNumber = json.getString("OrderNumber");
                if (ConstantUtils.Status_200.equals(Status)) {
                    Message = json.getString("Message");
                }
            } else {
                Status = "404";
                stringJson = null;
                Message = "查询返回为空，异常中断！";
            }
        } catch (Exception e) {
            Status = "500";
            stringJson = null;
            Message = e.getMessage();
        }
        //调用日志
        Map<String, String> datamap = new HashMap<>();
//        datamap.put("opname",operation);
        datamap.put("APInumber", number);
        datamap.put("APIname", name);
        datamap.put("Status", Status);
        datamap.put("Message", Message);
        datamap.put("OrderNumber", OrderNumber);
        datamap.put("stringJson", stringJson);
        CommonUtils.writeInLogin(datamap);
        return stringJson;
    }

    @Override
    public void postMethod(DynamicObject apiInfo, DynamicObject apiRegister, Map<String, String> params) {
    }

    @Override
    public String requestMethod(String number, Map<String, String> params) {
        DynamicObject apiRegister = BusinessDataServiceHelper.loadSingle("yem_api_register",
                "id,number,yem_textaddress,group,yem_reqmethod", new QFilter[]{new QFilter("number", QCP.equals, "number")});
        if (apiRegister == null) {
            throw new KDBizException("接口注册信息为空");
        }
        //第三方接口信息
        DynamicObject apiInfo = apiRegister.getDynamicObject("group");
        String requestMethod = apiInfo.getString("yem_reqmethod");
        if (requestMethod.equals("GET")) {
            return getMethod(apiInfo, apiRegister, params);
        }
        return "";
    }
}
