package com.eversec.kit.dev;

import com.eversec.common.ExcelKit;
import com.eversec.common.FileKit;
import com.eversec.common.Kv;
import com.jfinal.template.Engine;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Predicate;

/**
 * 字典数据入库
 * 1、读取excel
 * 2、生成入库语句
 *
 * @author: liangxianyou at 2018/8/15 10:54.
 */
public class Dict2Db {

    public static String clazzRoot = Dict2Db.class.getClassLoader().getResource("").getPath();
    public static Engine engine = Engine.use();

    public static void main(String[] args) {
        //
        //createSql(readExcel());
    }

    /**
     * 读取dict字典数据
     * @return
     */
    public static Map<String, List<Map>> readExcel(){
        try {
            return ExcelKit.readExcelAll(new File("res/xls/dict.xls"), new String[]{"id", "name", "code"});
        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }

    /**
     * 创建字典入库sql语句
     * @param listMap
     */
    public static void createSql(Map<String, List<Map>> listMap) {

        Kv kv = Kv.of("maps", listMap);
        String str = engine.getTemplate(clazzRoot + "libs/tpl/DictSqlTpl.sql").renderToString(kv);

        try {
            FileKit.strToFile(str, new File("tmp/db/dict_data.sql"), true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<Map> readCityData() {
        try {
            return ExcelKit.readExcel(new File("res/xls/省市县数据.xlsx"), new String[]{"code", "province", "city"});
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    Predicate<Map> isProvice = (s) -> String.valueOf(s.get("code")).trim().endsWith("0000");
    Predicate<Map> isCity = (s) -> String.valueOf(s.get("code")).trim().endsWith("00");
    Predicate<Map> isCounty = (s) -> !String.valueOf(s.get("code")).trim().endsWith("00");

    /**
     * 处理 省-市-县数据
     */
    //@Test
    public Map getCityData() {
        List<Map> maps = readCityData();
        maps.remove(0);

        Map provices = new LinkedHashMap();
        maps.forEach(x -> {
            if (isProvice.test(x)) {
                //System.out.println(x);
                LinkedHashMap<Object, Object> provice = new LinkedHashMap<>();
                provice.put("name", x.get("province"));
                provices.put(x.get("code"), provice);
            } else {
                String proCode = String.valueOf(x.get("code")).trim().substring(0, 2) + "0000"; // 省编码
                String cityCode = String.valueOf(x.get("code")).trim().substring(0, 4) + "00"; // 市编码

                Map provice = (Map) provices.getOrDefault(proCode, new LinkedHashMap<>()); //省数据
                Map city = (Map) provice.getOrDefault(cityCode, new LinkedHashMap<>()); //市数据
                if (isCity.test(x)) {
                    city.put("name", x.get("city"));
                    provice.put(x.get("code"), city);
                } else if (isCounty.test(x)){
                    String countyCode = String.valueOf(x.get("code")).trim(); // 县编码
                    Map county = (Map) provice.getOrDefault(countyCode, new LinkedHashMap<>()); //县数据
                    county.put("name", x.get("city"));

                    city.put(countyCode, county);
                }
                provices.put(proCode, provice);
            }
        });


        /*try {
            FileKit.strToFile(new Gson().toJson(provices), new File("tmp/city.json"));
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        return provices;
    }

    private BiFunction<String, Map<String, Object>, String> fun = (s, m) -> {
        //扫描第一层
        for (String k : m.keySet()) {
            if (!"name".equals(k)) {
                Map map = (Map) m.get(k);
                if (String.valueOf(map.get("name")).contains(s)) {
                    return k;
                }
            }
        }

        return null;
    };

    private BiFunction<String[], Map<String, Object>, String[]> cityDeal = (ss, m) -> {
        String proCode = fun.apply(ss[0], m);
        String cityCode = null;

        if (proCode != null) {
            Map<String, Object> proData = (Map<String, Object>) m.get(proCode);
            cityCode = fun.apply(ss[1], proData);

            for (String k : proData.keySet()) {
                if (!"name".equals(k)) {
                    cityCode = fun.apply(ss[1], (Map<String, Object>) proData.get(k));
                    if (cityCode != null) {
                        break;
                    }
                }
            }
        }

        return new String[]{proCode, cityCode};
    };



    /**
     * 中文反查询 城市编码
     */
    @Test
    public void run1() {
        String provice = "宁夏";
        String city = "同心";

        Kv kv = Kv.of(440000,"东莞市").set(370000,"临沂市").set(440000,"云浮市").set(440000,"佛山市").set(620000,"兰州市").set(110000,"北京").set(320000,"南京").set(360000,"南昌").set(350000,"厦门").set(340000,"合肥").set(150000,"呼和浩特").set(120000,"天津").set(140000,"太原").set(510000,"广元").set(440000,"广州").set(320000,"徐州").set(440000,"惠州").set(510000,"成都").set(440000,"揭阳").set(320000,"无锡").set(530000,"昆明").set(330000,"杭州").set(440000,"梅州").set(420000,"武汉").set(440000,"江门").set(350000,"泉州").set(370000,"泰安").set(370000,"济南").set(370000,"济宁").set(370000,"淄博").set(440000,"深圳").set(440000,"湛江").set(370000,"滨州").set(370000,"潍坊").set(370000,"烟台").set(440000,"珠海").set(650000,"石河子").set(350000,"福州").set(440000,"肇庆").set(340000,"芜湖").set(320000,"苏州").set(430000,"衡阳").set(630000,"西宁").set(610000,"西安").set(360000,"赣州").set(510000,"达州").set(130000,"邢台").set(420000,"鄂州").set(500000,"重庆").set(320000,"镇江").set(430000,"长沙").set(370000,"青岛").set(420000,"黄石");

        String[] sArr = {provice, city};

        Map<String, Map<String, Object>> cityData = getCityData();

        StringBuilder buf = new StringBuilder();
        cityData.forEach((k, v) -> {
            buf.append(String.format("('%s','%s'),%n", k, v.get("name")));

            System.out.println(v);

            v.forEach((k1, v1) -> {
                if (k1.equals("name")) {
                } else {
                    buf.append(String.format("('%s','%s'),%n", k1, ((Map)v1).get("name")));

                    ((Map) v1).forEach((k2,v2) -> {
                        if (!k2.equals("name")) {
                            buf.append(String.format("('%s','%s'),%n", k2, ((Map)v2).get("name")));
                        }
                    });
                }
            });
        });

        try {
            FileKit.strToFile(buf.toString(), new File("tmp/city.sql"));
        } catch (IOException e) {
            e.printStackTrace();
        }


        /*kv.forEach((k, v) -> {
            Map map = (Map) cityData.get(String.valueOf(k));
            map.forEach((_k,_v) -> {
                System.out.println(_v);
                if (!"name".equals(_k) && String.valueOf(((Map)_v).get("name")).equals(String.valueOf(v))) {
                    System.out.printf("%s - %s", _k, v);
                }
            });
        });*/





        /*String[] apply = cityDeal.apply(sArr, cityData);

        System.out.println(apply[0]);
        System.out.println(apply[1]);*/
    }

}
