package com.org.hktshop.service.portal.product;

import com.org.hktshop.Interface.global.IHktLanguageService;
import com.org.hktshop.Interface.portal.product.IPortalProductService;
import com.org.hktshop.Interface.product.*;
import com.org.hktshop.Interface.system.HktFavoritesService;
import com.org.hktshop.base.BaseService;
import com.org.hktshop.base.MongoHelper;
import com.org.hktshop.constant.CommonConstant;
import com.org.hktshop.entity.Page;
import com.org.hktshop.entity.global.HktLanguage;
import com.org.hktshop.entity.hotking.HktBrandGoodsAttrQueryItem;
import com.org.hktshop.entity.product.*;
import com.org.hktshop.utils.GoodsUtils;
import com.org.hktshop.utils.IKAnalyzerUtil;
import com.org.hktshop.utils.IpUtils;
import com.org.hktshop.utils.StringUtils;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author owen
 */
@Service
public class PortalProductServiceImpl extends BaseService<HktGoodsCategory> implements IPortalProductService {
    private static Logger logger = LoggerFactory.getLogger(PortalProductServiceImpl.class);
    @Autowired
    private MongoHelper<HktGoodsCategory> mongoHelper;

    @Autowired
    private IHktGoodsService hktGoodsService;

    @Autowired
    IHktLanguageService languageService;

    @Autowired
    private IHktGoodsAttrService hktGoodsAttrService;

    @Autowired
    private IHktGoodsCategoryService hktGoodsCategoryService;

    @Autowired
    private HktFavoritesService hktFavoritesService;

    @Autowired
    private IHktPriceRegulationService hktPriceRegulationService;

    @Autowired
    private GoodsUtils goodsUtils;

    @Autowired
    private IHktSearchReplacementService hktSearchReplacementService;

    private MongoHelper<HktGoodItem> hktGoodsPageItemMongoHelper = new MongoHelper<>();

    private MongoHelper<HktGoodsSeoDesc> hktGoodsSeoDescMongoHelper = new MongoHelper<>();

    @Override
    public List<HktGoodsCategory> queryList() {
        HktGoodsCategory hktGoodsCategory = new HktGoodsCategory();
        return mongoHelper.find(hktGoodsCategory, HktGoodsCategory.class);
    }


    @Override
    public HktGoodItem findProduct(HktGoodItem hktGoods) {

        HktGoodItem hktGoodItem;
        HktLanguage language = new HktLanguage();
        language.setId(hktGoods.getLanguage());
        HktLanguage flanguage = languageService.queryLanguage(language);
        hktGoodItem = hktGoodsPageItemMongoHelper.findOne(hktGoods, CommonConstant.HKT_Goods_Cache_KeyHead + flanguage.getAbbreviate(), HktGoodItem.class);
        if (hktGoodItem == null) {
            return null;
        }
        hktPriceRegulationService.callPriceRegulation(hktGoodItem);

        String[] arr = {hktGoodItem.getIndustryId(), hktGoodItem.getTechnologyId()};
        List<HktGoodsSeoDesc> list = hktGoodsSeoDescMongoHelper.findIn("id", arr, HktGoodsSeoDesc.class);

        String remark = hktGoodItem.getBrandName() + " " + hktGoodItem.getName();

        for (HktGoodsSeoDesc hg : list) {
            String id = hg.getId();
            if (id.equals(hktGoodItem.getIndustryId())) {
                hktGoodItem.setIndustryId(hg.getName());
                remark += " " + hg.getName();
                continue;
            }
            if (id.equals(hktGoodItem.getTechnologyId())) {
                hktGoodItem.setTechnologyId(hg.getName());
                remark += " " + hg.getName();
            }
        }

        String categoryId = hktGoodItem.getCategoryId();
        HktGoodsCategory hktGoodsCategory = new HktGoodsCategory();
        hktGoodsCategory.setId(categoryId);
        HktGoodsCategory hktGoodsCategory1 = hktGoodsCategoryService.queryCategory(hktGoodsCategory);
        HktGoodsCategory hktGoodsCategory2 = new HktGoodsCategory();
        hktGoodsCategory2.setId(hktGoodsCategory1.getParentId());
        HktGoodsCategory hktGoodsCategory3 = hktGoodsCategoryService.queryCategory(hktGoodsCategory2);
        hktGoodItem.setParentCategoryId(hktGoodsCategory3.getId());
        switch (hktGoods.getLanguage()) {
            case "1":
                hktGoodItem.setParentCategoryName(hktGoodsCategory3.getNameCh());
                break;
            default:
                hktGoodItem.setParentCategoryName(hktGoodsCategory3.getNameEn());
                break;
        }

        hktGoodItem.setName(hktGoodItem.getCategoryName() + " " + hktGoodItem.getName());

        hktGoodItem.setGoodRemark(remark);
//        hktGoodItem.setRemarkId(remark);

        hktGoodItem.setQueryValue(null);
        hktGoodItem.setCreateTime(null);
        hktGoodItem.setModifyTime(null);
        Set<String> ids = hktFavoritesService.getIdGoodsByUser();
        if(ids.contains(hktGoodItem.getId())){
            hktGoodItem.setCollect(1);
        }
        return hktGoodItem;
    }

