package com.tenlionsoft.baselib.core.widget.views;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.hjq.toast.ToastUtils;
import com.tenlionsoft.baselib.R;
import com.tenlionsoft.baselib.constant.PathConfig;
import com.tenlionsoft.baselib.core.beans.AreaBean;
import com.tenlionsoft.baselib.core.retrofit_net.RetrofitManager;
import com.tenlionsoft.baselib.core.retrofit_net.api.BaseApiService;
import com.tenlionsoft.baselib.utils.UIUtil;
import com.tenlionsoft.baselib.utils.UserLgUtils;

import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;


/**
 * 作者 : Adam on 2018/7/23.
 * 邮箱 : itgaojian@163.com
 * 描述 : 地区选择
 */
public class AreaChooseDialog extends Dialog {

    private boolean iscancelable;
    private boolean isBackCancelable;
    private View view;
    private Context context;
    private int gravity;
    private OnChoseListener mListener;
    private boolean mIsShow;
    private boolean mIsShowOther;
    private boolean mIsDefault;
    private TextView mTvArea1;
    private TextView mTvArea2;
    private TextView mTvArea3;
    private TextView mTvArea4;
    private TextView mTvArea5;
    private OptionsPickerView mArea1Picker;
    private OptionsPickerView mArea2Picker;
    private OptionsPickerView mArea3Picker;
    private OptionsPickerView mArea4Picker;
    private OptionsPickerView mArea5Picker;


    private List<AreaBean> mArea1List;
    private List<AreaBean> mArea2List;
    private List<AreaBean> mArea3List;
    private List<AreaBean> mArea4List;
    private List<AreaBean> mArea5List;
    private AreaBean mSelArea1;
    private AreaBean mSelArea2;
    private AreaBean mSelArea3;
    private AreaBean mSelArea4;
    private AreaBean mSelArea5;

