package com.huigou.topsun.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huigou.cache.DictUtil;
import com.huigou.topsun.ep.epApplication.EpApplication;
import com.huigou.topsun.sap.exceptionReport.application.ExceptionReasonTypeDetailApplication;
import com.huigou.topsun.sap.exceptionReport.domain.ExceptionReasonTypeDetail;
import com.huigou.topsun.sap.exceptionReport.repository.ExceptionReasonTypeDetailRepository;
import com.huigou.topsun.sap.sapApplication.application.*;
import com.huigou.topsun.sap.sapApplication.domain.query.SapDialogOrderQuery;
import com.huigou.topsun.sap.sapApplication.domain.query.SapDialogQuery;

import com.huigou.topsun.sap.suppliers.application.SuppliersDataApplication;
import com.huigou.topsun.util.SAPUtils;
import com.huigou.uasp.annotation.ControllerMapping;
import com.huigou.uasp.bmp.common.easysearch.EasySearch;
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.configuration.application.DictionaryApplication;
import com.huigou.uasp.bmp.opm.application.MemEasySearcher;
import com.huigou.uasp.bmp.opm.application.impl.MemEasySearcherImpl;
import com.huigou.util.ClassHelper;
import com.huigou.util.JSONUtil;
import com.huigou.util.SDO;
import com.huigou.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: xin.lu
 * @Date: 2023/11/24/10:07
 * @Description:
 */
@Controller
@ControllerMapping("/resourceNameGroup")
public class ResourceSearchController {
    @Resource
    private SapDictionaryApplication sapDictionaryApplication;
    @Resource
    private SapPaymentApplication sapPaymentApplication;
    @Autowired
    private SapMaterialApplication sapMaterialApplication;
    @Autowired
    private SapAreaApplication sapAreaApplication;
    @Autowired
    private  DictionaryApplication dictionaryApplication;
    @Autowired
    private SapBankInfoApplication sapBankInfoApplication;
    @Autowired
    private SuppliersDataApplication suppliersDataApplication;
    @Autowired
    private EpApplication epApplication;
    @Autowired
    private ExceptionReasonTypeDetailApplication exceptionReasonTypeDetailApplication;

