package com.zcxk.core.mongo.utils;

import com.zcxk.core.common.pojo.ProgramItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Andy
 * @date 2021-07-22 11:03
 */
public class MongoPrivilegeTools {

    public static Criteria[] buildDataPrivilegeCriteria(List<ProgramItem> dataProgramList){
        List<Criteria> result = new ArrayList<>();
        // 1,安装维度构建Map
        Map<String,List<Integer>> dataProgramMap = new HashMap<>() ;
        for (ProgramItem item : dataProgramList){
            String code = item.getDimensionCode();
            String value = item.getDimensionValue() ;
            List<Integer> dataList = dataProgramMap.get(code);
            if(dataList == null) {
                dataList = new ArrayList<>();
                dataList.add(Integer.parseInt(value));
                dataProgramMap.put(code,dataList) ;
            }
            else{
                dataList.add(Integer.parseInt(value));
            }

        }
        // 2,构建查询条件
        for(Map.Entry<String, List<Integer>> entry : dataProgramMap.entrySet()){
            String key = entry.getKey();
            List<Integer> value = entry.getValue();
            // 省维度
            if(StringUtils.equals(key,"PROVINCE")){
                Criteria pCriteria = Criteria.where("provinceId").in(value);
                result.add(pCriteria);
            }
            // 市维度
            else if(StringUtils.equals(key,"CITY")){
                Criteria cityCriteria = Criteria.where("cityId").in(value);
                result.add(cityCriteria);
            }
            // 区维度
            else if(StringUtils.equals(key,"REGION")){
                Criteria cityCriteria = Criteria.where("regionId").in(value);
                result.add(cityCriteria);
            }
            // 小区维度
            else if(StringUtils.equals(key,"COMMUNITY")){
                Criteria communityCriteria = Criteria.where("communityId").in(value);
                result.add(communityCriteria);
            }
            // 建筑维度
            else if(StringUtils.equals(key,"BUILDING")){
                Criteria buildingCriteria = Criteria.where("buildingId").in(value);
                result.add(buildingCriteria);
            }
            // 客户维度
            else if (StringUtils.equals(key,"CUSTOMER")){
                Criteria cCriteria = Criteria.where("customerId").in(value) ;
                result.add(cCriteria);
            }
            // 项目维度
            else if (StringUtils.equals(key,"PROJECT")){
                Criteria proCriteria = Criteria.where("projectId").in(value) ;
                result.add(proCriteria);
            }
        }

        //转换数组
        Criteria[] criteriaArray = result.toArray(new Criteria[result.size()]);
        return criteriaArray ;
    }

}
