package com.xty.common.weight.areaselector;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Toast;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.xty.common.R;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MyAreaView extends ConstraintLayout {

    private String TAG = "AreaSelector";
    private Activity context;
    private final String MAP_KEY = "6QSBZ-JHQ3G-O46QE-ILDZC-LP3Y6-ETFP3";
    private String CityNo = "";
    private String CityName = "";
    private List<CitySuccess.ResultBean> province;//省
    private List<CitySuccess.ResultBean> city;//市
    private List<CitySuccess.ResultBean> area;//区
    private List<CitySuccess.ResultBean> cityList;//当前的市
    private List<CitySuccess.ResultBean> areaList;//当前的区
    private boolean isEnd = false;//定义数据是否已经添加完的标识

    private NumberPicker picker1,picker2,picker3;
    private Button button;
//    private OnClickListener listener;
//
//    public MyAreaView(Context context,OnClickListener listener){
//        this(context, (AttributeSet) null);
//        this.listener = listener;
//    }

    public MyAreaView(Context context) {
        this(context, (AttributeSet) null);
    }

    public MyAreaView(Context context, AttributeSet attrs) {
        this(context,attrs,0);
    }

    public MyAreaView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = (Activity) context;
        View view = LayoutInflater.from(context).inflate(R.layout.picket_dialog,this);
        picker1 = view.findViewById(R.id.picker1);
        picker2 = view.findViewById(R.id.picker2);
        picker3 = view.findViewById(R.id.picker3);
        button = view.findViewById(R.id.button);
        getCity(MAP_KEY);
    }

    public void setButtonOnClickListener(OnClickListener listener){
        if(listener!=null){
            button.setVisibility(VISIBLE);
            button.setOnClickListener(listener);
        }else{
            button.setVisibility(GONE);
        }
    }

    public String getCityNo() {
        CityNo = areaList.isEmpty()? cityList.get(picker2.getValue()).getId():areaList.get(picker3.getValue()).getId();
        return CityNo;
    }

    public String getCityName(String s) {
        CityName = areaList.isEmpty()? province.get(picker1.getValue()).getFullname()+s+cityList.get(picker2.getValue()).getFullname() : province.get(picker1.getValue()).getFullname()+s+cityList.get(picker2.getValue()).getFullname()+s+areaList.get(picker3.getValue()).getFullname();
        return CityName;
    }

    public void showMyAreaView() {
        if(province == null || city == null || area == null){
            Toast.makeText(context, "数据获取失败,请重试", Toast.LENGTH_SHORT).show();
            return;
        }
        //初始化控件的数据
        initPicket(picker1, province);
        //获取省级数据ID的前两位
        String num = province.get(0).getId().substring(0, 2);
        //获取数据
        cityList = getList(num,city);
        //初始化控件的数据
        initPicket(picker2, cityList);
        //areaList不赋值直接传是因为 腾讯的数据第一条是北京
        //北京上海香港澳门那些城市 他们的数据只到市级不到区级 所以北京的区级数据本来就是空的
        initPicket(picker3, areaList);

        //设置监听  当省级数据改变时  需要改变市和区的数据
        picker1.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker numberPicker, int i, int i1) {
                //获取省级数据ID的前两位  下面道理同上
                String num = province.get(i1).getId().substring(0, 2);
                //获取数据
                cityList = getList(num,city);
                //初始化控件
                initPicket(picker2, cityList);
                //获取当前市级数据ID的前四位
                num = cityList.get(0).getId().substring(0, 4);
                areaList = getList(num,area);
                initPicket(picker3, areaList);
            }
        });
        //设置监听  当省级数据改变时  只需要改变区级数据
        picker2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker numberPicker, int i, int i1) {
                String num = cityList.get(i1).getId().substring(0, 4);
                areaList = getList(num,area);
                initPicket(picker3, areaList);
            }
        });
    }

    private void getCity(String key) {
        Call<CitySuccess> call = new RetrofitUtil().getApiInstance().getCity(key);
        call.enqueue(new Callback<CitySuccess>() {
            @Override
            public void onResponse(Call<CitySuccess> call, Response<CitySuccess> response) {
                CitySuccess success = response.body();
                Log.e(TAG, "success \n"+success.toString());
                province = success.getResult().get(0);
                city = success.getResult().get(1);
                area = success.getResult().get(2);
                areaList = new ArrayList<>();
                cityList = new ArrayList<>();
                showMyAreaView();
            }

            @Override
            public void onFailure(Call<CitySuccess> call, Throwable t) {

            }
        });
    }

    private List<CitySuccess.ResultBean> getList(String num, List<CitySuccess.ResultBean> list){
        List<CitySuccess.ResultBean> myList = new ArrayList<>();
        int length = num.length();
        for (int x = 0; x < list.size(); x++) {
            Log.e("getList","x == "+x);
            //对比市级列表Id的前两位是否跟选中的省级Id前两位相等  相等的话则代表是该省下面的市
            //对比区级列表Id的前四位是否跟选中的市级Id前四位相等  相等的话则代表是该市下面的区
            if (num.equals(list.get(x).getId().substring(0, length))) {
                myList.add(list.get(x));
                if(!isEnd){
                    isEnd = true;
                }
                continue;
            }
            if (isEnd){
                //数据添加完成后  将isEnd重置并退出循环
                isEnd = false;
                break;
            }
        }
        return myList;
    }

    private void initPicket(NumberPicker picker, List<CitySuccess.ResultBean> list) {
        List<String> list1 = new ArrayList<>();
        for(CitySuccess.ResultBean bean : list){
            list1.add(bean.getFullname());
        }
//        List<String> list1 = list.stream().map(CitySuccess.ResultBean::getFullname).collect(Collectors.toList());
        String[] strings = new String[list1.size()];
        list1.toArray(strings);
        picker.setValue(0);
        if (strings.length == 0) {
            picker.setMinValue(0);
            picker.setMaxValue(0);
            picker.setDisplayedValues(new String[]{" "});
            return;
        }
        picker.setWrapSelectorWheel(false);
        picker.setMinValue(0);
        picker.setDisplayedValues(strings);
        picker.setMaxValue(strings.length - 1);
        picker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
    }
}