    @EasySearch(queryName = "knttp")
    public Map<String, Object> knttpSelect(SDO sdo){
        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize",10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        List<QuerySchemeField> fields =
                Arrays.asList(new QuerySchemeField("科目分配类别", "knttp", "string", 100L),
                        new QuerySchemeField("科目分配类别描述", "text", "string", 100L));
        EasySearchParse easySearchParse = new EasySearchParse();
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(450L);
        List<Map<String,Object>> mapList = new ArrayList<>();
        String filterValue = sdo.getString("filterValue");
        Map<String, String> knttp = DictUtil.getDictionary("knttp");
        knttp.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("knttp", value);
            if ("F".equals(key)){
                map.put("text","内部订单");
            }
            if ("K".equals(key)){
                map.put("text","成本中心");
            }
            if ("ZFW".equals(filterValue)) {
                if ("F".equals(key) || "K".equals(key)) {
                    mapList.add(map);
                }
            } else if ("ZNE1".equals(filterValue)) {
                if ("A".equals(key)) {
                    mapList.add(map);
                }
            } else if ("ZNE2".equals(filterValue)) {
                if ("K".equals(key)) {
                    mapList.add(map);
                }
            }
        });
        MemEasySearcher<Map<String, Object>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

    @EasySearch(queryName = "costCenter")
    public Map<String, Object> costCenterSelect(SDO sdo){
        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize",10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        List<QuerySchemeField> fields =
                Arrays.asList(
                        new QuerySchemeField("编码", "code", "string", 100L),
                        new QuerySchemeField("名称", "code", "string", 100L)
                );
        EasySearchParse easySearchParse = new EasySearchParse();
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(450L);
        List<Map<String,Object>> mapList = new ArrayList<>();
        String paramValue = sdo.getString("paramValue");

        MemEasySearcher<Map<String, Object>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

    @EasySearch(queryName = "sapMaterialSelect")
    public Map<String, Object> sapMaterialSelect(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String filterValue = sdo.getString("filterValue");
        String mtart = sdo.getString("mtart");//如果传了刀模板具，就排除掉
        SapDialogQuery queryRequest = sdo.toObject(SapDialogQuery.class);
        queryRequest.setWerks(filterValue);
        List<Map<String,String>> mapList = sapMaterialApplication.getSapMaterial(queryRequest);
//        if (CollectionUtil.isNotEmpty(mapList)){
//            mapList = mapList
//                    .stream()
//                    .map(map->{
//                        String s = map.get("MATNR");
//                        map.put("MATNR",s.replaceAll("^(0+)", ""));
//                        return map;
//                    })
//                    .collect(Collectors.toList());
//        }
        if (CollectionUtil.isNotEmpty(mapList)){
            if (StringUtil.isNotBlank(mtart)){//固定条件过滤，比如选了工厂后，只能读取改工厂下的物料组
                mapList = mapList
                        .stream()
                        .filter(map -> !map.containsValue(mtart))
                        .collect(Collectors.toList());
            }
        }


        if (CollectionUtil.isNotEmpty(mapList)){
            if (StringUtil.isNotBlank(param)){//模糊条件过滤
                mapList = mapList
                        .stream()
                        .filter(map -> map.values().stream().anyMatch(value->value.contains(param)))
                        .collect(Collectors.toList());
            }

            List<Map<String,String>> newMapList=new ArrayList<>();
            if (StringUtil.isNotBlank(sdo.getString("wlfl1"))){//包含物料分类2
                newMapList = mapList
                        .stream()
                        .filter(map -> map.values().stream().anyMatch(value->value.contains(sdo.getString("wlfl1"))))
                        .collect(Collectors.toList());
            }
            List<Map<String,String>> newMapList2=new ArrayList<>();
            if (StringUtil.isNotBlank(sdo.getString("wlfl2"))){//包含物料分类2
                newMapList2 = mapList
                        .stream()
                        .filter(map -> map.values().stream().anyMatch(value->value.contains(sdo.getString("wlfl2"))))
                        .collect(Collectors.toList());
                newMapList.addAll(newMapList2);
            }

            if (StringUtil.isNotBlank(sdo.getString("noWlfl1"))){//排除物料分类1
                newMapList = mapList
                        .stream()
                        .filter(map -> map.values().stream().noneMatch(value->value.contains(sdo.getString("noWlfl1"))))
                        .collect(Collectors.toList());
            }
            if (StringUtil.isNotBlank(sdo.getString("noWlfl2"))){//排除物料分类2
                newMapList = newMapList
                        .stream()
                        .filter(map -> map.values().stream().noneMatch(value->value.contains(sdo.getString("noWlfl2"))))
                        .collect(Collectors.toList());
            }

            if (StringUtil.isNotBlank(sdo.getString("wlfl1"))||
                 StringUtil.isNotBlank(sdo.getString("noWlfl1"))){//排除物料分类1
                mapList=newMapList;
            }


        }

        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize",10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        EasySearchParse easySearchParse = new EasySearchParse();
        List<QuerySchemeField> fields =
                Arrays.asList(
                        new QuerySchemeField("工厂", "WERKS", "string", 60L),
                        new QuerySchemeField("工厂名称", "NAME1", "string", 160L),
                        new QuerySchemeField("物料编码", "MATNR", "string", 140L),
                        new QuerySchemeField("物料名称", "MAKTX", "string", 200L),
                        new QuerySchemeField("物料分类", "MTART", "string", 100L),
                        new QuerySchemeField("物料分类描述", "MTBEZ", "string", 200L),
                        new QuerySchemeField("库存地点", "LGFSB", "string", 100L),
                        new QuerySchemeField("库存地点名称", "LGOBE", "string", 200L),
                        new QuerySchemeField("物料组", "MATKL", "string", 100L),
                        new QuerySchemeField("物料组名称", "WGBEZ", "string", 200L),
                        new QuerySchemeField("基本计量单位", "MEINS", "string", 100L),
                        new QuerySchemeField("基本计量单位名称", "MSEHL", "string", 100L),
                        new QuerySchemeField("采购组", "EKGRP", "string", 100L),
                        new QuerySchemeField("采购组名称", "EKNAM", "string", 200L),
                        new QuerySchemeField("价格基数", "PEINH", "string", 100L)
                );
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(500L);
        MemEasySearcher<Map<String, String>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

    @EasySearch(queryName = "sapMaterialSelect2")
    public Map<String, Object> sapMaterialSelect2(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String filterValue = sdo.getString("filterValue");
        String filterValue2 = sdo.getString("filterValue2");
        SapDialogQuery queryRequest = sdo.toObject(SapDialogQuery.class);
        queryRequest.setWerks(filterValue);
        List<Map<String,String>> mapList = sapMaterialApplication.getSapMaterial(queryRequest);
        queryRequest.setWerks(filterValue2);
        List<Map<String,String>> mapList2 = sapMaterialApplication.getSapMaterial(queryRequest);

        if (CollectionUtil.isNotEmpty(mapList)){
            if (StringUtil.isNotBlank(param)){//模糊条件过滤
                mapList = mapList
                        .stream()
                        .filter(map -> map.values().stream().anyMatch(value->value.contains(param)))
                        .collect(Collectors.toList());
            }
        }
        if (CollectionUtil.isNotEmpty(mapList2)){
            if (StringUtil.isNotBlank(param)){//模糊条件过滤
                mapList2 = mapList2
                        .stream()
                        .filter(map -> map.values().stream().anyMatch(value->value.contains(param)))
                        .collect(Collectors.toList());
            }
        }
        Set<String> matnrSet = mapList.stream().map(map -> {
            return map.get("MATNR");
        }).collect(Collectors.toSet());

        Set<String> matnrSet2 = mapList2.stream().map(map -> {
            return map.get("MATNR");
        }).collect(Collectors.toSet());

        List<String> collect = matnrSet.stream().filter(matnrSet2::contains).collect(Collectors.toList());

        mapList = mapList.stream().filter(map -> collect.contains(map.get("MATNR"))).collect(Collectors.toList());

        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize",10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        EasySearchParse easySearchParse = new EasySearchParse();
        List<QuerySchemeField> fields =
                Arrays.asList(
                        //new QuerySchemeField("工厂", "WERKS", "string", 60L),
                        //new QuerySchemeField("工厂名称", "NAME1", "string", 160L),
                        new QuerySchemeField("物料编码", "MATNR", "string", 140L),
                        new QuerySchemeField("物料名称", "MAKTX", "string", 200L),
                        new QuerySchemeField("物料分类", "MTART", "string", 100L),
                        new QuerySchemeField("物料分类描述", "MTBEZ", "string", 200L),
                        new QuerySchemeField("库存地点", "LGFSB", "string", 100L),
                        new QuerySchemeField("库存地点名称", "LGOBE", "string", 200L),
                        new QuerySchemeField("物料组", "MATKL", "string", 100L),
                        new QuerySchemeField("物料组名称", "WGBEZ", "string", 200L),
                        new QuerySchemeField("基本计量单位", "MEINS", "string", 100L),
                        new QuerySchemeField("基本计量单位名称", "MSEHL", "string", 100L),
                        new QuerySchemeField("采购组", "EKGRP", "string", 100L),
                        new QuerySchemeField("采购组名称", "EKNAM", "string", 200L),
                        new QuerySchemeField("价格基数", "PEINH", "string", 100L)
                );
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(500L);
        MemEasySearcher<Map<String, String>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

    @EasySearch(queryName = "sapProductSelect")
    public Map<String, Object> sapProductSelect(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        SapDialogQuery queryRequest = sdo.toObject(SapDialogQuery.class);
        List<Map<String,String>> mapList = sapMaterialApplication.getSapMaterial(queryRequest);
        if (CollectionUtil.isNotEmpty(mapList)){
            mapList = mapList
                    .stream()
                    .filter(map -> (map.containsValue("ZZCP")
                            || map.containsValue("ZBCP")
                    ))
                    .collect(Collectors.toList());
        }
        if (CollectionUtil.isNotEmpty(mapList)){
            if (StringUtil.isNotBlank(param)){//模糊条件过滤
                mapList = mapList
                        .stream()
                        .filter(map -> map.values().stream().anyMatch(value->value.contains(param)))
                        .collect(Collectors.toList());
            }
        }
        System.out.println("条数：" + mapList.size());
        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize",10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        EasySearchParse easySearchParse = new EasySearchParse();
        List<QuerySchemeField> fields =
                Arrays.asList(
                        new QuerySchemeField("工厂", "WERKS", "string", 60L),
                        new QuerySchemeField("工厂名称", "NAME1", "string", 160L),
                        new QuerySchemeField("物料编码", "MATNR", "string", 140L),
                        new QuerySchemeField("物料名称", "MAKTX", "string", 400L),
                        new QuerySchemeField("计量单位", "MSEHL", "string", 100L),
                        new QuerySchemeField("物料分类描述", "MTBEZ", "string", 60L)
                        //new QuerySchemeField("库存地点", "LGFSB", "string", 100L),
                        //new QuerySchemeField("库存地点名称", "LGOBE", "string", 200L)
                );
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(700L);
        MemEasySearcher<Map<String, String>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

     @EasySearch(queryName = "sapCustomerOrderSelect")
    public Map<String, Object> sapCustomerOrderSelect(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        SapDialogOrderQuery queryRequest = sdo.toObject(SapDialogOrderQuery.class);
        List  <Map<String,String>>mapList = sapMaterialApplication.getSapCustomerOrder(queryRequest);

//        if (CollectionUtil.isNotEmpty(mapList)){
//            if (StringUtil.isNotBlank(param)){//固定条件过滤，
//                mapList = mapList
//                        .stream()
//                        .filter(map -> map.values().stream().anyMatch(value->value.contains(param)))
//                        .collect(Collectors.toList());
//            }
//        }

         Integer intPage = sdo.getInteger("intPage", 1);
         Integer pageSize = sdo.getInteger("pageSize",10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        EasySearchParse easySearchParse = new EasySearchParse();
         List<QuerySchemeField> fields =new ArrayList<>();
//        if ("2".equals(queryRequest.getReasonType())){ //生产异常
//             fields =
//                    Arrays.asList(
//                            new QuerySchemeField("订单号", "VBELN", "string", 150L),
//                           // new QuerySchemeField("订单描述", "KTEXT", "string", 160L),
//                            new QuerySchemeField("物料编码", "MATNR", "string", 160L),
//                            new QuerySchemeField("物料描述", "MAKTX", "string", 160L),
//                            new QuerySchemeField("数量", "PSMNG", "string", 100L),
//                            new QuerySchemeField("单位", "MEINS", "string", 100L)
//                    );
//        } else {
//            fields =
//                    Arrays.asList(
//                            new QuerySchemeField("订单号", "VBELN", "string", 130L),
//                            new QuerySchemeField("客户编号", "KUNNR", "string", 60L),
//                            new QuerySchemeField("客户名称", "NAME1", "string", 150L)
//                    );
//        }
         fields =
                 Arrays.asList(
                         new QuerySchemeField("订单号", "VBELN", "string", 130L),
                         new QuerySchemeField("客户编号", "KUNNR", "string", 60L),
                         new QuerySchemeField("客户名称", "NAME1", "string", 150L)
                 );
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(500L);
        MemEasySearcher<Map<String, String>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

    @EasySearch(queryName = "sapCustomerProduceNo")
    public Map<String, Object> sapCustomerProduceNo(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        SapDialogOrderQuery queryRequest = sdo.toObject(SapDialogOrderQuery.class);
        List  <Map<String,String>>mapList = sapMaterialApplication.getSapCustomerOrder(queryRequest);

        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize",10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        EasySearchParse easySearchParse = new EasySearchParse();
        List<QuerySchemeField> fields =
                Arrays.asList(
                        new QuerySchemeField("生产单号", "AUFNR", "string", 140L),
                        new QuerySchemeField("物料编码", "MATNR", "string", 140L),
                        new QuerySchemeField("物料名称", "MAKTX", "string", 200L),
                        new QuerySchemeField("数量", "PSMNG", "string", 100L),

                        new QuerySchemeField("单位", "MEINS", "string", 100L),
                        new QuerySchemeField("币别", "KOEIN", "string", 100L),
                        new QuerySchemeField("金额", "KWERT", "string", 200L),
                        new QuerySchemeField("出货日期", "LFDAT", "string", 100L)

                );
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(500L);
        MemEasySearcher<Map<String, String>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

    @EasySearch(queryName = "sapCustomerProduceNoByProduceNo")
    public Map<String, Object> sapCustomerProduceNoByProduceNo(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        SapDialogOrderQuery queryRequest = sdo.toObject(SapDialogOrderQuery.class);
        List  <Map<String,String>>mapList = sapMaterialApplication.sapCustomerProduceNoByProduceNo(queryRequest);

        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize",10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        EasySearchParse easySearchParse = new EasySearchParse();
        List<QuerySchemeField> fields =
                Arrays.asList(
                        new QuerySchemeField("客户单号", "BSTNK", "string", 140L),
                        new QuerySchemeField("物料编号", "MATNR", "string", 140L),
                        new QuerySchemeField("物料名称", "MAKTX", "string", 200L),
                        new QuerySchemeField("生产单号", "AUFNR", "string", 200L),
                        new QuerySchemeField("生产数量", "PSMNG", "string", 100L),

                        new QuerySchemeField("单位", "MEINS", "string", 100L),
                        new QuerySchemeField("单位", "NETWR", "string", 100L),
                        new QuerySchemeField("币别", "KOEIN", "string", 100L),
                        new QuerySchemeField("金额", "KWERT", "string", 200L),
                        new QuerySchemeField("出货日期", "LFDAT", "string", 100L)

                );
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(500L);
        MemEasySearcher<Map<String, String>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

    @EasySearch(queryName = "dictionarySelect")
    public Map<String, Object> dictionarySelect(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String filterValue = sdo.getString("filterValue");
        String fieldName = sdo.getString("fieldName");
        String []displayName=sdo.getString("displayNames").split(",");
        String []displayLen=sdo.getString("displayLens").split(",");
      //  SapDialogQuery queryRequest = sdo.toObject(SapDialogQuery.class);
      //  queryRequest.setWerks(filterValue);
        Map maps = dictionaryApplication.querySysDictionaryDetailsByCode(fieldName);
        ObjectMapper objectMapper = SAPUtils.objectMapper();
        List<Map<String,String>> mapList = objectMapper.readValue(JSONUtil.toString(maps.get("Rows")), new TypeReference<List<Map<String, String>>>() {});

        if (CollectionUtil.isNotEmpty(mapList)){
            if (StringUtil.isNotBlank(filterValue)){//固定条件过滤，比如选了工厂后，只能读取改工厂下的物料组
                mapList = mapList
                        .stream()
                        .filter(map -> map.containsValue(filterValue))
                        .collect(Collectors.toList());
            }
        }
        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());
            }
        }
        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize",10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        EasySearchParse easySearchParse = new EasySearchParse();
        List<QuerySchemeField> fields=new ArrayList<>();
          fields.add(new QuerySchemeField(displayName[0], "name", "string", Long.valueOf(displayLen[0])));
        if (displayName.length>1){
            fields.add(new QuerySchemeField(displayName[1], "value", "string", Long.valueOf(displayLen[1])));
        } else {
            fields.add(new QuerySchemeField("", "value", "hidden", 0L));
        }

        Long widths=0L;
       for (int u=0;u<displayLen.length;u++){
           widths+=Long.valueOf(displayLen[u]);
       }
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(widths);
        MemEasySearcher<Map<String, String>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

    @EasySearch(queryName = "dictionary")
    public Map<String, Object> queryDictionary(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String fieldName = sdo.getString("fieldName");
        String filterValue = sdo.getString("filterValue");
        String noContain = sdo.getString("noContain");
        String notNull = sdo.getString("notNull");
        List<Map<String, String>> mapList = new ArrayList<>();
        if ("AUFNR".equals(fieldName)){
            mapList = sapDictionaryApplication.getSapDictionary(fieldName,param);
        }else {
            mapList = sapDictionaryApplication.getSapDictionary(fieldName);
        }
        List<QuerySchemeField> fields = new ArrayList<>();
        Long totalWidths=200L;
        if (CollectionUtil.isNotEmpty(mapList)){
            if (StringUtil.isNotBlank(filterValue)){//固定条件过滤，比如选了工厂后，只能读取改工厂下的物料组
                String[] split = filterValue.split(",");
                for (String s : split) {
                    mapList = mapList
                            .stream()
                            .filter(map -> map.values().stream().anyMatch(value->value.contains(s)))
                            //.filter(map -> map.containsValue(filterValue))
                            .collect(Collectors.toList());
                }
            }
            if (StringUtil.isNotBlank(noContain)){//固定条件过滤，不包含
                String[] split = noContain.split(",");
                for (String s : split) {
                    mapList = mapList
                            .stream()
                            .filter(map -> map.values().stream().noneMatch(value->value.contains(s)))
                            //.filter(map -> map.containsValue(filterValue))
                            .collect(Collectors.toList());
                }
            }
            if (StringUtil.isNotBlank(param)){//输入查询条件过滤
                mapList = mapList
                        .stream()
                        .filter(map -> map.values().stream().anyMatch(value->value.toLowerCase().contains(param.toLowerCase())))
                        .collect(Collectors.toList());
            }
            if (StringUtil.isNotBlank(notNull)){//某个字段的值不为空
                mapList = mapList
                        .stream()
                        .filter(map -> StringUtil.isNotBlank((String)map.get(notNull)))
                        .collect(Collectors.toList());
            }

            if (!CollectionUtils.isEmpty(mapList)){
                Map<String, String> map = mapList.get(0);
                String []widths=sapDictionaryApplication.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++;
                }
            }
        }

        System.out.println("数据条数："+ mapList.size());
        String string = JSONUtil.toString(mapList);
        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;
    }

    @EasySearch(queryName = "getCusAndSuppliers")
    public Map<String, Object> getCusAndSuppliers(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String BUKRS = sdo.getString("BUKRS");
        String ZEP_BPTYPE = sdo.getString("ZEP_BPTYPE");
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList = sapPaymentApplication.getCusAndSuppliers(BUKRS,ZEP_BPTYPE);
        return sapDictionaryApplication.initEasySearchModel( mapList, param, sdo);
    }

    @EasySearch(queryName = "getCusAndBanks")
    public Map<String, Object> getCusAndBanks(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String PARTNER = sdo.getString("PARTNER");
        String ZEP_BPTYPE = sdo.getString("ZEP_BPTYPE");
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList = sapPaymentApplication.getCusAndBanks(PARTNER,ZEP_BPTYPE);
        return sapDictionaryApplication.initEasySearchModel( mapList, param, sdo);
    }

    @EasySearch(queryName = "getCompanyAndBankInfos")
    public Map<String, Object> getCompanyAndBankInfos(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String BUKRS = sdo.getString("BUKRS");
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList = sapPaymentApplication.getCompanyAndBankInfos(BUKRS);
        return sapDictionaryApplication.initEasySearchModel( mapList, param, sdo);
    }

    @EasySearch(queryName = "getCompanyOrders")
    public Map<String, Object> getCompanyOrders(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String BUKRS = sdo.getString("BUKRS");
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList = sapPaymentApplication.getCompanyOrders(BUKRS);
        return sapDictionaryApplication.initEasySearchModel( mapList, param, sdo);
    }

    @EasySearch(queryName = "getPurchaseOrders")
    public Map<String, Object> getPurchaseOrders(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String BUKRS = sdo.getString("BUKRS");
        String PARTNER = sdo.getString("PARTNER");
        String ZEP_FTYPE = sdo.getString("ZEP_FTYPE");
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList = sapPaymentApplication.getPurchaseOrders(BUKRS,PARTNER,ZEP_FTYPE);
        return sapDictionaryApplication.initEasySearchModel( mapList, param, sdo);
    }

    @EasySearch(queryName = "getPartnerInvs")
    public Map<String, Object> getPartnerInvs(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String BUKRS = sdo.getString("BUKRS");
        String PARTNER = sdo.getString("PARTNER");
        String ZEP_FTYPE = sdo.getString("ZEP_FTYPE");
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList = sapPaymentApplication.getPartnerInvs(BUKRS,PARTNER,ZEP_FTYPE);
        return sapDictionaryApplication.initEasySearchModel( mapList, param, sdo);
    }

    @EasySearch(queryName = "getArea")
    public Map<String, Object> getArea(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String LAND1 = sdo.getString("LAND1");
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList = sapAreaApplication.getAreas(LAND1);
        return sapDictionaryApplication.initEasySearchModel( mapList, param, sdo);
    }

    @EasySearch(queryName = "getBankInfo")
    public Map<String, Object> getBankInfo(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String BANKS = sdo.getString("BANKS");
        String noContain = sdo.getString("noContain");
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList = sapBankInfoApplication.getBankInfo(BANKS);
        if (StringUtil.isNotBlank(noContain)){//固定条件过滤，不包含
            String[] split = noContain.split(",");
            for (String s : split) {
                mapList = mapList
                        .stream()
                        .filter(map -> map.values().stream().noneMatch(value->value.contains(s)))
                        .collect(Collectors.toList());
            }
        }
        return sapDictionaryApplication.initEasySearchModel( mapList, param, sdo);
    }

    @EasySearch(queryName = "selectSuppliersDatas")
    public Map<String, Object> getSuppliersDatas(SDO sdo) {
        String param = sdo.getString("paramValue");
        String PARTNER = sdo.getString("PARTNER");
      //  String ZEP_BPTYPE = sdo.getString("ZEP_BPTYPE");
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList = suppliersDataApplication.selectSuppliersDatas(PARTNER);
        return sapDictionaryApplication.initEasySearchModel( mapList, param, sdo);
    }

    @EasySearch(queryName = "selectEpProcess")
    public Map<String, Object> selectEpProcess(SDO sdo) {
        String param = sdo.getString("paramValue");
        String itemCode = sdo.getString("itemCode");
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList = epApplication.queryEpProductProcess(itemCode);
        return sapDictionaryApplication.initEasySearchModel( mapList, param, sdo);
    }

    @EasySearch(queryName = "selectEpBrandByItemCode")
    public Map<String, Object> selectEpBrandByItemCode(SDO sdo) {
        String param = sdo.getString("paramValue");
        String itemCode = sdo.getString("itemCode");
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList = epApplication.queryEpBrandByItemCode(itemCode);
        return sapDictionaryApplication.initEasySearchModel( mapList, param, sdo);
    }

    /**
     * 物料组字典选择
     * @param sdo
     * @return
     * @throws IOException
     */
    @EasySearch(queryName = "matklDictionary")
    public Map<String, Object> queryMatklDictionary(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String fieldName = sdo.getString("fieldName");
        String filterValue = sdo.getString("filterValue");
        List<Map<String, String>> mapList = new ArrayList<>();
        List<Map<String, String>> resultMapList = new ArrayList<>();
        mapList = sapDictionaryApplication.getSapDictionary("MATKL");
        List<QuerySchemeField> fields = new ArrayList<>();
        Long totalWidths=200L;
        if (CollectionUtil.isNotEmpty(mapList)){
            //只返回分类
            if ("MATKLTYPE".equals(fieldName)){
                resultMapList = mapList
                        .stream()
                        .filter(
                                map -> map.containsKey("MATKL") && map.get("MATKL").length() == 3
                        ).collect(Collectors.toList());
                resultMapList = resultMapList
                        .stream()
                        .filter(map -> map.values().stream().anyMatch(value->value.contains(filterValue)))
                        .collect(Collectors.toList());
            }else {
                //原材料  1/2/3开头，去掉二级分类（三位数）
                if (StringUtil.isNotBlank(filterValue)){//固定条件过滤,前3位为大类编码
                    resultMapList = mapList
                            .stream()
                            .filter(
                                    map -> map.containsKey("MATKL") && map.get("MATKL").startsWith(filterValue) && map.get("MATKL").length() > 3
                            )
                            .collect(Collectors.toList());
                    //不包含子类时，返回大类
                    if (CollectionUtil.isEmpty(resultMapList)){
                        resultMapList = mapList
                                .stream()
                                .filter(
                                        map -> map.containsKey("MATKL") && map.get("MATKL").equals(filterValue) && map.get("MATKL").length() == 3
                                )
                                .collect(Collectors.toList());
                    }

                }
            }

            if (StringUtil.isNotBlank(param)){//输入查询条件过滤
                resultMapList = resultMapList
                        .stream()
                        .filter(map -> map.values().stream().anyMatch(value->value.toLowerCase().contains(param.toLowerCase())))
                        .collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(resultMapList)){
                Map<String, String> map = resultMapList.get(0);
                String []widths=sapDictionaryApplication.getWidths(resultMapList);
                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++;
                }
            }
        }

        System.out.println("数据条数："+ mapList.size());
        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(resultMapList, easySearchParse, pageRequest, null);
        return model;
    }

    /**
     * 查询异常分类明细
     * @param sdo
     * @return
     */
    @EasySearch(queryName = "selectExceptionReasonTypeDetail")
    public Map<String, Object> selectExceptionReasonTypeDetail(SDO sdo) {
        String param = sdo.getString("paramValue");
        List<Map<String, String>> mapList = new ArrayList<>();
        List<Map<String, Object>> maps = exceptionReasonTypeDetailApplication.getReasonTypeDetailListMap(param);
        String result = JSONUtil.toString(maps);
        ObjectMapper objectMapper = SAPUtils.objectMapper();
        try {
            mapList = objectMapper.readValue(result, new TypeReference<List<Map<String, String>>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize",10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        EasySearchParse easySearchParse = new EasySearchParse();
        List<QuerySchemeField> fields =
                Arrays.asList(
                        new QuerySchemeField("标准名称大类", "reasonTypeName", "string", 100L),
                        new QuerySchemeField("问题类型代码", "reasonTypeDetail", "string", 100L),
                        new QuerySchemeField("问题类型", "reasonTypeDetailName", "string", 200L),
                        new QuerySchemeField("序号（一级分类编码）", "reasonType", "hidden")
                );
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(500L);
        MemEasySearcher<Map<String, String>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

    /**
     * 根据工厂、供应商编码查询货币码
     * @param sdo
     * @return
     */
    @EasySearch(queryName = "selectSupplierWaers")
    public Map<String, Object> selectSupplierWaers(SDO sdo) {
        String param = sdo.getString("partner");
        //String werks = sdo.getString("werks");
        List<Map<String, String>> mapList = new ArrayList<>();
        List<Map<String, Object>> maps = suppliersDataApplication.selectSupplierWaers(param);
        String result = JSONUtil.toString(maps);
        ObjectMapper objectMapper = SAPUtils.objectMapper();
        try {
            mapList = objectMapper.readValue(result, new TypeReference<List<Map<String, String>>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
//        if (StringUtil.isNotBlank(werks)){
//            mapList = mapList
//                   .stream()
//                   .filter(map -> (map.get("werks").equals(werks) || StringUtil.isBlank(map.get("werks"))))
//                   .collect(Collectors.toList());
//        }
        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize",10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        EasySearchParse easySearchParse = new EasySearchParse();
        List<QuerySchemeField> fields =
                Arrays.asList(
                        //new QuerySchemeField("工厂", "werks", "string", 100L),
                        new QuerySchemeField("供应商子范围", "ltsnr", "string", 150L),
                        new QuerySchemeField("供应商子范围描述", "ltsbz", "string", 150L),
                        new QuerySchemeField("货币码", "waers", "string", 100L),
                        new QuerySchemeField("货币码描述", "waersName","string", 100L)
                );
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(500L);
        MemEasySearcher<Map<String, String>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

    @EasySearch(queryName = "selectAufnr")
    public Map<String, Object> selectAufnr(SDO sdo) throws IOException {
        String param = sdo.getString("paramValue");
        String fieldName = sdo.getString("fieldName");
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList = sapDictionaryApplication.getSapDictionary(fieldName, param);
        if (CollectionUtil.isNotEmpty(mapList)) {
            // 创建一个映射，方便根据 VORNR 快速查找对象
            Map<String, Map<String, String>> vornrMap = new HashMap<>();
            for (Map<String, String> item : mapList) {
                vornrMap.put(item.get("VORNR"), item);
            }

            // 遍历数组，为每个对象添加 nextVornr 字段
            for (Map<String, String> item : mapList) {
                int currentVornr = Integer.parseInt(item.get("VORNR"));
                int nextVornr = currentVornr + 10;
                String nextVornrKey = String.format("%04d", nextVornr); // 补零到 4 位

                // 查找下一个工序的 LTXA1 值
                if (vornrMap.containsKey(nextVornrKey)) {
                    item.put("NEXTVORNR", vornrMap.get(nextVornrKey).get("LTXA1"));
                } else {
                    item.put("NEXTVORNR", null); // 如果没有下一个工序，设置为 null
                }
            }
        }
        System.out.println("数据条数：" + mapList.size());
        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize", 10);
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        EasySearchParse easySearchParse = new EasySearchParse();
        List<QuerySchemeField> fields =
                Arrays.asList(
                        new QuerySchemeField("工序号", "VORNR", "string", 50L),
                        new QuerySchemeField("工序描述", "LTXA1", "string", 100L),
                        new QuerySchemeField("下道工序描述", "NEXTVORNR", "string", 100L),
                        new QuerySchemeField("单位描述", "MSEHL", "hidden")
                );
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(500L);
        MemEasySearcher<Map<String, String>> memEasySearcher = new MemEasySearcherImpl<>();
        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
        return model;
    }

}
