package com.cooleshow.base.ui.activity.set;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.cooleshow.base.R;
import com.cooleshow.base.bean.AddressBean;
import com.cooleshow.base.bean.JsonBean;
import com.cooleshow.base.bean.request.EditAddressEntry;
import com.cooleshow.base.constanst.EditAddressContract;
import com.cooleshow.base.databinding.ActivityEditAddressBinding;
import com.cooleshow.base.presenter.EditAddressPresenter;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.GetJsonDataUtil;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.google.gson.Gson;

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

import java.util.ArrayList;
import java.util.List;

/**
 * 创建日期：2022/5/18 9:47
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.BaseCenter.MINE_EDIT_ADDRESS)
public class EditAddressActivity extends BaseMVPActivity<ActivityEditAddressBinding, EditAddressPresenter> implements EditAddressContract.EditAddressView, View.OnClickListener {

    private String province;//省
    private String city;//市
    private String region;//区
    private boolean isDefaultAddress = true;
    private int id;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }


    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.im_set_default) {
            isDefaultAddress = !isDefaultAddress;
            if (isDefaultAddress) {
                viewBinding.imSetDefault.setImageResource(R.drawable.icon_switch_open);
            } else {
                viewBinding.imSetDefault.setImageResource(R.drawable.icon_switch_off);
            }
        } else if (viewId == R.id.tv_district_detail) {
            if (isLoaded) {
                showPickerView();
            } else {
                ToastUtil.getInstance().showShort("数据加载中，请稍后重试！");
            }
        } else if (viewId == R.id.tv_save) {
            String name = viewBinding.etName.getText().toString().trim();
            if (TextUtils.isEmpty(name)) {
                ToastUtil.getInstance().showShort("请输入姓名");
                return;
            }
            String phoneNumber = viewBinding.etPhone.getText().toString().trim();
            if (TextUtils.isEmpty(phoneNumber)) {
                ToastUtil.getInstance().showShort("请输入收件人电话号码");
                return;
            }
            if (phoneNumber.length() != 11) {
                ToastUtil.getInstance().showShort("请输入正确电话号码");
                return;
            }
            if (TextUtils.isEmpty(province)) {
                ToastUtil.getInstance().showShort("请选择所在地区");
                return;
            }
            String detailAddress = viewBinding.etDetailAddress.getText().toString().trim();
            if (TextUtils.isEmpty(detailAddress)) {
                ToastUtil.getInstance().showShort("请输入详细地址");
                return;
            }
            EditAddressEntry entry = new EditAddressEntry();
            entry.name = name;
            entry.phoneNumber = phoneNumber;
            entry.province = province;
            entry.city = city;
            entry.region = region;
            entry.detailAddress = detailAddress;
            if (isDefaultAddress) {
                entry.defaultStatus = 1;
            } else {
                entry.defaultStatus = 0;
            }
            if (isAdd) {
                presenter.createNewAddress(entry);
            } else {
                presenter.updateAddress(id, entry);
            }
        }
    }

    @Autowired(name = "isAdd")
    boolean isAdd;

    @Autowired(name = "bundle")
    Bundle myBundle;


    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "编辑地址");
        viewBinding.tvSave.setOnClickListener(this);
        viewBinding.imSetDefault.setOnClickListener(this);
        viewBinding.tvDistrictDetail.setOnClickListener(this);
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        if (null != myBundle) {
            AddressBean addressBean = (AddressBean) myBundle.getSerializable("AddressBean");
            viewBinding.etName.setText(addressBean.name);
            viewBinding.etPhone.setText(addressBean.phoneNumber);
            if (!TextUtils.isEmpty(addressBean.province)) {
                province = addressBean.province;
                city = addressBean.city;
                region = addressBean.region;
                viewBinding.tvDistrictDetail.setText(addressBean.province + addressBean.city + addressBean.region);
                viewBinding.tvDistrictDetail.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_1a1a1a));
            }
            viewBinding.etDetailAddress.setText(addressBean.detailAddress);
            id = addressBean.id;
            isDefaultAddress = addressBean.defaultStatus == 1;//是否是默认地址
            if (addressBean.defaultStatus == 1) {
                viewBinding.imSetDefault.setImageResource(R.drawable.icon_switch_open);
            } else {
                viewBinding.imSetDefault.setImageResource(R.drawable.icon_switch_off);
            }
        }
    }

    @Override
    protected ActivityEditAddressBinding getLayoutView() {
        return ActivityEditAddressBinding.inflate(getLayoutInflater());
    }

    @Override
    protected EditAddressPresenter createPresenter() {
        return new EditAddressPresenter();
    }

    @Override
    public void createNewAddressSuccess(Object object) {
        finish();
    }


    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private static boolean isLoaded = false;
    private OptionsPickerView pvOptions;

    private void showPickerView() {// 弹出选择器

        pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + opt2tx + opt3tx;
                province = opt1tx;
                city = opt2tx;
                region = opt3tx;
                viewBinding.tvDistrictDetail.setText(tx);
                viewBinding.tvDistrictDetail.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_1a1a1a));
            }
        })
                .setLayoutRes(R.layout.pickerview_address_layout, v -> {
                    //自定义布局中的控件初始化及事件处理
                    final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                    TextView ivCancel = (TextView) v.findViewById(R.id.tv_cancel);
                    tvSubmit.setOnClickListener(v12 -> {
                        pvOptions.returnData();
                        pvOptions.dismiss();
                    });
                    ivCancel.setOnClickListener(v1 -> pvOptions.dismiss());

                })
                .isDialog(false)//是否显示为对话框样式
                .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();

    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        Log.e("asdkjhakdsfs", "Begin Parse Data");
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    Log.e("asdkjhakdsfs", "Parse Succeed");
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Log.e("asdkjhakdsfs", "Parse Failed");
                    break;
            }
        }
    };


}
