package org.jeecg.modules.ctop.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TestService {


    public static void main(String[] args) {
        List<JSONObject> list1 = new ArrayList<>();
        JSONObject sex = new JSONObject();
        sex.put("SEX", "男");
        list1.add(sex);
        JSONObject sex2 = new JSONObject();
        sex2.put("SEX", "女");
        list1.add(sex2);


        List<JSONObject> list2 = new ArrayList<>();

        JSONObject age = new JSONObject();
        age.put("age", "青年");
        list2.add(age);
        JSONObject age2 = new JSONObject();
        age2.put("age", "中年");
        list2.add(age2);


        List<JSONObject> list3 = new ArrayList<>();

        JSONObject area = new JSONObject();
        JSONArray arr1 = new JSONArray();
        arr1.add("北京");
        arr1.add("天津");
        area.put("area", arr1);
        list3.add(area);


        JSONObject area2 = new JSONObject();
        JSONArray arr2 = new JSONArray();
        arr2.add("上海");
        arr2.add("深圳");
        area2.put("area", arr2);
        list3.add(area2);


        List<List<JSONObject>> allList = new ArrayList<>();
        allList.add(list1);
        allList.add(list2);
        allList.add(list3);

        calculateCombination(allList);
    }


    public static void calculateCombination(List<List<JSONObject>> inputList) {
        JSONArray array = new JSONArray();
        List<Integer> combination = new ArrayList<Integer>();
        int n = inputList.size();
        for (int i = 0; i < n; i++) {
            combination.add(0);
        }
        int i = 0;
        boolean isContinue = false;
        do {
            JSONObject dataJson = new JSONObject();
            //打印一次循环生成的组合
            for (int j = 0; j < n; j++) {
                JSONObject jsonObject = inputList.get(j).get(combination.get(j));
                jsonObject.forEach((key, value) -> {
                    dataJson.put(key, value);
                });

            }
            array.add(dataJson);

            i++;
            combination.set(n - 1, i);
            for (int j = n - 1; j >= 0; j--) {
                if (combination.get(j) >= inputList.get(j).size()) {
                    combination.set(j, 0);
                    i = 0;
                    if (j - 1 >= 0) {
                        combination.set(j - 1, combination.get(j - 1) + 1);
                    }
                }
            }
            isContinue = false;
            for (Integer integer : combination) {
                if (integer != 0) {
                    isContinue = true;
                }
            }
        } while (isContinue);
    }
}
