package com.sheep.gamegroup.view.fragment;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.kfzs.duanduan.utils.ApkUtils;
import com.sheep.gamegroup.model.entity.AgentEntity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.MessageUnReadEntity;
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.LogUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.activity.ActMsg;
import com.sheep.gamegroup.view.activity.PersonalCenterAct;
import com.sheep.gamegroup.view.dialog.DialogShare;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;
import com.sheep.jiuyan.samllsheep.utils.G;

import org.afinal.simplecache.ACache;

import java.util.Locale;

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

import static com.sheep.gamegroup.util.UMConfigUtils.Event.USER_AGENT;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.USER_FAQ;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.USER_SHARE;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.USER_UPGRADE;
import static com.sheep.gamegroup.util.ViewUtil.backgroundAlpha;

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

public class FgtPersonalCenter extends BaseFragment {
    @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;
    @BindView(R.id.proxy_service_layout)
    View proxy_service_layout;
    @BindView(R.id.proxy_service_layout_line)
    View proxy_service_layout_line;
    @BindView(R.id.version_item_tv)
    TextView version_item_tv;
    @BindView(R.id.personal_center_version_new)
    View personal_center_version_new;
    @BindView(R.id.iv_redpackage)
    ImageView ivRedpackage;
    @BindView(R.id.ibtn_baseactivity_message)
    ImageView ivMessageIcon;
    @BindView(R.id.ibtn_baseactivity_right)
    View ibtn_baseactivity_right;
    @BindView(R.id.txt_baseactivity_title)
    View txt_baseactivity_title;
    @BindView(R.id.img_baseactivity_title)
    View img_baseactivity_title;

    public UserEntity userEntity;
    private String faqUrl;
    private String agentUrl;
    private Activity activity;

    @Override
    public int getLayoutId() {
        return R.layout.fgt_personalcenter_layout;
    }

