package org.jeecg.modules.stm.wb.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.stm.wb.manage.entity.WbCompanyDetail;
import org.jeecg.modules.stm.wb.manage.entity.WbCompanyInfo;
import org.jeecg.modules.stm.wb.manage.entity.WbCompanyThirdApi;
import org.jeecg.modules.stm.wb.manage.mapper.WbCompanyDetailMapper;
import org.jeecg.modules.stm.wb.manage.service.IWbCompanyDetailService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.lang.StringBuffer;

/**
 * @Description: wb_company_detail
 * @Author: jeecg-boot
 * @Date:   2024-03-09
 * @Version: V1.0
 */
@Service
public class WbCompanyDetailServiceImpl extends ServiceImpl<WbCompanyDetailMapper, WbCompanyDetail> implements IWbCompanyDetailService {

    @Override
    public WbCompanyDetail getById(Serializable id) {
        return super.getById(id);
    }

    public  Result<List<WbCompanyDetail>> pullDataFromAPI(WbCompanyInfo wbCompanyInfo, WbCompanyThirdApi api, String token) {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
        HttpConnectionParams.setSoTimeout(httpParams, 2000);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        Result<List<WbCompanyDetail>> result = new Result<>();
        try {
            String strUrdl = api.getUrl()+"?keyword=" +  wbCompanyInfo.getName();
            HttpGet get = new HttpGet(strUrdl);
            get.setHeader("Authorization",token);
            HttpResponse response = httpClient.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                String resStr= EntityUtils.toString(response.getEntity(),"utf-8");
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(resStr);
                String retMsg = jsonNode.get("reason").asText();
                int errCode = jsonNode.get("error_code").asInt();
                if(errCode==0) {
                    JsonNode jsonResult = jsonNode.get("result");
                    JsonNode jsonItems = jsonResult.get("items");
                    if(jsonItems!=null){
                        List<WbCompanyDetail> list = parseJSONItems(jsonItems,wbCompanyInfo.getId(),api.getApiId());
                        result.setResult(list);
                    } else {
                        List<WbCompanyDetail> list = parseJSON(jsonResult,wbCompanyInfo.getId(),api.getApiId());
                        result.setResult(list);
                    }
                }
                result.setCode(errCode);
                result.setMessage(retMsg);

            } else {
                result.setCode(500);
                result.setMessage("远程服务器错误");
            }

        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("服务器异常");
            System.out.println();
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
            return result;
        }

    }

    public  Result<List<WbCompanyDetail>>  pullDataFromAPIWithPage(WbCompanyInfo wbCompanyInfo,WbCompanyThirdApi api, String token,Integer pullPageNum) {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
        HttpConnectionParams.setSoTimeout(httpParams, 2000);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        Result<List<WbCompanyDetail>> result = new Result<>();
        try {
            int total=0;
            int pageSize=20;
            int curPage=0;
            List<WbCompanyDetail> retList = new ArrayList<>();
            do {
                curPage++;
                StringBuffer sbUrl = new StringBuffer();
                sbUrl.append(api.getUrl()).append("?pageSize=").append(pageSize)
                        .append("&pageNum=").append(curPage).append("&keyword=").append(wbCompanyInfo.getName());
                HttpGet get = new HttpGet(sbUrl.toString());
                get.setHeader("Authorization", token);
                HttpResponse response = httpClient.execute(get);
                if (response.getStatusLine().getStatusCode() == 200) {
                    String resStr = EntityUtils.toString(response.getEntity(), "utf-8");
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode jsonNode = objectMapper.readTree(resStr);
                    int errCode = jsonNode.get("error_code").asInt();
                    String retMsg = jsonNode.get("reason").asText();
                    if (errCode == 0) {
                        JsonNode jsonResult = jsonNode.get("result");
                        JsonNode jsonItems = jsonResult.get("items");
                        total = jsonResult.get("total").asInt();
                        if (jsonItems != null && jsonItems.size()>0) {
                            List<WbCompanyDetail> list = parseJSONItems(jsonItems, wbCompanyInfo.getId(), api.getApiId());
                            retList.addAll(list);
                        } else {
                            break;
                        }
                    }
                    result.setCode(errCode);
                    result.setMessage(retMsg);

                } else {
                    result.setCode(500);
                    result.setMessage("远程服务器错误");
                }
                if(pullPageNum!=null&&curPage>=pullPageNum){
                    break;
                }
            } while (curPage*pageSize<total);
            result.setResult(retList);
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("服务器异常");
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
            return result;
        }
    }

    public List<WbCompanyDetail> parseJSON(JsonNode jsonResult,int cid,int apiId) {
        try {
            if(jsonResult.isObject()) {
                List<WbCompanyDetail> list = new ArrayList<>();
                jsonResult.fields().forEachRemaining(entry -> {
                    WbCompanyDetail detail = new WbCompanyDetail();
                    JsonNode val =  entry.getValue();
                    detail.setCid(cid);
                    detail.setApiId(apiId);
                    detail.setGrpInd(1);
                    detail.setAttrKey(entry.getKey());
                   if(val.isObject()) {
                        detail.setAttrVal(val.toString());
                    } else if(val.isArray()) {
                        detail.setAttrVal(val.toString());
                    } else if(val.isBoolean()) {
                        detail.setAttrVal(val.asBoolean()?"是":"否");
                    } else {
                        detail.setAttrVal(val.asText());
                    }
                    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
                    list.add(detail);
                });
                QueryWrapper<WbCompanyDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("api_id",apiId).eq("cid",cid);
                this.remove(queryWrapper);
                this.saveBatch(list);
                return list;
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return null;
    }

    public List<WbCompanyDetail>  parseJSONItems(JsonNode jsonItems,int cid,int apiId) {
        try {
            if(jsonItems.isArray()) {
                Integer k=0;
                List<WbCompanyDetail> list = new ArrayList<>();
                for (JsonNode element : jsonItems) {
                    k=k+1;
                    Integer finalK = k;
                    element.fields().forEachRemaining(entry -> {
                        WbCompanyDetail detail = new WbCompanyDetail();
                        JsonNode val =  entry.getValue();
                        detail.setCid(cid);
                        detail.setApiId(apiId);
                        detail.setGrpInd(Integer.valueOf(finalK));
                        detail.setAttrKey(entry.getKey());
                        if (val.isObject()) {
                            detail.setAttrVal(val.toString());
                        } else if (val.isArray()) {
                            detail.setAttrVal(val.toString());
                        } else if (val.isBoolean()) {
                            detail.setAttrVal(val.asBoolean() ? "是" : "否");
                        } else {
                            detail.setAttrVal(val.asText());
                        }
                        list.add(detail);
                    });
                };
//                QueryWrapper<WbCompanyDetail> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("api_id",apiId).eq("cid",cid);
//                this.remove(queryWrapper);
                this.saveBatch(list);
                return list;
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    public void traverseJsonNode(JsonNode node) {
        if (node.isObject()) {
            node.fields().forEachRemaining(entry -> {
                System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
                traverseJsonNode(entry.getValue());
            });
        } else if (node.isArray()) {
            for (JsonNode element : node) {
                traverseJsonNode(element);
            }
        } else {
            System.out.println("Value: " + node);
        }
    }

}
