package com.mayi.fastdevelop.view.wheel;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import com.alibaba.fastjson.JSON;
import com.mayi.fastdevelop.R;
import com.mayi.fastdevelop.view.wheel.adapters.AbstractWheelTextAdapter;
import com.mayi.fastdevelop.view.wheel.views.CustomWheelView;
import com.mayi.fastdevelop.view.wheel.views.OnWheelChangedListener;
import com.mayi.fastdevelop.view.wheel.views.OnWheelScrollListener;
import com.mayi.fastdevelop.view.dialog.BaseDialog;
import com.mayi.fastdevelop.view.dialog.DialogViewHolder;

import org.json.JSONArray;
import org.json.JSONObject;

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


/**
 * 城市二级联动对话框
 */
public class ChangeAddressDialog extends BaseDialog implements View.OnClickListener {

    private CustomWheelView wvProvince;
    private CustomWheelView wvCitys;
    private TextView btnSure;
    private TextView btnCancel;

    private Context context;
    private JSONObject mJsonObj;
    private String[] mProvinceDatas;
    private Map<String, String[]> mCitisDatasMap = new HashMap<>();

    private ArrayList<String> arrProvinces = new ArrayList<String>();
    private ArrayList<String> arrCitys = new ArrayList<String>();
    private AddressTextAdapter provinceAdapter;
    private AddressTextAdapter cityAdapter;

    private String strProvince = "上海市";
    private String strCity = "黄浦区";
    private OnAddressCListener onAddressCListener;

    private final static int maxsize = 16;
    private final static int minsize = 14;
    private final static int chooicesize = 20;

    public ChangeAddressDialog(Context context, OnAddressCListener onAddressCListener) {
        super(context, R.layout.dialog_myinfo_changeaddress);
        this.context = context;
        this.onAddressCListener = onAddressCListener;
        initDataAndBindEvent();
    }

    @Override
    public void convert(DialogViewHolder holder) {
        View view = holder.getConvertView();
        wvProvince = (CustomWheelView) view.findViewById(R.id.wv_address_province);
        wvCitys = (CustomWheelView) view.findViewById(R.id.wv_address_city);
        btnSure = (TextView) view.findViewById(R.id.btn_sure);
        btnCancel = (TextView) view.findViewById(R.id.btn_cancel);

        btnSure.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
    }

