package cn.stylefeng.team.form.api.parser;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.NoResourceException;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.roses.kernel.rule.format.BaseSimpleFieldFormatProcess;
import cn.stylefeng.team.form.api.entity.FormItem;
import cn.stylefeng.team.form.api.parser.base.BaseFormFormat;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class FormCityFormatFormat extends BaseSimpleFieldFormatProcess implements BaseFormFormat {

    private static Map<String, String> CITY_CODE_TO_NAME = new HashMap<>();

    private static final Object LOCK_OBJ = new Object();

    @Override
    public Class<?> getItemClass() {
        return String.class;
    }

    @Override
    public Object simpleItemFormat(Object businessId) {

        if (ObjectUtil.isEmpty(businessId)) {
            return null;
        }

        if (ObjectUtil.isEmpty(CITY_CODE_TO_NAME)) {
            synchronized (LOCK_OBJ) {
                readObj();
            }
        }

        String cityCodeArryString = String.valueOf(businessId);

        JSONArray cityArray = JSON.parseArray(cityCodeArryString);
        if (ObjectUtil.isEmpty(cityArray)) {
            return null;
        }

        StringBuilder cityName = new StringBuilder();

        for (int i = 0; i < cityArray.size(); i++) {
            String cityCode = cityArray.getString(i);
            cityName.append(CITY_CODE_TO_NAME.get(cityCode)).append("-");
        }

        return cityName.deleteCharAt(cityName.length() - 1);
    }

    private void readObj() {
        InputStream inputStream = null;
        try {
            inputStream = ResourceUtil.getStream("city.json");
            String cityJson = IoUtil.readUtf8(inputStream);
            JSONArray jsonArray = JSON.parseArray(cityJson);

            putAllCityToCache(jsonArray);
        } catch (Exception e) {
            throw new NoResourceException("city.json资源文件读取失败！");
        } finally {
            IoUtil.close(inputStream);
        }
    }

    private void putAllCityToCache(JSONArray jsonArray) {

        if (ObjectUtil.isEmpty(jsonArray)) {
            return;
        }

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject cityInfo = jsonArray.getJSONObject(i);
            String code = cityInfo.getString("value");
            String label = cityInfo.getString("label");
            CITY_CODE_TO_NAME.put(code, label);

            JSONArray children = cityInfo.getJSONArray("children");
            putAllCityToCache(children);
        }

    }

    @Override
    public Object formatProcess(FormItem formItem, Object originValue) {
        return this.simpleItemFormat(originValue);
    }

}