    @Override
    public void onViewCreated() {
        activity = getActivity();
        ibtn_baseactivity_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Jump2View.getInstance().goSetting(activity, null);
            }
        });

        if (activity instanceof PersonalCenterAct) {
            txt_baseactivity_title.setVisibility(View.VISIBLE);
            img_baseactivity_title.setVisibility(View.VISIBLE);
            img_baseactivity_title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    activity.finish();
                }
            });
        } else {
            img_baseactivity_title.setVisibility(View.INVISIBLE);
            txt_baseactivity_title.setVisibility(View.INVISIBLE);
        }
    }

    private void initData() {
        //代理
        CommonUtil.getInstance().getAgencyState(activity, new Action1<BaseMessage>() {
            @Override
            public void call(BaseMessage baseMessage) {
                try {
                    if (baseMessage != null) {
                        AgentEntity agentEntity = baseMessage.getData(AgentEntity.class);
                        if (agentEntity != null && agentEntity.getIs_banned() == 0) {
                            //设置是否显示代理服务
                            proxy_service_layout_line.setVisibility(View.VISIBLE);
                            proxy_service_layout.setVisibility(View.VISIBLE);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        initUserInfo();
        String newVersionUrl = ACache.get(SheepApp.getInstance()).getAsString("version_url");
        personal_center_version_new.setVisibility(TextUtils.isEmpty(newVersionUrl) ? View.GONE : View.VISIBLE);
        String appVersionName = ApkUtils.getCurrentPkgVersionName(SheepApp.getInstance());
        version_item_tv.setText("小绵羊V");
        version_item_tv.append(appVersionName);
        getUnReadMessageCounts();
    }

    private void initUserInfo() {
        CommonUtil.getInstance().callActionWithUserInfo(new Action1<UserEntity>() {
            @Override
            public void call(UserEntity userEntity) {
                if(userEntity != null){
                    FgtPersonalCenter.this.userEntity = userEntity;
                    ivRedpackage.setVisibility(userEntity.isKfzsPackageUser() ? View.GONE : View.VISIBLE);
                    initWidget();
                }
            }
        });
    }

    private void initWidget() {
        personalcenter_item_price_tv.setText(String.format(Locale.CHINA, "%s\u0020元", userEntity.getBalance()));
        ViewUtil.setText(nameTv, userEntity.getNickname());
        sheepNumTv.setText(String.format(Locale.CHINA, "绵羊号：%s", userEntity.getInvitation_code()));
        GlideImageLoader.setAvatar(iconImgIv, userEntity.getAvatar(), Color.argb(128, 255, 255, 255));

    }

    /**
     * 获取是否有未读消息并更新图标
     */
    private void getUnReadMessageCounts() {
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .getMessageUnReadNum(DataUtil.getInstance().getUserId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        MessageUnReadEntity entity = baseMessage.getData(MessageUnReadEntity.class);
                        if (entity != null && entity.getNum() > 0) {
                            ivMessageIcon.setImageResource(R.mipmap.message_unread_icon);
                        } else {
                            ivMessageIcon.setImageResource(R.mipmap.message_read_icon);
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                    }
                });

    }


    /**
     * 兑换红包
     *
     * @param code ,邀请码
     */
    public void getRedPackage(String code, final PopupWindow popupWindow) {
        SheepApp.getInstance().getNetComponent().getApiService().exchangeRedPackage(code)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        LogUtil.logI("0------" + new Gson().toJson(baseMessage));
                        G.showToast(baseMessage.getMsg());
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        showRedPackageAfterInvitation(activity, getView(), baseMessage);
                        if (popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }

                    }
                });
    }


    /**
     * 邀请成功后在个人资料显示领红包弹窗
     *
     * @param mActivity 当前Activity
     */
    public void showRedPackageAfterInvitation(final Activity mActivity, View viewAnchor, BaseMessage baseMessage) {
        if (viewAnchor == null) {
            return;
        }
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_redpackage_after_invitation, null, false);
        TextView tvGetRedPackage = view.findViewById(R.id.tv_get_redpackage);
        TextView tvMoney = view.findViewById(R.id.tv_money);
        ImageView ivClose = view.findViewById(R.id.iv_close);
        final PopupWindow popupWindow = new PopupWindow(mActivity);
        popupWindow.setContentView(view);
        popupWindow.setAnimationStyle(R.style.Rising);
        popupWindow.setWidth(ActionBar.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ActionBar.LayoutParams.MATCH_PARENT);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        backgroundAlpha(0.7f, mActivity);
        try {
            popupWindow.showAtLocation(viewAnchor, Gravity.CENTER, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        popupWindow.setOnDismissListener(new ViewUtil.PopDismissListener(mActivity));
        tvMoney.setText("1");
        tvGetRedPackage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //   CommonUtil.getInstance().updateUserInfo(null);
                updateUserInfo(null);
                popupWindow.dismiss();
                ivRedpackage.setVisibility(View.GONE);
            }
        });
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                ivRedpackage.setVisibility(View.GONE);
            }
        });

    }

    public void updateUserInfo(final Action1<UserEntity> action1) {
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .getInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        if (action1 != null)
                            action1.call(null);

                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        UserEntity userEntity = baseMessage.getData(UserEntity.class);
                        if (userEntity != null) {
                            DataUtil.getInstance().setUserEntity(userEntity);
                        }
                        initUserInfo();
                        if (action1 != null)
                            action1.call(userEntity);
                    }
                });
    }

    @OnClick({R.id.icon_img_iv, R.id.account_detail_layout, R.id.personalcenter_price_layout,
            R.id.account_task_layout, R.id.proxy_service_layout, R.id.feedbook_layout,
            R.id.recommend_friend_layout, R.id.faq_layout, R.id.reservation_layout,
            R.id.version_layout, R.id.order_layout, R.id.proxy_game_account_layout,
            R.id.iv_redpackage, R.id.ibtn_baseactivity_message
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_baseactivity_message://消息
                startActivity(new Intent(activity, ActMsg.class));
                break;
            case R.id.iv_redpackage://邀请成功后有可领红包
                ViewUtil.changeRedPackage(activity, getView(), FgtPersonalCenter.this);
                break;
            case R.id.icon_img_iv://图片
                if (TestUtil.isTest()) {
                    TestUtil.test(activity);
                } else
                    Jump2View.getInstance().goPersionInfo(activity, null);
                break;
            case R.id.account_detail_layout://个人资料
                Jump2View.getInstance().goPersionInfo(activity, null);
                break;
            case R.id.personalcenter_price_layout://我的资产
                Jump2View.getInstance().goMyMoney(activity, null);
                break;
            case R.id.account_task_layout://任务记录
                Jump2View.getInstance().goAuditTastList(activity, null);
                break;
            case R.id.proxy_service_layout://代理
                CommonUtil.getInstance().initUrlConfigByNet("agenturl", new Action1<String>() {
                    @Override
                    public void call(String url) {
                        agentUrl = url;
                        if (!TextUtils.isEmpty(agentUrl))
                            Jump2View.getInstance().goWeb(activity, agentUrl, "代理服务");
                        else
                            G.showToast(R.string.loading_data);
                    }
                });
                USER_AGENT.onEvent();
                break;
            case R.id.faq_layout://FAQ帮助
                CommonUtil.getInstance().initUrlConfigByNet("faqurl", new Action1<String>() {
                    @Override
                    public void call(String url) {
                        faqUrl = url;
                        if (!TextUtils.isEmpty(faqUrl))
                            Jump2View.getInstance().goWeb(activity, faqUrl, "FAQ帮助");
                        else
                            Jump2View.getInstance().goWeb(activity, "http://smallstation.kfzs.com/h5_faq/#/faq", "FAQ帮助");
                    }
                });
                USER_FAQ.onEvent();
                break;
            case R.id.reservation_layout://游戏预约
                Jump2View.getInstance().goActReservation(activity);
                break;
            case R.id.feedbook_layout://意见反馈
                Jump2View.getInstance().goFeedbackAct(activity);
                break;
            case R.id.recommend_friend_layout://推荐给好友
                if (userEntity != null) {
                    ViewUtil.shareLink(activity, CommonUtil.getInstance().jointString(userEntity.getShareLink(DialogShare.OTHER), DialogShare.OTHER));
                }
                USER_SHARE.onEvent();
                break;
            case R.id.version_layout://版本更新
                SysAppUtil.showVersionInfo(activity, null);
                USER_UPGRADE.onEvent();
                break;
            case R.id.order_layout://订单管理
                Jump2View.getInstance().goGameTaskOrderList(activity);
                break;
            case R.id.proxy_game_account_layout://游戏账号
                Jump2View.getInstance().goGameAccount(activity, null);
                break;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser) {
            try {
                initData();
            } catch (Exception e) {
                e.printStackTrace();
                G.showToast(e.getMessage());
            }
        }
    }

    private boolean isFirstOnResume = true;//第一次onResume
    @Override
    public void onResume() {
        super.onResume();
        if(!isFirstOnResume) {
            try {
                initData();
            } catch (Exception e) {
                e.printStackTrace();
                G.showToast(e.getMessage());
            }
        }
        isFirstOnResume = false;
    }
}
