package io.openim.android.demo.ui.user;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.ToastUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.openim.android.demo.R;
import io.openim.android.demo.databinding.ActivityPersonalInfoBinding;
import io.openim.android.demo.ui.main.EditTextActivity;
import io.openim.android.demo.vm.PersonalVM;
import io.openim.android.ouicore.base.BaseActivity;
import io.openim.android.ouicore.base.BaseApp;
import io.openim.android.ouicore.net.bage.GsonHel;
import io.openim.android.ouicore.utils.Common;
import io.openim.android.ouicore.utils.Constants;
import io.openim.android.ouicore.utils.RegexValid;
import io.openim.android.ouicore.utils.TimeUtil;
import io.openim.android.ouicore.widget.BottomPopDialog;
import io.openim.android.ouicore.widget.PhotographAlbumDialog;
import io.openim.android.sdk.OpenIMClient;
import io.openim.android.sdk.listener.OnFileUploadProgressListener;
import io.openim.android.sdk.models.PutArgs;

/**
 * 我的信息
 */
public class PersonalInfoActivity extends BaseActivity<PersonalVM, ActivityPersonalInfoBinding> {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        bindVM(PersonalVM.class);
        super.onCreate(savedInstanceState);
        bindViewDataBinding(ActivityPersonalInfoBinding.inflate(getLayoutInflater()));
        vm.getSelfUserInfo();
        initCustomTimePicker();
        initView();
        click();
    }

    private void click() {
        PhotographAlbumDialog albumDialog = new PhotographAlbumDialog(this);
        view.avatarLy.setOnClickListener(view -> {
            albumDialog.setOnSelectResultListener(path -> {
                vm.setFaceURL(path[0]);
                vm.waitDialog.show();

                PutArgs putArgs = new PutArgs(path[0]);
                OpenIMClient.getInstance().uploadFile(new OnFileUploadProgressListener() {
                    @Override
                    public void onError(int code, String error) {
                        vm.waitDialog.dismiss();
                        toast(error + code);
                    }

                    @Override
                    public void onProgress(long progress) {
                        vm.waitDialog.dismiss();
                    }

                    @Override
                    public void onSuccess(String s) {
                        Map<String, String> map = GsonHel.fromJson(s, HashMap.class);
                        s = map.get("url");
                        vm.setFaceURL(s);
                        Common.UIHandler.postDelayed(() -> vm.waitDialog.dismiss(), 1500);
                    }
                }, null, putArgs);
            });
            albumDialog.show();
        });
        view.nickNameLy.setOnClickListener(v ->
                nicknameLauncher.launch(new Intent(this, EditTextActivity.class)
                        .putExtra(EditTextActivity.INIT_TXT, vm.userInfo.val().getNickname())
                        .putExtra(EditTextActivity.MAX_LENGTH, 16)
                        .putExtra(EditTextActivity.TITLE,
                                getString(io.openim.android.ouicore.R.string.NickName))));
        view.genderLy.setOnClickListener(v -> {
            BottomPopDialog dialog = new BottomPopDialog(this);
            dialog.show();
            dialog.getMainView().menu3.setOnClickListener(v1 -> dialog.dismiss());
            dialog.getMainView().menu1.setText(io.openim.android.ouicore.R.string.male);
            dialog.getMainView().menu2.setText(io.openim.android.ouicore.R.string.girl);

            dialog.getMainView().menu1.setOnClickListener(v1 -> {
                vm.setGender(1);
                dialog.dismiss();
            });
            dialog.getMainView().menu2.setOnClickListener(v1 -> {
                vm.setGender(2);
                dialog.dismiss();
            });
        });
        view.birthdayLy.setOnClickListener(v -> {
//            TimePickerView pvTime = new TimePickerBuilder(this,
//                (date, v12) -> vm.setBirthday(date.getTime())).build();
//            pvTime.show(v);
            pvCustomTime.show(v);

        });
        view.email.setOnClickListener(v -> {
            emailLauncher.launch(new Intent(this, EditTextActivity.class)
                    .putExtra(EditTextActivity.INIT_TXT, "")
                    .putExtra(EditTextActivity.TIPS, "")
                    .putExtra(EditTextActivity.TITLE, getString(io.openim.android.ouicore.R.string.mail)));
        });
    }

    private final ActivityResultLauncher<Intent> nicknameLauncher =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
                if (result.getResultCode() != Activity.RESULT_OK) return;
                String resultStr = result.getData().getStringExtra(Constants.K_RESULT);
                vm.setNickname(resultStr);
            });
    private final ActivityResultLauncher<Intent> emailLauncher =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
                if (result.getResultCode() != Activity.RESULT_OK) return;
                String resultStr = result.getData().getStringExtra(Constants.K_RESULT);
                if (!RegexValid.isValidEmail(resultStr)) {
                    toast(BaseApp.inst().getString(io.openim.android.ouicore.R.string.email_tips));
                    return;
                }
                vm.setEmail(resultStr);
            });

    private void initView() {
        vm.userInfo.observe(this, v -> {
            if (null == v) return;
            view.avatar.load(v.getFaceURL(), v.getNickname());
            view.nickName.setText(v.getNickname());
            view.gender.setText(v.getGender() == 1 ? io.openim.android.ouicore.R.string.male :
                    io.openim.android.ouicore.R.string.girl);
            if (v.getBirth() > 0) {
                view.birthday.setText(TimeUtil.getTime(v.getBirth(),
                        TimeUtil.yearMonthDayFormat));
            }
            view.phoneNumTv.setText(v.getPhoneNumber());
            view.emailTV.setText(v.getEmail());
        });
    }

    private TimePickerView pvCustomTime;


    private void initCustomTimePicker() {
        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(1900, 1, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2100, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
//                btn_CustomTime.setText(getTime(date));
//                ToastUtils.showShort(date.getTime() + "");
                vm.setBirthday(date.getTime());
            }
        })

                /*.setType(TimePickerView.Type.ALL)//default is all
                .setCancelText("Cancel")
                .setSubmitText("Sure")
                .setContentTextSize(18)
                .setTitleSize(20)
                .setTitleText("Title")
                .setTitleColor(Color.BLACK)
               /*
                .setTextColorCenter(Color.LTGRAY)//设置选中项的颜色
                .setDividerColor(Color.TRANSPARENT)//设置分割线的颜色
                .setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
                .setTitleBgColor(Color.DKGRAY)//标题背景颜色 Night mode
                .setBgColor(Color.BLACK)//滚轮背景颜色 Night mode
                .setSubmitColor(Color.WHITE)
                .setCancelColor(Color.WHITE)*/
                /*.animGravity(Gravity.RIGHT)// default is center*/
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.birthday_picker_view, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
//                .setContentTextSize(18)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel(getString(io.openim.android.ouicore.R.string.new_4), getString(io.openim.android.ouicore.R.string.new_5), getString(io.openim.android.ouicore.R.string.new_6), "时", "分", "秒")
                .setLineSpacingMultiplier(3f)
                .setItemVisibleCount(5)
                .setTextXOffset(0, 0, 0, 0, 0, 0)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.TRANSPARENT)
                .build();
    }
}
