package com.kfzs.duanduan.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.kfzs.duanduan.BaseCompatFragment;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.FriendAndAwardEntity;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.entity.WebviewEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.FastJsonUtils;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.MyDbManager;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.activity.PersonalCenterAct;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;

import org.xutils.ex.DbException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 个人中心
 * Created by ljy on 2018/5/8.
 */

public class FgtPersonalCenter extends BaseCompatFragment {
    @BindView(R.id.icon_img_iv)
    ImageView iconImgIv;
    @BindView(R.id.name_tv)
    TextView nameTv;
    @BindView(R.id.sheep_num_tv)
    TextView sheepNumTv;
    @BindView(R.id.personalcenter_item_price_tv)
    TextView personalcenter_item_price_tv;
    Unbinder unbinder;

    private UserEntity userEntitys;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.fgt_personalcenter_layout);

    }

    private void initData() {
        getShardData();
        try {
            userEntitys = MyDbManager.getInstance().dbFindUser();
        } catch (DbException e) {
            e.printStackTrace();
        }
        if(userEntitys != null){
            initWidget();
        }else {
            SheepApp.get(getActivity())
                    .getNetComponent()
                    .getApiService()
                    .getInfo()
                    .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) {
                            userEntitys = JSON.parseObject(JSONObject.toJSONString(baseMessage.getData()), UserEntity.class);
                            try {
                                MyDbManager.getInstance().saveOrUpdateUser(userEntitys);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            initWidget();
                        }
                    });

        }
    }

    private void initWidget(){

        personalcenter_item_price_tv.setText(userEntitys.getBalance()+" 元");
        nameTv.setText(userEntitys.getNickname() + "");//绵羊号：123456789
        sheepNumTv.setText("绵羊号：" + userEntitys.getInvitation_code());
        Glide.with(getActivity())
                .load(userEntitys.getAvatar()+"")
                .apply(new RequestOptions().circleCrop().placeholder(R.drawable.icon))
                .into(iconImgIv);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initData();
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.icon_img_iv, R.id.account_detail_layout, R.id.personalcenter_price_layout, R.id.account_safe_layout, R.id.account_task_layout, R.id.proxy_service_layout, R.id.abourt_us_layout, R.id.feedbook_layout, R.id.recommend_friend_layout, R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.icon_img_iv://图片
            case R.id.account_detail_layout://个人资料
                Jump2View.getInstance().goPersionInfo(getActivity(), userEntitys);
                break;
            case R.id.personalcenter_price_layout://我的资产
                Jump2View.getInstance().goMyMoney(getActivity(), null);
                break;
            case R.id.account_safe_layout:
                Jump2View.getInstance().goAccountAndSecurit(getActivity(), null);
                break;
            case R.id.account_task_layout://任务记录
                Jump2View.getInstance().goTaskList2View(getActivity(), null);
                break;
            case R.id.proxy_service_layout://代理
                G.showToast("敬请期待!");
                break;
            case R.id.abourt_us_layout://关于我们
                Jump2View.getInstance()
                        .goWebview(
                                getActivity(),
                                new WebviewEntity(
                                        1,
                                        "关于我们"));
                break;
            case R.id.feedbook_layout://意见反馈
                Jump2View.getInstance()
                        .goFeedbackAct(
                                getActivity());
                break;
            case R.id.recommend_friend_layout://推荐给好友
                if(Ety!= null){
                    ViewUtil.shareLink(getActivity(),Ety.getShare_link());
                }
                break;
            case R.id.tv_submit://注销
                CommonUtil.getInstance()
                        .loginOut((BaseActivity) getActivity());
                break;
        }
    }


    FriendAndAwardEntity Ety;

    /**
     * 获取分享数据
     */
    private void  getShardData(){
        SheepApp.get(getActivity()).getNetComponent().getApiService().FriendCountAndAward()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.mContext) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        showToast(baseMessage.getMsg());
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if(baseMessage!=null){
                            Ety = FastJsonUtils.toBean( JSONObject.toJSONString(baseMessage.getData()),FriendAndAwardEntity.class);
                        }else{
                            showToast("数据解析出错");
                        }

                    }
                });

    }

    @Override
    public void onResume() {
        super.onResume();
        try{
            initData();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