    @Override
    public Page<HktGoodItem> selectProductLike(HktGoodItem hktGoods) {
        boolean flag = false;
        List<Criteria> criteriaList = new ArrayList<>();
        Criteria criatira = new Criteria();
        //根据类分页查
        String categoryId = hktGoods.getCategoryId();
        HktGoodsCategory categoryTail = null;

        if (!StringUtils.isNull(categoryId)) {
            HktGoodsCategory category = new HktGoodsCategory();
            category.setId(categoryId);
            categoryTail = hktGoodsCategoryService.queryCategory(category);
            if (categoryTail != null && categoryTail.getLevel() == 1) {
                flag = true;
                categoryTail.setLanguage(hktGoods.getLanguage());
                Criteria[] criteriaAttrs = getCriteriaAttrs2(hktGoods);
                for(Criteria cr : criteriaAttrs){
                    criteriaList.add(cr);
                }
            } else {
                Criteria[] criteriaAttrs = getCriteriaAttrs1(hktGoods);
                for(Criteria cr : criteriaAttrs){
                    criteriaList.add(cr);
                }
            }
        } else if (!StringUtils.isNull(hktGoods.getCategoryName())) {
            criteriaList.add(Criteria.where("categoryName").is(hktGoods.getCategoryName()));
        }

        if (!StringUtils.isNull(hktGoods.getParentCategoryId()))
            criteriaList.add(Criteria.where("parentCategoryId").is(hktGoods.getParentCategoryId()));

        if(IpUtils.getAddress() == 2){
            criteriaList.add(Criteria.where("hktType").is(1));
        }else {
            criteriaList.add(Criteria.where("hjType").is(1));
        }

        String brandId = hktGoods.getBrandId();
        if (!StringUtils.isNull(brandId)) {
            criteriaList.add(Criteria.where("brandId").is(brandId));
        } else if (!StringUtils.isNull(hktGoods.getBrandName())) {
            criteriaList.add(Criteria.where("brandName").is(hktGoods.getBrandName()));
        }

        if (!StringUtils.isNull(hktGoods.getStoreCount())) {
            criteriaList.add(Criteria.where("storeCount").gt(hktGoods.getStoreCount()));
        }

        if (!StringUtils.isNull(hktGoods.getSpecParam())) {
            String[] stringList = hktGoods.getSpecParam().split(" ");
            Criteria[] criteria = new Criteria[stringList.length];
            for (int i = 0; i < stringList.length; i++) {
                criteria[i] = Criteria.where("specParam").regex(stringList[i]);
                criteriaList.add(criteria[i]);
            }

        }

        //0 普通 1 特价 2 热销 3 采购专区
        Integer goodsType = hktGoods.getGoodsType();
        if (!StringUtils.isNull(goodsType)) {
            criteriaList.add(Criteria.where("goodsType").is(goodsType));
        }
        String queryValue = hktGoods.getQueryValue();
        if (!StringUtils.isNull(queryValue) && StringUtils.isNull(hktGoods.getType())) {
//            List<String> stringList = IKAnalyzerUtil.IKAnalysis(queryValue);
           List<String> stringList = Arrays.asList(queryValue.toUpperCase().split(" "));
            Criteria[] criteria = new Criteria[stringList.size()];
            for (int i = 0; i < stringList.size(); i++) {
                if(StringUtils.isNull(stringList.get(i))){
                    continue;
                }
                String replaceForMatching = hktSearchReplacementService.findReplaceForMatching(stringList.get(i)).trim();
                if(replaceForMatching.contains("Ω")){
                    criteria[i] = Criteria.where("attrs.attrId").is("阻值").and("attrs.attrValue").is(replaceForMatching);
                }else if(replaceForMatching.endsWith("W") && replaceForMatching.length() < 6){
                    criteria[i] = Criteria.where("attrs.attrId").is("功率").and("attrs.attrValue").is(replaceForMatching);
                }else {
                    criteria[i] = Criteria.where("queryValue").regex(replaceForMatching,"i");
                }

                criteriaList.add(criteria[i]);
            }
            if(hktGoods.getAttrs() != null && hktGoods.getAttrs().size() > 0){
                List<HktGoodsAttrItem> attrs = hktGoods.getAttrs();
                for(HktGoodsAttrItem ha : attrs){
                    String[] split = ha.getAttrValue().split(",");
                    Criteria in = Criteria.where("attrs.attrId").is(ha.getAttrId()).and("attrs.attrValue").in(split);
                    criteriaList.add(in);
                }
            }
        }

        Criteria[] criterialist = new Criteria[criteriaList.size()];
        for(int i=0;i<criteriaList.size();i++){
            criterialist[i] =criteriaList.get(i);
        }
        if(criterialist.length > 0){
            criatira.andOperator(criterialist);
        }
        Query query = new Query(criatira);
        query.with(new Sort(Sort.Direction.DESC, "goodsType"));
        query.with(new Sort(Sort.Direction.ASC, "brandId"));
        //1:升序  2:降序
        if ("2".equals(hktGoods.getSort())) {
            query.with(new Sort(Sort.Direction.DESC, "price"));
        } else {
            query.with(new Sort(Sort.Direction.ASC, "price"));
        }
        query.with(new Sort(Sort.Direction.DESC, "score"));
        String collectionName = goodsUtils.getCollectionName(hktGoods.getLanguage());
        Page<HktGoodItem> hktGoodsItem = hktGoodsPageItemMongoHelper.findPage(hktGoods, query, HktGoodItem.class, collectionName);

        Map<String, Object> objectMap = new HashMap<>();
        if (!StringUtils.isNull(hktGoods.getQueryValue())) {
            // //模糊搜索
            setProjectMap(objectMap, criatira, collectionName);
            hktGoodsItem.setObject(objectMap);
        } else {
            if (!StringUtils.isNull(hktGoods.getType()) && hktGoods.getType() == 1) {
                setProjectMap(objectMap, criatira, collectionName);
            } else {
                if(IpUtils.getAddress() == 2){
                    Object stringListMap = mongoHelper.distinctSearch(criatira, collectionName);
                    objectMap.put("QueryItems", stringListMap);
                }else {
                    if(!StringUtils.isNull(hktGoods.getBrandId()) && !StringUtils.isNull(hktGoods.getCategoryId())){
                        HktGoodItem hktGoodItem = new HktGoodItem();
                        hktGoodItem.setCategoryId(hktGoods.getCategoryId());
                        hktGoodItem.setLanguage(hktGoods.getLanguage());
                        hktGoodItem.setBrandId(hktGoods.getBrandId());
                        Object hktBrandCategoryAttrQueryItems = hktGoodsAttrService.queryBrandSelectCache(hktGoodItem);
                        objectMap.put("QueryItems", hktBrandCategoryAttrQueryItems);
                    }else {
                        HktGoodsCategory category = new HktGoodsCategory();
                        category.setId(hktGoods.getCategoryId());
                        category.setLanguage(hktGoods.getLanguage());
                        Object hktGoodsAttrQueryItems = hktGoodsAttrService.querySelectCache(category);
                        objectMap.put("QueryItems", hktGoodsAttrQueryItems);
                    }
                }
                if (flag) {
                    List<Map<String, Object>> list = new ArrayList<>();
                    HktGoodsCategory category1 = new HktGoodsCategory();
                    category1.setParentId(hktGoods.getCategoryId());
                    List<HktGoodsCategory> hktGoodsCategories = hktGoodsCategoryService.queryLists(category1);
                    for (HktGoodsCategory hktGoodsCategory : hktGoodsCategories) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", hktGoodsCategory.getId());
                        map.put("name", hktGoodsCategory.getNameCh());
                        map.put("hot",hktGoodsCategory.getIsHot());
                        list.add(map);
                    }
                    objectMap.put("categoryItem", list);
                }
            }
            hktGoodsItem.setObject(objectMap);
        }



