package com.navinfo.outdoor.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.navinfo.outdoor.R;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.base.BaseActivity;
import com.navinfo.outdoor.bean.BankPhoneBean;
import com.navinfo.outdoor.bean.CityBean;
import com.navinfo.outdoor.bean.JsonBean;
import com.navinfo.outdoor.bean.UserBean;
import com.navinfo.outdoor.http.Callback;
import com.navinfo.outdoor.http.DialogCallback;
import com.navinfo.outdoor.http.HttpInterface;
import com.navinfo.outdoor.http.OkGoBuilder;
import com.navinfo.outdoor.util.GetJsonDataUtil;
import com.navinfo.outdoor.util.RegexUtil;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.tencent.mapsdk.internal.aaa.getContext;

/**
 * 用户资料
 */
public class UserActivity extends BaseActivity implements View.OnClickListener {
    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<CityBean>>> cityItems = new ArrayList<>();
    private Button btnGathering, btnAttestation;
    private ImageView ivUser;
    private TextView region;
    private EditText etPhone, etQq, etMailbox;
    private Button userSave;
    private LinearLayout llRegion;
    private String userqq;
    private String userphone;
    private String usermailbox;
    private String region_id;
    private SharedPreferences navInfo;
    private SharedPreferences.Editor navInfoEditor;


    @Override
    protected int getLayout() {
        return R.layout.activity_user;
    }

    @Override
    protected void initData() {
        super.initData();

    }

