package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.sheep.gamegroup.absBase.AbsChooseImageActivity;
import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.module.login.ReLoginNameAct;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.share.ShareLinkConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.BIND_PHONE;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.BIND_QQ;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.BIND_TX_WX;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.BIND_WX;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.USER_INFO_AVATAR;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.USER_INFO_LOGINNAME;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.USER_INFO_NAME;


/**
 * Created by Administrator on 2018/3/16.
 */

public class PersonalInfoAct extends AbsChooseImageActivity {

    UserEntity userEntity;
    @BindView(R.id.personal_info_name)
    TextView personal_info_name;
    @BindView(R.id.personal_info_loginname)
    TextView personal_info_loginname;
    @BindView(R.id.personal_info_code)
    TextView personal_info_code;
    @BindView(R.id.personal_info_qr)
    ImageView personal_info_qr;

    @BindView(R.id.personal_info_avatar)
    ImageView personal_info_avatar;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.personal_info_phone)
    TextView personal_info_phone;
    @BindView(R.id.personal_info_bind_tx_wx)
    TextView personal_info_bind_tx_wx;
    @BindView(R.id.personal_info_bind_qq)
    TextView personal_info_bind_qq;
    @BindView(R.id.personal_info_bind_wx)
    TextView personal_info_bind_wx;
    @BindView(R.id.personal_info_authentication)
    TextView personal_info_authentication;


    @Override
    protected int getLayoutId() {
        return R.layout.xpersion_info_act_layout;
    }

    private Activity activity;

    @Override
    public void initView() {
        activity = this;
        setShowCamera(false);
        TitleBarUtils
                .getInstance()
                .setShowOrHide(this, true)
                .setTitle(this, "个人资料")
                .setTitleFinish(this);
    }

    @Override
    public void initListener() {

    }


    @Override
    public void initData() {
        if (userEntity == null) {
            userEntity = DataUtil.getInstance().getUserEntity();
        }
        if (userEntity != null) {
            loadUserInfo();
        }

    }

    /**
     * 上传性别
     *
     * @param sex         ,
     * @param popupWindow ,
     */
    public void upLoadSex(final int sex, final PopupWindow popupWindow) {
        JSONObject j = new JSONObject();
        j.put("gender", sex);
        SheepApp.getInstance().getNetComponent().getApiService().changeBaseInfo(j)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage.getMsg());
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if (baseMessage != null) {
                            CommonUtil.getInstance().getUserInfo(SheepApp.getInstance());
                            popupWindow.dismiss();
                            tvSex.setText(sex == 1 ? "男" : "女");
                            G.showToast("修改成功！");
                        } else {
                            G.showToast("修改失败！");
                        }

                    }
                });
    }

    public void upLoadBirthday(final String birthday) {
        JSONObject j = new JSONObject();
        j.put("birthday", birthday + "T00:00:00Z");
        SheepApp.getInstance().getNetComponent().getApiService().changeBaseInfo(j)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage.getMsg());
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if (baseMessage != null) {
                            CommonUtil.getInstance().getUserInfo(SheepApp.getInstance());
                            G.showToast("修改成功！");
                        } else {
                            G.showToast("修改失败！");
                        }

                    }
                });
    }

    @OnClick({R.id.personal_info_avatar_container, R.id.personal_info_name_container, R.id.personal_info_qr_container,
            R.id.personal_info_phone_container, R.id.personal_info_bind_tx_wx_container,
            R.id.personal_info_bind_qq_container, R.id.personal_info_bind_wx_container,
            R.id.personal_info_authentication_container, R.id.llayout_birthday,
            R.id.personal_info_loginname_container})

    public void onClick(View view) {
        if (userEntity == null) {
            G.showToast(R.string.loading_data);
            return;
        }
        switch (view.getId()) {
//            case R.id.llayout_sex://用户性别
//                ViewUtil.choiceSex(PersonalInfoAct.this, getCurrentFocus());
//                break;
            case R.id.llayout_birthday://用户生日
                ViewUtil.showDateDialog(PersonalInfoAct.this, tvBirthday, TextUtils.isEmpty(userEntity.getBirthday()) ? "1990-01-01" : userEntity.getBirthday());
                break;
            case R.id.personal_info_avatar_container://头像
                showChooseDialog();
                USER_INFO_AVATAR.onEvent();
                break;
            case R.id.personal_info_name_container:
                Intent i = new Intent(PersonalInfoAct.this, ReNameActivity.class);
                i.putExtra("name", userEntity.getNickname());
                startActivity(i);
                USER_INFO_NAME.onEvent();
                break;
            case R.id.personal_info_loginname_container:
                if (userEntity.getSet_password() == 0) {
                    Intent intent = new Intent(PersonalInfoAct.this, ReLoginNameAct.class);
                    intent.putExtra("name", userEntity.getUser_name());
                    startActivity(intent);
                    USER_INFO_LOGINNAME.onEvent();
                } else {
                    G.shortToast("设置登录密码后不可修改登录名");
                }
                break;
            case R.id.personal_info_qr_container:
                ViewUtil.showQR(PersonalInfoAct.this, userEntity.getShareLink(ShareLinkConfig.OTHER));
                break;
            case R.id.personal_info_phone_container:   //跳转到绑定手机号
                Jump2View.getInstance().goBindPhone(activity, null);
                BIND_PHONE.onEvent();
                break;
            case R.id.personal_info_bind_tx_wx_container:  //跳转到绑定提现微信号的界面
                CommonUtil.getInstance().callActionWithUserInfo(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {
                        if (userEntity == null) {
                            G.showToast(R.string.error_data);
                        } else if (TextUtils.isEmpty(userEntity.getWx_openid())) {
                            Jump2View.getInstance().goNoBindWx(activity, ChangeWxOrTelAct.TYPE_NORMAL);
                        } else {
                            G.showToast("您已经绑定微信");
                        }
                    }
                });
                BIND_TX_WX.onEvent();
                break;
            case R.id.personal_info_bind_qq_container:  //跳转到验证手机号并绑定qq的界面
                CommonUtil.getInstance().callActionWithUserInfo(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {
                        if (userEntity == null) {
                            G.showToast(R.string.error_data);
                        } else if (!userEntity.isBindQQ()) {
                            bindQQ();
                        } else {
                            Jump2View.getInstance().goBindThird(activity, ActModifyThird.THIRD_TYPE_QQ);
                        }
                    }
                });
                BIND_QQ.onEvent();
                break;
            case R.id.personal_info_bind_wx_container:  //跳转到验证手机号并绑定微信的界面
                CommonUtil.getInstance().callActionWithUserInfo(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {
                        if (userEntity == null) {
                            G.showToast(R.string.error_data);
                        } else if (!userEntity.isBindWx()) {
                            bindWX();
                        } else {
                            Jump2View.getInstance().goBindThird(activity, ActModifyThird.THIRD_TYPE_WX);
                        }
                    }
                });
                BIND_WX.onEvent();
                break;
            case R.id.personal_info_authentication_container: ////跳转授权
                Jump2View.getInstance().goRealNameAuther(activity, userEntity, 0);
                break;
        }
    }

    private void bindQQ() {
        UMShareAPI.get(this).doOauthVerify(this, SHARE_MEDIA.QQ, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
                showProgress();
            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
                bindThird("qzone", data.get("access_token"), data.get("openid"));
            }

            @Override
            public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                G.showToast("QQ授权失败  请检查网络是否正常");
                hideProgress();
            }

            @Override
            public void onCancel(SHARE_MEDIA platform, int action) {
                G.showToast("您取消了QQ授权");
                hideProgress();
            }
        });
    }

    private void bindWX() {
        UMShareAPI.get(this).deleteOauth(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                UMShareAPI.get(activity).doOauthVerify(activity, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
                    @Override
                    public void onStart(SHARE_MEDIA platform) {
                        showProgress();
                    }

                    @Override
                    public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
                        bindThird("wechat", data.get("access_token"), data.get("openid"));
                    }

                    @Override
                    public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                        G.showToast("微信授权失败  请检查网络是否正常");
                        hideProgress();
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA platform, int action) {
                        G.showToast("您取消了微信授权");
                        hideProgress();
                    }
                });
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {

            }
        });

    }

    /**
     * access_token	string
     * open_id	string
     * platform	string
     * qzone, wechat
     * s_from	string
     * sheep, web_sheep
     *
     * @param access_token
     * @param openid
     */
    private void bindThird(String platform, String access_token, String openid) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("access_token", access_token);
        jsonObject.put("open_id", openid);
        jsonObject.put("platform", platform);
        jsonObject.put("s_from", "sheep");
        SheepApp.getInstance().getNetComponent().getApiService().bindThird(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        hideProgress();
                        CommonUtil.getInstance().updateUserInfo(new Action1<UserEntity>() {
                            @Override
                            public void call(UserEntity result) {
                                if (result != null) {
                                    userEntity = result;
                                    loadUserInfo();
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        hideProgress();
                        G.showToast(baseMessage);
                    }
                });
    }

    @Override
    protected void onNotGetImage(String msg) {
        G.showToast(msg);
    }

    @Override
    protected void onGetImage(String path) {
//        GlideImageLoader.setAvatar(personal_info_avatar, path);
    }

    @Override
    protected void onSetNetImageUrl(final String url) {
        setLoaddingText("更新中");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("avatar", url);
        SheepApp.getInstance().getNetComponent().getApiService().changeBaseInfo(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new AbsObserver<BaseMessage>() {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        setLoaddingText("完成");
                        onGetNetImageUrl(url);
                        dismissLoaddingDialog();
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        updateError("失败");
                    }
                });
    }

    @Override
    protected void onGetNetImageUrl(String url) {
        DataUtil.getInstance().setUserAvatar(url);
        GlideImageLoader.setAvatar(personal_info_avatar, url);
    }

    @Override
    protected void onResume() {
        super.onResume();
        UserEntity result = DataUtil.getInstance().getUserEntity();
        if (result == null) {
            CommonUtil.getInstance().updateUserInfo(new Action1<UserEntity>() {
                @Override
                public void call(UserEntity item) {
                    if (item != null) {
                        userEntity = item;
                        loadUserInfo();
                    }
                }
            });
        } else {
            userEntity = result;
            loadUserInfo();
        }
    }

    private void loadUserInfo() {
        tvSex.setText((userEntity.getGender() == 0) ? "点击设置" : (userEntity.getGender() == 1 ? "男" : "女"));
        tvBirthday.setText((userEntity.getBirthday().substring(0, 1)).equals("0") ? "点击设置" : userEntity.getBirthday().substring(0, 10));
        personal_info_name.setText(userEntity.getNickname());
        if(TextUtils.isEmpty(userEntity.getUser_name())){
            personal_info_loginname.setText("还未设置登录名");
        }else {
            personal_info_loginname.setText(userEntity.getUser_name());
        }
        personal_info_code.setText(userEntity.getInvitation_code());

        GlideImageLoader.saveAndSetRqImage(personal_info_qr, userEntity.getShareLink(ShareLinkConfig.FACE_TO_FACE), 90);
        GlideImageLoader.setAvatar(personal_info_avatar, userEntity.getAvatar());
        //账号与安全

        if (TextUtils.isEmpty(userEntity.getMobile())) {
            personal_info_phone.setText("未绑定");
        } else {
            personal_info_phone.setText(userEntity.getMobile());
            DataUtil.getInstance().setUserMobile(userEntity.getMobile());
        }

        if (TextUtils.isEmpty(userEntity.getWx_nickname())) {
            if (TextUtils.isEmpty(userEntity.getWx_openid())) {
                personal_info_bind_tx_wx.setText("未绑定");
            } else {
                personal_info_bind_tx_wx.setText("");
            }
        } else {
            personal_info_bind_tx_wx.setText(userEntity.getWx_nickname());
        }
        personal_info_bind_qq.setText(userEntity.isBindQQ() ? "去修改" : "去绑定");
        personal_info_bind_wx.setText(userEntity.isBindWx() ? "去修改" : "去绑定");

        boolean isId_number = TextUtils.isEmpty(userEntity.getId_number());
        boolean isRoalName = TextUtils.isEmpty(userEntity.getReal_name());
        if (isId_number && isRoalName) {
            personal_info_authentication.setText("未认证");
        } else if (!isId_number && !isRoalName) {
            personal_info_authentication.setText("已认证");
        } else {
            personal_info_authentication.setText("认证中");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
