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.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

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.entity.UserTaskExistsNew;
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.ListUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.share.ShareLinkConfig;
import com.sheep.gamegroup.view.activity.ActMsg;
import com.sheep.gamegroup.view.activity.PersonalCenterAct;
import com.sheep.gamegroup.view.adapter.AdpUserCenterModule;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;
import com.sheep.jiuyan.samllsheep.bean.UserCenterModule;
import com.sheep.jiuyan.samllsheep.utils.G;

import org.afinal.simplecache.ACache;
import org.afinal.simplecache.ApiKey;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

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.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_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;
    @BindView(R.id.audit_activity)
    TextView audit_activity;
    @BindView(R.id.audit_success)
    TextView audit_success;
    @BindView(R.id.audit_failed)
    TextView audit_failed;
    @BindView(R.id.audit_activity_oval)
    View audit_activity_oval;
    @BindView(R.id.audit_success_oval)
    View audit_success_oval;
    @BindView(R.id.audit_failed_oval)
    View audit_failed_oval;
    @BindView(R.id.my_module_layout)
    LinearLayout moduleLayout;
    @BindView(R.id.my_module_list)
    RecyclerView moduleList;
    @BindView(R.id.fgt_person_center_my_focus_line)
    View fgt_person_center_my_focus_line;
    @BindView(R.id.fgt_person_center_my_focus)
    View fgt_person_center_my_focus;

    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();
    }

    @Override
    protected void initViewOnVisibleToUser() {
        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);
        }
        ViewUtil.setText(audit_activity, getString(R.string.audit_activity, ViewUtil.INDENT));
        ViewUtil.setVisibility(audit_activity_oval, false);
        ViewUtil.setText(audit_success, getString(R.string.audit_success, ViewUtil.INDENT));
        ViewUtil.setVisibility(audit_success_oval, false);
        ViewUtil.setText(audit_failed, getString(R.string.audit_failed, ViewUtil.INDENT));
        ViewUtil.setVisibility(audit_failed_oval, false);
        initUserModuleItemView();
        //是否显示我的关注
        ViewUtil.setVisibility(fgt_person_center_my_focus_line, !TestUtil.isLTVersion3_4_5());
        ViewUtil.setVisibility(fgt_person_center_my_focus, !TestUtil.isLTVersion3_4_5());
    }

    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);
        //获取未查看的任务成功或失败的记录
        SheepApp.getInstance().getNetComponent().getApiService().getUserTaskExistsNew()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        UserTaskExistsNew userTaskExistsNew = baseMessage.getData(UserTaskExistsNew.class);
                        if (userTaskExistsNew != null) {
                            ViewUtil.setText(audit_activity, getString(R.string.audit_activity, String.valueOf(userTaskExistsNew.getActivity_task_num())));
                            ViewUtil.setVisibility(audit_activity_oval, userTaskExistsNew.getActivity_new_num() > 0);
                            ViewUtil.setText(audit_success, getString(R.string.audit_success, String.valueOf(userTaskExistsNew.getSuccess_task_num())));
                            ViewUtil.setVisibility(audit_success_oval, userTaskExistsNew.getSuccess_new_num() > 0);
                            ViewUtil.setText(audit_failed, getString(R.string.audit_failed, String.valueOf(userTaskExistsNew.getFailed_task_num())));
                            ViewUtil.setVisibility(audit_failed_oval, userTaskExistsNew.getFailed_new_num() > 0);

                        }
                    }

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


    //用户中心模块数据
    private List<UserCenterModule> userCenterModuleList = ListUtil.emptyList();
    //初始化用户中心模块界面
    private void initUserModuleItemView() {
        GridLayoutManager manager = new GridLayoutManager(SheepApp.getInstance(), 4);
        moduleList.setHasFixedSize(true);
        moduleList.setNestedScrollingEnabled(false);
        moduleList.setLayoutManager(manager);
        moduleList.setAdapter(new AdpUserCenterModule(userCenterModuleList));
    }

    //通过缓存数据初始化用户中心模块列表
    private void initUserModuleItemByACache() {
        List<UserCenterModule> cacheList = DataUtil.getInstance().getCacheList(ApiKey.user_module, UserCenterModule.class);
        loadUserModuleList(cacheList);
    }

    //加载用户中心模块数据并刷新、设置显示状态
    private void loadUserModuleList(List<UserCenterModule> newList) {
        if (!ListUtil.isEmpty(newList)) {
            userCenterModuleList.clear();
            userCenterModuleList.addAll(newList);
            ViewUtil.notifyDataSetChanged(moduleList);
            ViewUtil.setVisibility(moduleLayout, true);
        } else {
            ViewUtil.setVisibility(moduleLayout, !userCenterModuleList.isEmpty());
        }
    }

    /**
     * 初始化用户中心模块列表
     */
    private void initUserModuleItem() {
        SheepApp.getInstance().getNetComponent().getApiService().getUserModule()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                            @Override
                            public void onNext(BaseMessage baseMessage) {
                                boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.user_module);
                                if (isNewData) {
                                    ArrayList<UserCenterModule> newList = baseMessage.getDataList(UserCenterModule.class);
                                    loadUserModuleList(newList);
                                }
                            }

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

    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));

    }

    /**
     * 兑换红包
     *
     * @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.audit_activity_cl, R.id.audit_success_cl, R.id.audit_failed_cl,
            R.id.iv_redpackage, R.id.fgt_person_center_my_focus
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.audit_activity_cl://审核中心
                Jump2View.getInstance().goAuditTastList(activity, FgtMainAudit.POSITION_ACTIVITY);
                break;
            case R.id.audit_success_cl://审核中心--审核成功
                Jump2View.getInstance().goAuditTastList(activity, FgtMainAudit.POSITION_SUCCESS);
                break;
            case R.id.audit_failed_cl://审核中心--审核失败
                Jump2View.getInstance().goAuditTastList(activity, FgtMainAudit.POSITION_FAILED);
                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, userEntity.getShareLink(ShareLinkConfig.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;
            case R.id.fgt_person_center_my_focus://我的关注
                Jump2View.getInstance().goActMyFocus();
                break;
        }
    }

    @Override
    public void initDataOnVisibleToUser() {
        try {
            initData();
        } catch (Exception e) {
            e.printStackTrace();
            G.showToast(e.getMessage());
        }
    }

}