    private AreaChooseDialog(Context context, boolean isCancelable, boolean isBackCancelable, int gravity, boolean isShow, boolean isShowOther, boolean isDefault) {
        super(context, R.style.dialog_center_alpha);
        this.context = context;
        this.gravity = gravity;
        this.iscancelable = isCancelable;
        this.isBackCancelable = isBackCancelable;
        this.mIsShow = isShow;
        this.mIsShowOther = isShowOther;
        this.mIsDefault = isDefault;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = LayoutInflater.from(context).inflate(R.layout.dialog_choose_area_new, null);
        setContentView(view);
        setCancelable(iscancelable);
        setCanceledOnTouchOutside(isBackCancelable);
        mTvArea1 = view.findViewById(R.id.tv_area1);
        mTvArea2 = view.findViewById(R.id.tv_area2);
        mTvArea3 = view.findViewById(R.id.tv_area3);
        mTvArea4 = view.findViewById(R.id.tv_area4);
        mTvArea5 = view.findViewById(R.id.tv_area5);

        mTvArea3.setOnClickListener(v -> onShowArea3());
        mTvArea4.setOnClickListener(v -> onShowArea4());
        mTvArea5.setOnClickListener(v -> onShowArea5());
        if (mIsDefault) {
            mTvArea1.setText(PathConfig.DEFAULT_AREA_1_Name);
            mTvArea2.setText(PathConfig.DEFAULT_AREA_2_Name);
            mSelArea1 = new AreaBean();
            mSelArea1.setAreaName(PathConfig.DEFAULT_AREA_1_Name);
            mSelArea1.setAreaId(PathConfig.DEFAULT_AREA_1);
            mSelArea1.setAreaCode(PathConfig.DEFAULT_AREA_1_CODE);
            mSelArea2 = new AreaBean();
            mSelArea2.setAreaName(PathConfig.DEFAULT_AREA_2_Name);
            mSelArea2.setAreaId(PathConfig.DEFAULT_AREA_2);
            mSelArea2.setAreaCode(PathConfig.DEFAULT_AREA_2_CODE);
        } else {
            mTvArea1.setOnClickListener(v -> onShowArea1());
            mTvArea2.setOnClickListener(v -> onShowArea2());
            mTvArea1.setText("");
            mTvArea2.setText("");
        }
        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> this.dismiss());
        view.findViewById(R.id.tv_confirm).setOnClickListener(v -> doConfirm());
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        Window window = this.getWindow();
        window.setGravity(Gravity.CENTER);
        window.setWindowAnimations(R.style.dialog_center_alpha);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = (int) (displayMetrics.widthPixels * 0.9);
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
        window.setBackgroundDrawable(new ColorDrawable());
    }

    private void doConfirm() {
        if (checkParams()) {
            String areq1 = mTvArea1.getText().toString().trim();
            String area2 = mTvArea2.getText().toString().trim();
            String area3 = mTvArea3.getText().toString().trim();
            String area4 = mTvArea4.getText().toString().trim();
            String area5 = mTvArea5.getText().toString().trim();
            String selArea = areq1 + "," + area2 + "," + area3;
            if (!TextUtils.isEmpty(area4)) {
                selArea += "," + area4;
            }
            if (!TextUtils.isEmpty(area5)) {
                selArea += "," + area5;
            }
            String id = mSelArea3.getAreaId();
            String code = mSelArea3.getAreaCode();
            if (mSelArea4 != null) {
                id = mSelArea4.getAreaId();
                code = mSelArea4.getAreaCode();
            }
            if (mSelArea5 != null) {
                id = mSelArea5.getAreaId();
                code = mSelArea5.getAreaCode();
            }
            mListener.doConfirm(selArea, id, code);
        }
    }

    /**
     * 校验参数
     */
    private boolean checkParams() {
        if (mSelArea1 == null) {
            ToastUtils.show("请选择省、自治区");
            return false;
        }
        if (mSelArea2 == null) {
            ToastUtils.show("请选择盟市");
            return false;
        }
        if (mSelArea3 == null) {
            ToastUtils.show("请选择旗县区");
            return false;
        }
        return true;
    }


    /**
     * area1
     */
    private void onShowArea1() {
        if (null == mArea1List || mArea1List.size() <= 0) {
            getAreaList(1, PathConfig.DEFAULT_AREA_CODE);
        } else {
            mArea1Picker = new OptionsPickerBuilder(context, (options1, options2, options3, v) -> {
                AreaBean bean = mArea1List.get(options1);
                mTvArea1.setText(bean.getAreaName());
                mSelArea1 = bean;

                mSelArea2 = null;
                mTvArea2.setText("");
                mArea2List = null;

                mSelArea3 = null;
                mTvArea3.setText("");
                mArea3List = null;

                mSelArea4 = null;
                mTvArea4.setText("");
                mArea4List = null;

                mSelArea5 = null;
                mTvArea5.setText("");
                mArea5List = null;

            })
                    .setTitleText("请选择区域")
                    .isDialog(true)
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
            mArea1Picker.setPicker(mArea1List);
            mArea1Picker.show();
        }
    }


    /**
     * area2
     */
    private void onShowArea2() {
        if (null == mArea2List || mArea2List.size() <= 0) {
            if (mSelArea1 == null) {
                ToastUtils.show("请选择省、自治区");
            } else {
                getAreaList(2, mSelArea1.getAreaId());
            }
        } else {
            mArea2Picker = new OptionsPickerBuilder(context, (options1, options2, options3, v) -> {
                AreaBean bean = mArea2List.get(options1);
                mTvArea2.setText(bean.getAreaName());
                mSelArea2 = bean;

                mSelArea3 = null;
                mTvArea3.setText("");
                mArea3List = null;

                mSelArea4 = null;
                mTvArea4.setText("");
                mArea4List = null;

                mSelArea5 = null;
                mTvArea5.setText("");
                mArea5List = null;
            })
                    .setTitleText("请选择区域")
                    .isDialog(true)
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
            mArea2Picker.setPicker(mArea2List);
            mArea2Picker.show();
        }
    }

    /**
     * area3
     */
    private void onShowArea3() {
        if (null == mArea3List || mArea3List.size() <= 0) {
            if (mSelArea2 == null) {
                ToastUtils.show("请选择盟市");
            } else {
                getAreaList(3, mSelArea2.getAreaId());
            }
        } else {
            mArea3Picker = new OptionsPickerBuilder(context, (options1, options2, options3, v) -> {
                AreaBean bean = mArea3List.get(options1);
                mTvArea3.setText(bean.getAreaName());
                mSelArea3 = bean;

                mSelArea4 = null;
                mTvArea4.setText("");
                mArea4List = null;

                mSelArea5 = null;
                mTvArea5.setText("");
                mArea5List = null;
            })
                    .setTitleText("请选择区域")
                    .isDialog(true)
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
            mArea3Picker.setPicker(mArea3List);
            mArea3Picker.show();
        }
    }

    /**
     * area4
     */
    private void onShowArea4() {
        if (null == mArea4List || mArea4List.size() <= 0) {
            if (mSelArea3 == null) {
                ToastUtils.show("请选择旗县区");
            } else {
                getAreaList(4, mSelArea3.getAreaId());
            }
        } else {
            mArea4Picker = new OptionsPickerBuilder(context, (options1, options2, options3, v) -> {
                AreaBean bean = mArea4List.get(options1);
                mTvArea4.setText(bean.getAreaName());
                mSelArea4 = bean;
                mSelArea5 = null;
                mTvArea5.setText("");
                mArea5List = null;
            })
                    .setTitleText("请选择区域")
                    .isDialog(true)
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
            mArea4Picker.setPicker(mArea4List);
            mArea4Picker.show();
        }
    }

    /**
     * area5
     */
    private void onShowArea5() {
        if (null == mArea5List || mArea5List.size() <= 0) {
            if (mSelArea4 == null) {
                ToastUtils.show("请选择乡镇街道");
            } else {
                getAreaList(5, mSelArea4.getAreaId());
            }
        } else {
            mArea5Picker = new OptionsPickerBuilder(context, (options1, options2, options3, v) -> {
                AreaBean bean = mArea5List.get(options1);
                mTvArea5.setText(bean.getAreaName());
                mSelArea5 = bean;
            })
                    .setTitleText("请选择区域")
                    .isDialog(true)
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
            mArea5Picker.setPicker(mArea5List);
            mArea5Picker.show();
        }
    }

    private void getAreaList(int type, String id) {
        ProgressDialog dialog = UIUtil.initDialog(context, "获取中...");
        dialog.show();
        RetrofitManager.getInstance()
                .create(BaseApiService.class)
                .getAreaListByPid(id, UserLgUtils.getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<AreaBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(List<AreaBean> areaListBeans) {
                        dialog.dismiss();
                        if (null != areaListBeans && areaListBeans.size() > 0) {
                            switch (type) {
                                case 1: //area1
                                    mArea1List = areaListBeans;
                                    onShowArea1();
                                    break;
                                case 2://area2
                                    mArea2List = areaListBeans;
                                    onShowArea2();
                                    break;
                                case 3://area3
                                    mArea3List = areaListBeans;
                                    onShowArea3();
                                    break;
                                case 4://area4
                                    mArea4List = areaListBeans;
                                    onShowArea4();
                                    break;
                                case 5://area5
                                    mArea5List = areaListBeans;
                                    onShowArea5();
                                    break;
                            }
                        } else {
                            ToastUtils.show("暂无区域数据");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dialog.dismiss();
                        ToastUtils.show("获取区域失败");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void addOnChoseListener(OnChoseListener listener) {
        this.mListener = listener;
    }

    /**
     * 选择
     *
     * @param i
     */
    private void choseType(int i) {
        this.dismiss();
    }

    public interface OnChoseListener {
        void doConfirm(String names, String id, String code);
    }

    public static class DialogBuilder {
        private Context mContext;
        private boolean isCancelable;
        private boolean mIsBackable;
        private int mGravity = Gravity.BOTTOM;
        private OnChoseListener mListener;
        private boolean mIsShowOther;
        private boolean isDefault;

        public DialogBuilder(Context context) {
            this.mContext = context;
        }

        public DialogBuilder setIscancelable(boolean iscancelable) {
            this.isCancelable = iscancelable;
            return this;
        }

        public DialogBuilder setIsBackCancelable(boolean isBackCancelable) {
            this.mIsBackable = isBackCancelable;
            return this;
        }

        public DialogBuilder setShowLocation(int gravity) {
            this.mGravity = gravity;
            return this;
        }

        private boolean mIsShow;

        public DialogBuilder setIsShowFile(boolean isShowFile) {
            mIsShow = isShowFile;
            return this;
        }

        public DialogBuilder setIsShowOther(boolean isShow) {
            mIsShowOther = isShow;
            return this;
        }

        public DialogBuilder setDefault(boolean isDefault) {
            this.isDefault = isDefault;
            return this;
        }

        public AreaChooseDialog build() {
            return new AreaChooseDialog(this.mContext, this.isCancelable, this.mIsBackable, this.mGravity, mIsShow, mIsShowOther, isDefault);
        }
    }
}