        return getPage(hktGoodsItem, categoryTail,queryValue);
    }

    @Override
    public Page<HktGoodsSeoDesc> selectTitle(HktGoodsSeoDesc hktGoodsSeoDesc) {
        Criteria criteria = new Criteria();
        Criteria a = Criteria.where("useType").is(6);
        Criteria b = Criteria.where("languageId").is(hktGoodsSeoDesc.getLanguage());
        criteria.andOperator(a, b);
        Query query = new Query(criteria);
        query.with(new Sort(Sort.Direction.ASC, "sort"));
        return hktGoodsSeoDescMongoHelper.findPage(hktGoodsSeoDesc, query, HktGoodsSeoDesc.class);
    }

    @Override
    public Map<String, Object> statisticsCountProduct(Map map) {
        Criteria criteria;
        int address = IpUtils.getAddress();
        if(address == 1){
            criteria = Criteria.where("hjType").is(1);
        }else{
            criteria = Criteria.where("hktType").is(1);
        }
        String collectionName = goodsUtils.getCollectionName(map.get("language") + "");
        Query query = new Query(criteria);
        long count = hktGoodsPageItemMongoHelper.count(query, HktGoodItem.class, collectionName);
        Map<String, Object> objectMap = new HashMap<>();
        objectMap.put("count", count);
        return objectMap;
    }

    @Override
    public Page<Map<String, Object>> resembleProduct(HktGoodItem hktGoodItem) {
        String collectionName = goodsUtils.getCollectionName(hktGoodItem.getLanguage());
        Criteria criteria = new Criteria();
        Criteria a = Criteria.where("categoryId").is(hktGoodItem.getCategoryId());
        Criteria b = Criteria.where("_id").ne(hktGoodItem.getId());
        criteria.andOperator(a, b);
        String[] stringList = hktGoodItem.getSpecParam().split("|");
        Criteria[] criteria1 = new Criteria[stringList.length];
        for (int i = 0; i < stringList.length; i++) {
            criteria1[i] = Criteria.where("queryValue").regex(stringList[i]);
        }
        criteria.orOperator(criteria1);
        Query query = new Query(criteria);
        return getListForMap(hktGoodItem, query, collectionName, 1);
    }

    @Override
    public Page<Map<String, Object>> otherProduct(HktGoodItem hktGoodItem) {
        String collectionName = goodsUtils.getCollectionName(hktGoodItem.getLanguage());
        Criteria criteria = new Criteria();
        Criteria a = Criteria.where("categoryId").is(hktGoodItem.getCategoryId());
        criteria.andOperator(a);
        Query query = new Query(criteria);
        query.with(new Sort(Sort.Direction.DESC, "salesSum"));
        return getListForMap(hktGoodItem, query, collectionName, 0);
    }

    @Override
    public List<Map<String, Object>> prodectCategory(HktGoodItem hktGoodItem) {
        Criteria criteria = Criteria.where("brandId").is(hktGoodItem.getBrandId());
        String collectionName = goodsUtils.getCollectionName(hktGoodItem.getLanguage());
        Page<HktGoodItem> page = new Page<>();
        page.setPageSize(hktGoodItem.getPageSize());
        page.setCurrent(hktGoodItem.getPageNum());
        List<Map<String, Object>> map = new ArrayList<>();
        setProjectMap2(map, criteria, collectionName);
        return map;
    }

    @Override
    public Page<HktGoodItem> prodectGuesgsYouLike(HktGoodItem hktGoodItem) {
        String collectionName = goodsUtils.getCollectionName(hktGoodItem.getLanguage());
        String[] categoryIds = hktGoodItem.getCategoryId().split(",");
        Criteria criteria = new Criteria();
        Criteria a = Criteria.where("categoryId").in(categoryIds);
        String[] ids = hktGoodItem.getId().split(",");
        Criteria b = Criteria.where("id").nin(ids);
        criteria.andOperator(a, b);
        Query query = new Query(criteria);
        Page<HktGoodItem> pages = hktGoodsPageItemMongoHelper.findPage(hktGoodItem, query, HktGoodItem.class, collectionName);
        if (pages.getRecords().size() > 0) {
            hktPriceRegulationService.callPriceRegulation(pages.getRecords());
        }
        return pages;
    }

    @Override
    public Object screen(HktGoodItem hktGoods) {
        List<Criteria> criteriaList = new ArrayList<>();
        Criteria criatira = new Criteria();
        //根据类分页查
        String categoryId = hktGoods.getCategoryId();
        HktGoodsCategory categoryTail = null;

        if (!StringUtils.isNull(categoryId)) {
            HktGoodsCategory category = new HktGoodsCategory();
            category.setId(categoryId);
            categoryTail = hktGoodsCategoryService.queryCategory(category);
            if (categoryTail != null && categoryTail.getLevel() == 1) {
                categoryTail.setLanguage(hktGoods.getLanguage());
                Criteria[] criteriaAttrs = getCriteriaAttrs2(hktGoods);
                for(Criteria cr : criteriaAttrs){
                    criteriaList.add(cr);
                }
            } else {
                Criteria[] criteriaAttrs = getCriteriaAttrs1(hktGoods);
                for(Criteria cr : criteriaAttrs){
                    criteriaList.add(cr);
                }
            }
        } else if (!StringUtils.isNull(hktGoods.getCategoryName())) {
            criteriaList.add(Criteria.where("categoryName").is(hktGoods.getCategoryName()));
        }

        if(!StringUtils.isNull(hktGoods.getQueryValue())){
            Criteria[] criteriaAttrs3 = getCriteriaAttrs3(hktGoods);
            for(Criteria cr : criteriaAttrs3){
                criteriaList.add(cr);
            }
        }

        if (!StringUtils.isNull(hktGoods.getParentCategoryId()))
            criteriaList.add(Criteria.where("parentCategoryId").is(hktGoods.getParentCategoryId()));

        if(IpUtils.getAddress() == 2){
            criteriaList.add(Criteria.where("hktType").is(1));
        }else {
            criteriaList.add(Criteria.where("hjType").is(1));
        }

        String brandId = hktGoods.getBrandId();
        if (!StringUtils.isNull(brandId)) {
            criteriaList.add(Criteria.where("brandId").is(brandId));
        } else if (!StringUtils.isNull(hktGoods.getBrandName())) {
            criteriaList.add(Criteria.where("brandName").is(hktGoods.getBrandName()));
        }

        if (!StringUtils.isNull(hktGoods.getStoreCount())) {
            criteriaList.add(Criteria.where("storeCount").gt(hktGoods.getStoreCount()));
        }

        if (!StringUtils.isNull(hktGoods.getSpecParam())) {
            String[] stringList = hktGoods.getSpecParam().split(" ");
            Criteria[] criteria = new Criteria[stringList.length];
            for (int i = 0; i < stringList.length; i++) {
                criteria[i] = Criteria.where("specParam").regex(stringList[i]);
                criteriaList.add(criteria[i]);
            }

        }

        //0 普通 1 特价 2 热销 3 采购专区
        Integer goodsType = hktGoods.getGoodsType();
        if (!StringUtils.isNull(goodsType)) {
            criteriaList.add(Criteria.where("goodsType").is(goodsType));
        }

        String queryValue = hktGoods.getQueryValue();
        if (!StringUtils.isNull(queryValue) && StringUtils.isNull(hktGoods.getType())) {
//            List<String> stringList = IKAnalyzerUtil.IKAnalysis(queryValue);
            List<String> stringList = Arrays.asList(queryValue.toUpperCase().split(" "));
            Criteria[] criteria = new Criteria[stringList.size()];
            for (int i = 0; i < stringList.size(); i++) {
                if(StringUtils.isNull(stringList.get(i))){
                    continue;
                }
                String replaceForMatching = hktSearchReplacementService.findReplaceForMatching(stringList.get(i)).trim();
                criteria[i] = Criteria.where("queryValue").regex(replaceForMatching,"i");
                criteriaList.add(criteria[i]);
            }
        }
        Criteria[] criterialist = new Criteria[criteriaList.size()];
        for(int i=0;i<criteriaList.size();i++){
            criterialist[i] =criteriaList.get(i);
        }
        if(criterialist.length > 0){
            criatira.andOperator(criterialist);
        }
        String collectionName = goodsUtils.getCollectionName(hktGoods.getLanguage());
        Map<String, Object> objectMap = new HashMap<>();
        Object stringListMap = mongoHelper.distinctSearch(criatira, collectionName);
        objectMap.put("QueryItems", stringListMap);
        return objectMap;
    }

    @Override
    public List<HktGoodItem> selectProductListByBrandId(HktGoodItem hktGoodItem) {
        String collectionName = goodsUtils.getCollectionName(hktGoodItem.getLanguage());
        Criteria criteria = Criteria.where("brandId").is(hktGoodItem.getBrandId());
        Query query = new Query(criteria);
        return hktGoodsPageItemMongoHelper.find(query, HktGoodItem.class, collectionName);
    }

    @Override
    public Object filterList(HktGoodItem hktGoodItem) {
        List<Criteria> criteriaList = new ArrayList<>();
        Criteria criatira = new Criteria();
        HktGoodsCategory category = new HktGoodsCategory();
        category.setId(hktGoodItem.getCategoryId());
        category.setLanguage("1");
        if(StringUtils.isNull(hktGoodItem.getBrandId())){
            List<Map<String, Object>> mapList = hktGoodsAttrService.querySelectCache(category);
            if(StringUtils.isNull(hktGoodItem.getAttrs())){
                return mapList;
            }

            if (!StringUtils.isNull(hktGoodItem)) {
                HktGoodsCategory category1 = new HktGoodsCategory();
                category1.setId(hktGoodItem.getCategoryId());
                HktGoodsCategory categoryTail = hktGoodsCategoryService.queryCategory(category1);
                if (categoryTail != null && categoryTail.getLevel() == 1) {
                    categoryTail.setLanguage("1");
                    Criteria[] criteriaAttrs = getCriteriaAttrs2(hktGoodItem);
                    for(Criteria cr : criteriaAttrs){
                        criteriaList.add(cr);
                    }
                } else {
                    Criteria[] criteriaAttrs = getCriteriaAttrs1(hktGoodItem);
                    for(Criteria cr : criteriaAttrs){
                        criteriaList.add(cr);
                    }
                }
            }
            Criteria[] criterialist = new Criteria[criteriaList.size()];
            for(int i=0;i<criteriaList.size();i++){
                criterialist[i] =criteriaList.get(i);
            }
            if(criterialist.length > 0){
                criatira.andOperator(criterialist);
            }
            String collectionName = goodsUtils.getCollectionName("1");
            Set<String> set = new HashSet<>();
            if(hktGoodItem.getAttrs().size() > 0 ){
                set = hktGoodsPageItemMongoHelper.distinctSearch1(criatira, collectionName);
            }
            List<Map<String, Object>> ls = new ArrayList<>();
            for(Map<String, Object> m : mapList){
                Map<String,Object> map1 = new HashMap<>();
                List<String> attrs = (List<String>) m.get("attrs");
                List<Object> objectList = new ArrayList<>();
                for(String str : attrs){
                    Map<String,Object> map = new HashMap<>();
                    map.put("values",str);
                    if(hktGoodItem.getAttrs().size() > 0 && !set.contains(str)){
                        map.put("type",0);
                    }else {
                        map.put("type",1);
                    }
                    objectList.add(map);
                }
                map1.put("name",m.get("name")+"");
                map1.put("sort",m.get("sort")+"");
                map1.put("attrs",objectList);
                ls.add(map1);
            }
            return ls;
        }else {
            List<HktBrandGoodsAttrQueryItem> hktBrandGoodsAttrQueryItems = hktGoodsAttrService.queryBrandSelectCache(hktGoodItem);
            if (!StringUtils.isNull(hktGoodItem)) {
                HktGoodsCategory category1 = new HktGoodsCategory();
                category1.setId(hktGoodItem.getCategoryId());
                HktGoodsCategory categoryTail = hktGoodsCategoryService.queryCategory(category1);
                if (categoryTail != null && categoryTail.getLevel() == 1) {
                    categoryTail.setLanguage("1");
                    Criteria[] criteriaAttrs = getCriteriaAttrs2(hktGoodItem);
                    for(Criteria cr : criteriaAttrs){
                        criteriaList.add(cr);
                    }
                } else {
                    Criteria[] criteriaAttrs = getCriteriaAttrs1(hktGoodItem);
                    for(Criteria cr : criteriaAttrs){
                        criteriaList.add(cr);
                    }
                }
            }
            Criteria[] criterialist = new Criteria[criteriaList.size()];
            for(int i=0;i<criteriaList.size();i++){
                criterialist[i] =criteriaList.get(i);
            }
            if(criterialist.length > 0){
                criatira.andOperator(criterialist);
            }
            String collectionName = goodsUtils.getCollectionName("1");
            Set<String> set = new HashSet<>();
            if(hktGoodItem.getAttrs().size() > 0 ){
                set = hktGoodsPageItemMongoHelper.distinctSearch1(criatira, collectionName);
            }
            List<Map<String, Object>> ls = new ArrayList<>();
            for(HktBrandGoodsAttrQueryItem m : hktBrandGoodsAttrQueryItems){
                Map<String,Object> map1 = new HashMap<>();
                Set<String> attrs = m.getAttrs();
                List<Object> objectList = new ArrayList<>();
                for(String str : attrs){
                    Map<String,Object> map = new HashMap<>();
                    map.put("values",str);
                    if(hktGoodItem.getAttrs().size() > 0 && !set.contains(str)){
                        map.put("type",0);
                    }else {
                        map.put("type",1);
                    }
                    objectList.add(map);
                }
                map1.put("name",m.getName());
                map1.put("attrs",objectList);
                ls.add(map1);
            }
            ls.sort((o1, o2) -> {
                String name1 = o1.get("name").toString();
                String name2 = o2.get("name").toString();
                return name2.compareTo(name1);
            });
            return ls;
        }
    }

    private Page<HktGoodItem> getPage(Page<HktGoodItem> hktGoodsItem, HktGoodsCategory category,String queryValue) {
        Set<String> ids = hktFavoritesService.getIdGoodsByUser();
        List<HktGoodItem> records = hktGoodsItem.getRecords();
        String language = "";
        if (category != null && !StringUtils.isNull(category.getLanguage())) {
            language = category.getLanguage();
        }
        if (records.size() > 0) {
            for (HktGoodItem hktGoodItem : records) {
                if (ids.contains(hktGoodItem.getId())) {
                    hktGoodItem.setCollect(1);
                }
//                hktGoodItem.setAttrs(null);
                if("2".equals(hktGoodItem.getLanguage())){
                    hktGoodItem.setName(hktGoodItem.getName());
                }else {
                    hktGoodItem.setName(hktGoodItem.getCategoryName() + " " + hktGoodItem.getName());
                }
                if (category != null && !StringUtils.isNull(category.getLanguage())) {
                    hktGoodItem.setParentCategoryId(category.getId());
                    switch (language) {
                        case "1":
                            hktGoodItem.setCategoryName(category.getNameCh());
                            break;
                        default:
                            hktGoodItem.setCategoryName(category.getNameEn());
                            break;
                    }
                }
            }
        }
        hktPriceRegulationService.callPriceRegulation(records);
        if(!StringUtils.isNull(queryValue)){
//            List<String> stringList = IKAnalyzerUtil.IKAnalysis(queryValue);
            String[] stringList = queryValue.toUpperCase().split(" ");
            for(HktGoodItem hgi : hktGoodsItem.getRecords()){
                hgi.setMn(hgi.getMaterialSn());
                hgi.setGn(hgi.getName());
                for(String str : stringList){
                    str = hktSearchReplacementService.findReplaceForMatching(str).trim();
                    if(hgi.getName().toUpperCase().contains(str)){
                        hgi.setName(getReplaceValue(hgi.getName().toUpperCase(),str));
                    }
//
                    /*if(hgi.getSpecParam().toUpperCase().contains(str)){
                        hgi.setSpecParam(getReplaceValue(hgi.getSpecParam().toUpperCase(),str));
                    }*/
                    if(hgi.getCategoryName().toUpperCase().contains(str)){
                        hgi.setCategoryName(getReplaceValue(hgi.getCategoryName().toUpperCase(),str));
                    }
                    if(hgi.getPackageSpecification().toUpperCase().contains(str)){
                        hgi.setPackageSpecification(getReplaceValue(hgi.getPackageSpecification().toUpperCase(),str));
                    }
                    if(hgi.getMaterialSn().toUpperCase().contains(str)){
                        hgi.setMaterialSn(getReplaceValue(hgi.getMaterialSn().toUpperCase(),str));
                    }
                }
                hgi.setMaterialSn(hgi.getMaterialSn().replaceAll("✔","span").replaceAll("★","style").replaceAll("✖","color").replaceAll("✤","#0067ed").toUpperCase());
//                hgi.setSpecParam(hgi.getSpecParam().replaceAll("✔","span").replaceAll("★","style").replaceAll("✖","color").replaceAll("✤","#0067ed").toUpperCase());
                hgi.setPackageSpecification(hgi.getPackageSpecification().replaceAll("✔","span").replaceAll("★","style").replaceAll("✖","color").replaceAll("✤","#0067ed").toUpperCase());
                hgi.setCategoryName(hgi.getCategoryName().replaceAll("✔","span").replaceAll("★","style").replaceAll("✖","color").replaceAll("✤","#0067ed").toUpperCase());
//                hgi.setBrandName(hgi.getBrandName().replaceAll("✔","span").replaceAll("★","style").replaceAll("✖","color").replaceAll("✤","#0067ed"));
                hgi.setName(hgi.getName().replaceAll("✔","span").replaceAll("★","style").replaceAll("✖","color").replaceAll("✤","#0067ed").toUpperCase());
            }
        }

       /*     for(HktGoodItem hgi : hktGoodsItem.getRecords()){

            }*/

        return hktGoodsItem;
    }

    private String getReplaceValue(String value,String replace){
//        return value.replaceAll(replace,"<span style='color:#0067ed'>"+replace+"</span>");
        return value.replaceAll(replace,"<✔ ★='✖:✤'>"+replace+"</✔>");
    }

    private Criteria[] getCriteriaAttrs1(HktGoodItem hktGoods) {
        Criteria[] ct;
        List<HktGoodsAttrItem> attrs = hktGoods.getAttrs();
        if (attrs != null && attrs.size() > 0) {
            ct = new Criteria[attrs.size() + 1];
            for (int i = 0; i < attrs.size(); i++) {
                String attrValue = attrs.get(i).getAttrValue();
                String[] splitValue = attrValue.split("&");
                String attrId = attrs.get(i).getAttrId();
                if ("封装".equals(attrId) || "specification".equals(attrId)) {
                    ct[i] = Criteria.where("packageSpecification").in(splitValue);
                } else if("品牌".equals(attrs.get(i).getAttrId()) || "brand".equals(attrs.get(i).getAttrId())) {
                    ct[i] = Criteria.where("brandName").in(splitValue);
                }else {
                    ct[i] = Criteria.where("attrs.attrId").is(attrs.get(i).getAttrId()).and("attrs.attrValue").in(splitValue);
                }
            }
            Criteria categoryCriteria = Criteria.where("categoryId").is(hktGoods.getCategoryId());
            ct[ct.length - 1] = categoryCriteria;
        } else {
            ct = new Criteria[1];
            Criteria categoryCriteria = Criteria.where("categoryId").is(hktGoods.getCategoryId());
            ct[0] = categoryCriteria;
        }
        return ct;
    }

    private Criteria[] getCriteriaAttrs2(HktGoodItem hktGoods) {

        HktGoodsCategory hg = new HktGoodsCategory();
        hg.setParentId(hktGoods.getCategoryId());
        List<HktGoodsCategory> hktGoodsCategories = hktGoodsCategoryService.queryLists(hg);
        Set<String> set = new HashSet<>();
        for (HktGoodsCategory hc : hktGoodsCategories) {
            set.add(hc.getId());
        }

        Criteria[] ct;
        List<HktGoodsAttrItem> attrs = hktGoods.getAttrs();
        if (attrs != null && attrs.size() > 0) {
            ct = new Criteria[attrs.size() + 1];
            for (int i = 0; i < attrs.size(); i++) {
                String attrValue = attrs.get(i).getAttrValue();
                String[] splitValue = attrValue.split("&");
//                ct[i] = Criteria.where("attrs.attrId").is(attrs.get(i).getAttrId()).and("attrs.attrValue").in(splitValue);
                if ("封装".equals(attrs.get(i).getAttrId()) || "specification".equals(attrs.get(i).getAttrId())) {
                    ct[i] = Criteria.where("packageSpecification").in(splitValue);
                } else if("品牌".equals(attrs.get(i).getAttrId()) || "brand".equals(attrs.get(i).getAttrId())) {
                    ct[i] = Criteria.where("brandName").in(splitValue);
                }else {
                    ct[i] = Criteria.where("attrs.attrId").is(attrs.get(i).getAttrId()).and("attrs.attrValue").in(splitValue);
                }
            }
            Criteria parentId = Criteria.where("categoryId").in(set);
            ct[ct.length - 1] = parentId;
        } else {
            ct = new Criteria[1];
            Criteria parentId = Criteria.where("categoryId").in(set);
            ct[0] = parentId;
        }
        return ct;
    }

    private Criteria[] getCriteriaAttrs3(HktGoodItem hktGoods) {

        Criteria[] ct;
        List<HktGoodsAttrItem> attrs = hktGoods.getAttrs();
        if (attrs != null && attrs.size() > 0) {
            ct = new Criteria[attrs.size()];
            for (int i = 0; i < attrs.size(); i++) {
                String attrValue = attrs.get(i).getAttrValue();
                String[] splitValue = attrValue.split("&");
                String attrId = attrs.get(i).getAttrId();
                if ("封装".equals(attrId) || "specification".equals(attrId)) {
                    ct[i] = Criteria.where("packageSpecification").in(splitValue);
                } else {
                    ct[i] = Criteria.where("attrs.attrId").is(attrs.get(i).getAttrId()).and("attrs.attrValue").in(splitValue);
                }
            }

        }else {
            ct = new Criteria[0];
        }
        return ct;
    }

    private void setProjectMap(Map<String, Object> objectMap, Criteria criatira, String collectionName) {
        List<String> brandName = mongoHelper.distinct(criatira, "brandName", collectionName);
        List<String> categoryName = mongoHelper.distinct(criatira, "categoryName", collectionName);
        objectMap.put("brandName", brandName);
        objectMap.put("categoryName", categoryName);
    }

    private void setProjectMap2(List<Map<String, Object>> objectMap, Criteria criatira, String collectionName) {
        List<Map<String, Object>> categoryName = mongoHelper.distinct1(criatira, "categoryName", collectionName);
        List<Map<String, Object>> list = mongoHelper.distinct1(criatira, "parentCategoryName", collectionName);
        Set<String> parentSet = new HashSet<>();
        Set<String> idsSet = new HashSet<>();

        for (Map<String, Object> stringObjectMap : list) {
            parentSet.add(stringObjectMap.get("name").toString());
        }
        String end = collectionName.substring(CommonConstant.HKT_Goods_Cache_KeyHead.length());
        end = end.substring(0, 1).toUpperCase() + end.substring(1);
        String newName = "name" + end;
        Criteria a = Criteria.where(newName).in(parentSet);

        Query querya = new Query(a);
        List<HktGoodsCategory> hktGoodsCategories = mongoHelper.find(querya, HktGoodsCategory.class);

        for (HktGoodsCategory hgc : hktGoodsCategories) {
            idsSet.add(hgc.getId());
        }

        Criteria b = Criteria.where("parentId").in(idsSet);

        Query queryb = new Query(b);
        List<HktGoodsCategory> hktGoodsCategories1 = mongoHelper.find(queryb, HktGoodsCategory.class);
        for (HktGoodsCategory hgc : hktGoodsCategories) {
            Map<String, Object> objMap = new HashMap<>();
            Object countTotal;
            for (Map<String, Object> map : list) {
                if (map.get("name").equals(getCategoryNameByEndWith(end, hgc))) {
                    countTotal = map.get("count");
                    objMap.put("id", hgc.getId());
                    objMap.put("name", getCategoryNameByEndWith(end, hgc));
                    objMap.put("count", countTotal);
                    List<Map<String, Object>> subList = new ArrayList<>();
                    for (HktGoodsCategory hgdc : hktGoodsCategories1) {
                        Map<String, Object> subMap = new HashMap<>();
                        if (hgc.getId().equals(hgdc.getParentId())) {
                            Object count;
                            for (Map<String, Object> map1 : categoryName) {
                                if (map1.get("name").equals(getCategoryNameByEndWith(end, hgdc))) {
                                    count = map1.get("count");
                                    subMap.put("count", count);
                                    subMap.put("name", getCategoryNameByEndWith(end, hgdc));
                                    subMap.put("id", hgdc.getId());
                                    subList.add(subMap);
                                }
                            }
                        }
                    }
                    objMap.put("sub", subList);
                }
            }
            objectMap.add(objMap);
        }
    }

    private String getCategoryNameByEndWith(String end, HktGoodsCategory hktGoodsCategory) {
        String name = "";
        if (end.endsWith("Ch")) {
            name = hktGoodsCategory.getNameCh();
        } else {
            name = hktGoodsCategory.getNameEn();
        }
        return name;
    }


    private Page<Map<String, Object>> getListForMap(HktGoodItem hktGoodItem, Query query, String collectionName, int type) {

        Page<HktGoodItem> pages = hktGoodsPageItemMongoHelper.findPage(hktGoodItem, query, HktGoodItem.class, collectionName);
        List<HktGoodItem> records = pages.getRecords();
        hktPriceRegulationService.callPriceRegulation(records);
        List<Map<String, Object>> list = new ArrayList<>();
        if (records != null && records.size() > 0) {
            for (HktGoodItem hg : records) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", hg.getId());
                map.put("image", hg.getGoodsImg());
                map.put("name", hg.getCategoryName() + " " + hg.getName());
                map.put("storeCount", hg.getStoreCount() + "/" + hg.getStoreCompany());
                if (type == 1) {
                    map.put("brandName", hg.getBrandName());
                    Double price = hg.getPrice();
                    map.put("price", price);
                    if (hktGoodItem.getPrice() > price) {
                        map.put("compare", "价格更低");
                    } else if (price.equals(hktGoodItem.getPrice())) {
                        map.put("compare", "价格相同");
                    } else {
                        map.put("compare", "价格更高");
                    }
                }
                list.add(map);
            }
        }
        Page<Map<String, Object>> mapPage = new Page<>();
        mapPage.setRecords(list);
        mapPage.setCurrent(pages.getCurrent());
        mapPage.setTotal(pages.getTotal());
        mapPage.setPageSize(pages.getPageSize());
        mapPage.setPages(pages.getPages());
        return mapPage;
    }
}