    @Override
    protected void initView() {
        super.initView();
        initJsonData();
        navInfo = getSharedPreferences(Constant.SHARED_PREFERENCES, Context.MODE_PRIVATE);
        navInfoEditor = getSharedPreferences(Constant.SHARED_PREFERENCES, Context.MODE_PRIVATE).edit();
        ivUser = findViewById(R.id.iv_user);
        ivUser.setOnClickListener(this::onClick);
        btnAttestation = findViewById(R.id.btn_attestations);
        btnAttestation.setOnClickListener(this::onClick);
        btnGathering = findViewById(R.id.btn_gathering);
        btnGathering.setOnClickListener(this::onClick);
        region = findViewById(R.id.region);
        region.setOnClickListener(this::onClick);
        llRegion = findViewById(R.id.ll_region);
        llRegion.setOnClickListener(this::onClick);
        etPhone = findViewById(R.id.et_phone);
        etPhone.setOnClickListener(this::onClick);
        etQq = findViewById(R.id.edit_qq);
        etQq.setOnClickListener(this::onClick);
        etMailbox = findViewById(R.id.edit_mailbox);
        etMailbox.setOnClickListener(this::onClick);
        userSave = findViewById(R.id.btn_save);
        userSave.setOnClickListener(this::onClick);
        if (Constant.MOBILE!=null){
            etPhone.setText(Constant.MOBILE);
        }
        if (Constant.QQ!=null){
            etQq.setText(Constant.QQ);
        }
        String regions = navInfo.getString("region", null);
        if (regions!=null){
            region.setText(regions);
        }
        if (Constant.AUDITSTATUS==1){
            btnAttestation.setText("已认证");
        }
        if (Constant.ID_NUMBER!=null){
            btnGathering.setText("已绑定");

        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_user:
                finish();
                break;
            case R.id.btn_gathering:
                if (Constant.AUDITSTATUS==-1){
                    Toast.makeText(getContext(), "请先实名认证", Toast.LENGTH_SHORT).show();
                }else if (Constant.AUDITSTATUS==1){//认证通过

                    Intent gatheringIntent = new Intent(this, FragmentManagement.class);
                    gatheringIntent.putExtra("tag", 24);
                    startActivity(gatheringIntent);
                }else if (Constant.AUDITSTATUS==0){
                    Toast.makeText(this, Constant.AUDITMSG+"", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_attestations:
                Intent attestationIntent = new Intent(this, FragmentManagement.class);
                attestationIntent.putExtra("tag", 25);
                startActivity(attestationIntent);
                break;
            case R.id.ll_region:
                showPickerView();
                break;
            case R.id.edit_qq:
                // qq();
                break;
            case R.id.edit_mailbox:

                break;
            case R.id.btn_save:
                if (Constant.ID_NUM==null){
                    Toast.makeText(this, "请先实名认证", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (Constant.ID_NUMBER==null){
                    Toast.makeText(this, "请先绑定银行卡", Toast.LENGTH_SHORT).show();

                }
                userphone = etPhone.getText().toString().trim();
                userqq = etQq.getText().toString().trim();
                usermailbox = etMailbox.getText().toString().trim();
                HttpParams httpParams = new HttpParams();
                httpParams.put("pid",Constant.USERID);
                long time = System.currentTimeMillis();
                httpParams.put("datetime", time);
                boolean isQQNum_matcher = userqq.matches("[1-9][0-9]{4,14}");
                // 邮箱匹配结果
                boolean isEmail_matcher = usermailbox.matches( "^[\\w-\\+]+(\\.[\\w]+)*@[\\w-]+(\\.[\\w]+)*(\\.[a-z]{2,})$");
                //&& userqq.length() < 11 && userqq.length() > 5
                if (TextUtils.isEmpty(userphone) || TextUtils.isEmpty(userqq) || TextUtils.isEmpty(usermailbox)|| TextUtils.isEmpty(region_id)) {
                    if (region_id == null || region_id.equals("")) {
                        Toast.makeText(this, "所在地区为空，请重新输入", Toast.LENGTH_SHORT).show();
                    return;
                    }else {
                        httpParams.put("regionId",region_id);
                    }

                    if (!RegexUtil.isPhone(userphone)) {
                        Toast.makeText(this, "手机号输入错误", Toast.LENGTH_SHORT).show();
                        return;
                    }else {
                        httpParams.put("mobile",userphone);
                    }
                    if (userqq.equals("")) {
                        if (!isQQNum_matcher) {
                            Toast.makeText(this, "QQ号输入错误", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        return;
                    }else {
                        httpParams.put("qq",userqq);
                    }
                    if (!usermailbox.equals("")){
                        if (!isEmail_matcher) {
                            Toast.makeText(this, "邮箱格式错误", Toast.LENGTH_SHORT).show();
                        }
                        return;
                    }else {
                       // httpParams.put("qq",userqq);
                    }
                }
                netWork(httpParams);
                break;
        }
    }

    private void netWork(HttpParams httpParams) {
        showLoadingDialog();
        OkGoBuilder.getInstance()
                .Builder(this)
                .url(HttpInterface.USER_UPDATE)
                .cls(UserBean.class)
                .token(Constant.ACCESS_TOKEN)
                .params(httpParams)
                .postRequest(new Callback<UserBean>() {
                    @Override
                    public void onSuccess(UserBean response, int id) {
                        dismissLoadingDialog();
                        Log.d("TAG", "onSuccess: " + response.toString() + "sssssssssssss");
                        if (response.getCode()==200) {
                            MessageDialog.show(UserActivity.this, "提示","是否保存", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                                @Override
                                public boolean onClick(BaseDialog baseDialog, View v) {
                                    navInfoEditor.putString("region",region.getText().toString());
                                    navInfoEditor.commit();
                                    finish();
                                    return false;
                                }
                            });
                        } else {
                            MessageDialog.show(UserActivity.this, "提示","是否保存",  "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                                @Override
                                public boolean onClick(BaseDialog baseDialog, View v) {
                                    return false;
                                }
                            });
                        }
                    }
                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Toast.makeText(UserActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onError: " + e.getMessage());
                    }
                });
    }


//    public static boolean isEmail(String email) {
//        if (null == email || "".equals(email)) return false;
//        Matcher m = compile.matcher(email);
//        return m.matches();
//    }

    private void showPickerView() {// 弹出选择器（省市区三级联动）
        OptionsPickerView pvOptions = new OptionsPickerBuilder(UserActivity.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) : "";
                region_id = cityItems.get(options1).get(options2).get(options3).getRegion_id();
                Toast.makeText(UserActivity.this, region_id, Toast.LENGTH_SHORT).show();
                String tx = opt1tx + " " + opt2tx + " " + opt3tx;
                region.setText(tx);
            }
        }).setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setTitleText("城市选择")//标题
                .setSubCalSize(18)//确定和取消文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.parseColor("#2196F3"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#2196F3"))//取消按钮文字颜色
                .setContentTextSize(18)//滚轮文字大小
                .setLabels("", "", "")//设置选择的三级单位
                .setCyclic(false, false, false)//循环与否
                .setSelectOptions(0, 0, 0)  //设置默认选中项
                .setOutSideCancelable(false)//点击外部dismiss default true
                .build();
        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    private void initJsonData() {//解析数据 （省市区三级联动）
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(UserActivity.this, "prov_city_county.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<CityBean>> city_AreaList = new ArrayList<>();//该省的所有地区列表（第三级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三级）

            for (int c = 0; c < jsonBean.get(i).getCitys().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCitys().get(c).getCity();
                CityList.add(CityName);//添加城市
                ArrayList<CityBean> AreaList = new ArrayList<>();//该城市的所有地区列表
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCitys().get(c).getCounties() == null
                        || jsonBean.get(i).getCitys().get(c).getCounties().size() == 0) {
                    AreaList.add(new CityBean("", ""));
                    City_AreaList.add("");
                } else {
                    for (int j = 0; j < jsonBean.get(i).getCitys().get(c).getCounties().size(); j++) {
                        AreaList.add(new CityBean(jsonBean.get(i).getCitys().get(c).getCounties().get(j).getName(), jsonBean.get(i).getCitys().get(c).getCounties().get(j).getRegion_id()));
                        City_AreaList.add(jsonBean.get(i).getCitys().get(c).getCounties().get(j).getName());
                    }

                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
                city_AreaList.add(AreaList);//添加该省所有地区数据的bean
            }

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

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
            cityItems.add(city_AreaList);
        }
    }

    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();
        }
        return detail;
    }


}
