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.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
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.view.dialog.DialogShare;
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 butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.BIND_PHONE;
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_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_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;


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

    private Activity activity;

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

    @Override
    public void initListener() {

    }

    @BindView(R.id.personal_info_phone)
    TextView personal_info_phone;
    @BindView(R.id.personal_info_wx)
    TextView personal_info_wx;
    @BindView(R.id.personal_info_authentication)
    TextView personal_info_authentication;

    @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.mContext) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage.getMsg());
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if (baseMessage != null) {
                            CommonUtil.getInstance().getUserInfo(SheepApp.mContext);
                            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.mContext) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage.getMsg());
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if (baseMessage != null) {
                            CommonUtil.getInstance().getUserInfo(SheepApp.mContext);
                            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_wx_container,
            R.id.personal_info_authentication_container, R.id.llayout_sex, R.id.llayout_birthday})

    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.tv_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.tv_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_qr_container:
                ViewUtil.showQR(PersonalInfoAct.this, userEntity.getShareLink(DialogShare.OTHER));
                break;
            case R.id.personal_info_phone_container:   //跳转到绑定手机号
                Jump2View.getInstance().goBindPhone(activity, null);
                BIND_PHONE.onEvent();
                break;
            case R.id.personal_info_wx_container:  ////跳转到微信
                if (userEntity == null) {
                    G.showToast(R.string.loading_data);
                } else if (TextUtils.isEmpty(userEntity.getWx_openid())) {
                    Jump2View.getInstance().goNoBindWx(activity, ChangeWxOrTelAct.TYPE_NORMAL);
                } else {
                    G.showToast("您已经绑定微信");
                }
                BIND_WX.onEvent();
                break;
            case R.id.personal_info_authentication_container: ////跳转授权
                Jump2View.getInstance().goRealNameAuther(activity, userEntity, 0);
                break;
        }
    }

    @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.get(this).getNetComponent().getApiService().changeBaseInfo(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BaseMessage>() {
                    @Override
                    public void call(BaseMessage baseMessage) {
                        setLoaddingText("完成");
                        onGetNetImageUrl(url);
                        dismissLoaddingDialog();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(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());
        personal_info_code.setText(userEntity.getInvitation_code());

        GlideImageLoader.saveAndSetRqImage(personal_info_qr, userEntity.getShareLink(DialogShare.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_wx.setText("未绑定");
            } else {
                personal_info_wx.setText("");
            }
        } else {
            personal_info_wx.setText(userEntity.getWx_nickname());
        }

        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("认证中");
        }
    }

}