    private void initDataAndBindEvent() {
        initJsonData();
        initDatas();
        initProvinces();
        String s= JSON.toJSONString(mCitisDatasMap);
        provinceAdapter = new AddressTextAdapter(context, arrProvinces, getProvinceItem(strProvince), maxsize, minsize);
        wvProvince.setVisibleItems(5);
        wvProvince.setViewAdapter(provinceAdapter);
        wvProvince.setCurrentItem(getProvinceItem(strProvince));

        initCitys(mCitisDatasMap.get(strProvince));
        cityAdapter = new AddressTextAdapter(context, arrCitys, getCityItem(strCity), maxsize, minsize);
        wvCitys.setVisibleItems(5);
        wvCitys.setViewAdapter(cityAdapter);
        wvCitys.setCurrentItem(getCityItem(strCity));

        wvProvince.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(CustomWheelView wheel, int oldValue, int newValue) {
                // TODO Auto-generated method stub
                String currentText = (String) provinceAdapter.getItemText(wheel.getCurrentItem());
                strProvince = currentText;
                setTextviewSize(currentText, provinceAdapter);
                String[] citys = mCitisDatasMap.get(currentText);
                initCitys(citys);
                cityAdapter = new AddressTextAdapter(context, arrCitys, 0, maxsize, minsize);
                wvCitys.setVisibleItems(5);
                wvCitys.setViewAdapter(cityAdapter);
                wvCitys.setCurrentItem(0);
            }
        });

        wvProvince.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(CustomWheelView wheel) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onScrollingFinished(CustomWheelView wheel) {
                // TODO Auto-generated method stub
                String currentText = (String) provinceAdapter.getItemText(wheel.getCurrentItem());
                setTextviewSize(currentText, provinceAdapter);
            }
        });

        wvCitys.addChangingListener(new OnWheelChangedListener() {

            @Override
            public void onChanged(CustomWheelView wheel, int oldValue, int newValue) {
                // TODO Auto-generated method stub
                String currentText = (String) cityAdapter.getItemText(wheel.getCurrentItem());
                strCity = currentText;
                setTextviewSize(currentText, cityAdapter);
            }
        });

        wvCitys.addScrollingListener(new OnWheelScrollListener() {

            @Override
            public void onScrollingStarted(CustomWheelView wheel) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onScrollingFinished(CustomWheelView wheel) {
                // TODO Auto-generated method stub
                String currentText = (String) cityAdapter.getItemText(wheel.getCurrentItem());
                setTextviewSize(currentText, cityAdapter);
            }
        });
    }

    private class AddressTextAdapter extends AbstractWheelTextAdapter {
        ArrayList<String> list;

        protected AddressTextAdapter(Context context, ArrayList<String> list, int currentItem, int maxsize, int minsize) {
            super(context, R.layout.item_birth_year, NO_RESOURCE, currentItem, maxsize, minsize);
            this.list = list;
            setItemTextResource(R.id.tempValue);
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        @Override
        public int getItemsCount() {
            return list.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return list.get(index) + "";
        }
    }

    /**
     * 设置字体大小
     *
     * @param curriteItemText
     * @param adapter
     */
    private void setTextviewSize(String curriteItemText, AddressTextAdapter adapter) {
        ArrayList<View> arrayList = adapter.getTestViews();
        int size = arrayList.size();
        String currentText;
        for (int i = 0; i < size; i++) {
            TextView textvew = (TextView) arrayList.get(i);
            currentText = textvew.getText().toString();
            if (curriteItemText.equals(currentText)) {
                textvew.setTextSize(chooicesize);
            } else {
                textvew.setTextSize(minsize);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_sure) {
            if (onAddressCListener != null) {
                onAddressCListener.onClick(strProvince, strCity);
            }
            dismiss();
        } else if (i == R.id.btn_cancel) {
            dismiss();
        }
    }

    /**
     * 回调接口
     *
     * @author Administrator
     */
    public interface OnAddressCListener {
        void onClick(String province, String city);
    }

    /**
     * 从文件中读取地址数据
     */
    private void initJsonData() {
        try {
            InputStream is = context.getResources().getAssets().open("city.json");
            int ch = 0;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((ch = is.read()) != -1) {
                out.write(ch);
            }
            byte[] buff = out.toByteArray();
            out.close();
            is.close();
            String content = new String(buff, "UTF-8");

            mJsonObj = new JSONObject(content);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析数据
     */
    private void initDatas() {
        try {
            JSONArray jsonArray = mJsonObj.optJSONArray("citylist");
            mProvinceDatas = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.optJSONObject(i);
                String province = jsonP.optString("nm");
                mProvinceDatas[i] = province;
                JSONArray jsonCs = jsonP.optJSONArray("cl");
                if (jsonCs != null && jsonCs.length() > 0) {
                    String[] mCitiesDatas = new String[jsonCs.length()];
                    for (int j = 0; j < jsonCs.length(); j++) {
                        JSONObject jsonCity = jsonCs.optJSONObject(j);
                        String city = jsonCity.optString("nm");
                        mCitiesDatas[j] = city;
                        JSONArray jsonAreas = jsonCity.optJSONArray("cl");
                        if (jsonAreas != null && jsonAreas.length() > 0) {
                            String[] mAreasDatas = new String[jsonAreas.length()];
                            for (int k = 0; k < jsonAreas.length(); k++) {
                                String area = jsonAreas.optJSONObject(k).optString("nm");
                                mAreasDatas[k] = area;
                            }
                        }
                    }
                    mCitisDatasMap.put(province, mCitiesDatas);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mJsonObj = null;
    }

    /**
     * 初始化省会
     */
    private void initProvinces() {
        int length = mProvinceDatas.length;
        for (int i = 0; i < length; i++) {
            arrProvinces.add(mProvinceDatas[i]);
        }
    }

    /**
     * 根据省会，生成该省会的所有城市
     *
     * @param citys
     */
    private void initCitys(String[] citys) {
        if (citys != null) {
            arrCitys.clear();
            int length = citys.length;
            for (int i = 0; i < length; i++) {
                arrCitys.add(citys[i]);
            }
        } else {
            String[] city = mCitisDatasMap.get("上海市");
            arrCitys.clear();
            int length = city.length;
            for (int i = 0; i < length; i++) {
                arrCitys.add(city[i]);
            }
        }
        if (arrCitys != null && arrCitys.size() > 0
                && !arrCitys.contains(strCity)) {
            strCity = arrCitys.get(0);
        }
    }

    /**
     * 返回省会索引，没有就返回默认“上海市”
     *
     * @param province
     * @return
     */
    private int getProvinceItem(String province) {
        int size = arrProvinces.size();
        int provinceIndex = 0;
        for (int i = 0; i < size; i++) {
            if (province.equals(arrProvinces.get(i))) {
                return provinceIndex;
            } else {
                provinceIndex++;
            }
        }
        strProvince = "上海市";
        return 22;
    }

    /**
     * 得到城市索引，没有返回默认“市辖区”
     *
     * @param city
     * @return
     */
    private int getCityItem(String city) {
        int size = arrCitys.size();
        int cityIndex = 0;
        for (int i = 0; i < size; i++) {
            if (city.equals(arrCitys.get(i))) {
                return cityIndex;
            } else {
                cityIndex++;
            }
        }
        strCity = "市辖区";
        return 0;
    }

}