package com.huigou.topsun.sap.sapApplication.application.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huigou.cache.SystemCache;
import com.huigou.topsun.sap.common.HttpClient;
import com.huigou.topsun.sap.sapApplication.application.SapDictionaryApplication;
import com.huigou.topsun.util.SAPUtils;
import com.huigou.uasp.bmp.common.easysearch.domain.model.EasySearchParse;
import com.huigou.uasp.bmp.common.easysearch.domain.model.QuerySchemeField;
import com.huigou.uasp.bmp.opm.application.MemEasySearcher;
import com.huigou.uasp.bmp.opm.application.impl.MemEasySearcherImpl;
import com.huigou.util.JSONUtil;
import com.huigou.util.SDO;
import com.huigou.util.StringUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther: xin.lu
 * @Date: 2024/01/09/11:24
 * @Description:
 */
@Service
public class SapDictionaryApplicationImpl implements SapDictionaryApplication {
    @Resource
    private HttpClient httpClient;

    @Override
    public List<Map<String,String>> getSapDictionary(String fieldName) throws JsonProcessingException {
        String url = SystemCache.getParameter("sap.service.dictionary.url", String.class);
        Map<String,Object> map = new HashMap<>();
        map.put("FIELDNAME",fieldName);
        String execute = null;
        try {
            execute = httpClient.execute(map, url);
        } catch (IOException e) {
            throw new RuntimeException(String.format("查询“%s“数据字典出错”。", fieldName));
        }
        ObjectMapper objectMapper = SAPUtils.objectMapper();
        List<Map<String,String>> mapList = objectMapper.readValue(execute, new TypeReference<List<Map<String, String>>>() {});
        return mapList;
    }

    @Override
    public List<Map<String, String>> getSapDictionary(String fieldName, String fieldValue) throws IOException {
        Map<String,Object> map = new HashMap<>();
        map.put("FIELDNAME",fieldName);
        map.put("VALUE",fieldValue);
        String url = SystemCache.getParameter("sap.service.dictionary.url", String.class);
        String execute = null;
        try {
            execute = httpClient.execute(map, url);
        } catch (IOException e) {
            throw new RuntimeException(String.format("查询“%s“数据字典出错”。", fieldName));
        }
        ObjectMapper objectMapper = SAPUtils.objectMapper();
        List<Map<String,String>> mapList = objectMapper.readValue(execute, new TypeReference<List<Map<String, String>>>() {});
        return mapList;
    }

    @Override
    public Map<String,Object> initEasySearchModel(List<Map<String, String>> mapList,String param,SDO sdo){
        List<QuerySchemeField> fields = new ArrayList<>();
        Long totalWidths=200L;
        if (CollectionUtil.isNotEmpty(mapList)){
            if (StringUtil.isNotBlank(param)){//输入查询条件过滤
                mapList = mapList
                        .stream()
                        .filter(map -> map.values().stream().anyMatch(value->value.toLowerCase().contains(param.toLowerCase())))
                        .collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(mapList)){
                Map<String, String> map = mapList.get(0);
                String []widths=getWidths(mapList);
                for (int y=0;y<widths.length;y++){
                    totalWidths+=Long.valueOf(widths[y]);
                }

                int x=0;
                for (String key : map.keySet()) {
                    QuerySchemeField querySchemeField = new QuerySchemeField(key,key,"string",Long.valueOf(widths[x]));
                    fields.add(querySchemeField);
                    x++;
                }
              /*  map.keySet().forEach(key->{
                    QuerySchemeField querySchemeField = new QuerySchemeField(key,key,"string",200L);
                    fields.add(querySchemeField);
                });*/
            }
        }
        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize",10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        EasySearchParse easySearchParse = new EasySearchParse();
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(totalWidths);
        MemEasySearcher<Map<String, String>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

    @Override
    public String[] getWidths(List<Map<String, String>>  mapList){
        // 找到 value 值长度最长的 Map
        Map<String, String> map = findLongestMap(mapList);
        String []widths=new String[map.size()];
        int u=0;
        for (String key : map.keySet()) {
            if (widths[u]==null){
                widths[u] = "40";
            }
            String value=(String) map.get(key);
            int length = value.trim().length();
            if (length >= 1){
                widths[u]="100";
            }
            if (length >= 10){
                widths[u]=String.valueOf(length*10);
            }
//            if (length >= 15){
//                widths[u]="150";
//            }
//            if (length >= 20 ) {
//                widths[u]="200";
//            }
//            if (length >= 30 ) {
//                widths[u]="250";
//            }
            u++;
        }
        return widths;
    }

    /**
     * 计算 Map 中所有 value 的总长度
     */
    public int calculateValueLength(Map<String, String> map) {
        int totalLength = 0;
        for (String value : map.values()) {
            totalLength += value.length();
        }
        return totalLength;
    }

   /**
    * 找到 value 值长度最长的 Map
    */
   public Map<String, String> findLongestMap(List<Map<String, String>> mapList) {
       Map<String, String> longestMap = null;
       int maxLength = -1;
       for (Map<String, String> map : mapList) {
           int currentLength = calculateValueLength(map);
           if (currentLength > maxLength) {
               maxLength = currentLength;
               longestMap = map;
           }
       }
       return longestMap;
   }
}
