package com.sheep.gamegroup.view.activity;

import android.graphics.Paint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.entity.PunchAndSign;
import com.sheep.gamegroup.model.entity.PunchStarList;
import com.sheep.gamegroup.model.entity.PunchUser;
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.ListUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
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 java.util.List;
import java.util.Locale;

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

/**
 * Created by realicing on 2018/9/11.
 * realicing@sina.com
 * 打卡界面
 */
public class ActSignCard extends BaseActivity {
    @BindView(R.id.sign_card_tip)
    TextView sign_card_tip;
    @BindView(R.id.sign_card_total_bonus)
    TextView sign_card_total_bonus;
    @BindView(R.id.sign_card_total_people)
    TextView sign_card_total_people;
    @BindView(R.id.sign_card_success_people)
    TextView sign_card_success_people;
    @BindView(R.id.sign_card_fail_people)
    TextView sign_card_fail_people;
    @BindView(R.id.sign_card_award)
    TextView sign_card_award;
    @BindView(R.id.sign_card_join)
    TextView sign_card_join;
    @BindView(R.id.sign_card_time)
    TextView sign_card_time;
    @BindView(R.id.sign_card_title1)
    TextView sign_card_title1;
    @BindView(R.id.sign_card_title2)
    TextView sign_card_title2;
    @BindView(R.id.sign_card_users)
    RecyclerView sign_card_users;
    @BindView(R.id.sign_card_super_users)
    RecyclerView sign_card_super_users;
    private ActSignCard activity;
    @Override
    protected int getLayoutId() {
        return R.layout.act_sign_card;
    }

    @Override
    public void initView() {
        activity = this;
        TitleBarUtils
                .getInstance()
                .setShowOrHide(this, true)
                .setTitle(activity, "打卡挑战")
                .setTitleFinish(activity)
//                .setRightSecondBtn(activity, R.mipmap.question_black_img, new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("温馨提示").setBtnLeftText("我知道了")
//                                .setMsg("该栏目为日常活跃活动，收益可提现。"));
//                    }
//                })
                .setRightBtn(activity, "我的战绩", 0, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Jump2View.getInstance().goSignRecordAct(activity, null);
                    }
                });
        //加下划线
        sign_card_tip.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        if (DataUtil.getAsBoolean("isNotShowDialogSignCard", true)) {//没有记录显示过该对话框，就显示之
            DataUtil.putAsBoolean("isNotShowDialogSignCard", false);
            ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("活动说明").setBtnLeftText("我知道了")
                    .setMsgGravity(Gravity.START).setMsg("支付1元参与次日早起打卡挑战\n\n" +
                            "次日早起打卡成功瓜分奖池奖金\n\n" +
                            "次日未打卡或超过规定打卡时间则不可参与奖金瓜分\n\n" +
                            "早起打卡时间：7:00-9:00"));
        }
        ViewUtil.setDefaultText(sign_card_total_bonus);
        ViewUtil.setDefaultText(sign_card_total_people);
        ViewUtil.setDefaultText(sign_card_success_people);
        ViewUtil.setDefaultText(sign_card_fail_people);
        ViewUtil.setDefaultText(sign_card_award);
        ViewUtil.setDefaultText(sign_card_join);
    }

    @Override
    public void initListener() {
        sign_card_users.setLayoutManager(new GridLayoutManager(SheepApp.getInstance(), 8));
        sign_card_users.setNestedScrollingEnabled(false);
        sign_card_users.setAdapter(new AdbCommonRecycler<PunchUser>(SheepApp.getInstance(), userList) {
            @Override
            public int getViewIdByType(int type) {
                return R.layout.item_user;
            }

            @Override
            public void convert(ViewHolder holder, PunchUser user) {
                ImageView item_user_iv = holder.getView(R.id.item_user_iv);
                TextView item_user_tv = holder.getView(R.id.item_user_tv);
                if (user == null) {
                    ViewUtil.setDefaultText(item_user_tv);
                    GlideImageLoader.setAvatar(item_user_iv, null);
                } else {
                    ViewUtil.setText(item_user_tv, user.getNickname());
                    GlideImageLoader.setAvatar(item_user_iv, user.getAvatar());
                }
            }
        });
        sign_card_super_users.setLayoutManager(new GridLayoutManager(SheepApp.getInstance(), 3));
        sign_card_super_users.setHasFixedSize(true);
        sign_card_super_users.setNestedScrollingEnabled(false);
        sign_card_super_users.setAdapter(new AdbCommonRecycler<PunchUser>(SheepApp.getInstance(), superUserList) {
            @Override
            public int getViewIdByType(int type) {
                return R.layout.item_super_user;
            }

            @Override
            public void convert(ViewHolder holder, PunchUser user) {
                int position = holder.getAdapterPosition();
                ImageView item_super_user_bg1 = (ImageView) holder.itemView.findViewById(R.id.item_super_user_bg1);
                ImageView item_super_user_iv = (ImageView) holder.itemView.findViewById(R.id.item_super_user_iv);
                ImageView item_super_user_bg2 = (ImageView) holder.itemView.findViewById(R.id.item_super_user_bg2);
                TextView item_super_user_tv1 = (TextView) holder.itemView.findViewById(R.id.item_super_user_tv1);
                TextView item_super_user_tv2 = (TextView) holder.itemView.findViewById(R.id.item_super_user_tv2);
                TextView item_super_user_tv3 = (TextView) holder.itemView.findViewById(R.id.item_super_user_tv3);
                ViewUtil.setText(item_super_user_tv1, XING_TEXTS[position]);
                item_super_user_bg1.setImageResource(XING_BGS1[position]);
                item_super_user_bg2.setImageResource(XING_BGS2[position]);
                if (user == null) {
                    ViewUtil.setDefaultText(item_super_user_tv2);
                    ViewUtil.setDefaultText(item_super_user_tv3);
                    GlideImageLoader.setAvatar(item_super_user_iv, null);
                } else {
                    ViewUtil.setText(item_super_user_tv2, String.format(Locale.CHINA, "绵羊号%s", user.getInvitation_code()));
                    ViewUtil.setText(item_super_user_tv3, user.getDescText());
                    GlideImageLoader.setAvatar(item_super_user_iv, user.getAvatar());
                }
            }
        });
    }

    private final static String[] XING_TEXTS = {"早起之星", "挑战之星", "毅力之星"};
    private final static int[] XING_BGS1 = {R.drawable.yellow_bg1, R.drawable.bule_bg1, R.drawable.red_bg1};
    private final static int[] XING_BGS2 = {R.drawable.yellow_bg2, R.drawable.bule_bg2, R.drawable.red_bg2};
    private List<PunchUser> userList = ListUtil.emptyList();
    private List<PunchUser> superUserList = ListUtil.emptyList();
    private boolean isCanSignUp = false;//判断今日是否能报名 true可以 false不可以
    private int initCanSignUp = INIT;//是否已经初始化完成 isSignUp, -1 初始化状态 0 加载中 1 成功
    public static final int INIT = -2;
    public static final int LOADING = -1;
    public static final int SUCCESS = 0;
    //1未报名 2已打卡 3可以打卡 4已经过了时间 5活动暂未开始
    public static final int PUNCH_TYPE_NOT_SIGN_UP = 1;
    public static final int PUNCH_TYPE_HAD_PUNCH = 2;
    public static final int PUNCH_TYPE_CAN_PUNCH = 3;
    public static final int PUNCH_TYPE_OUT_TIME = 4;
    public static final int PUNCH_TYPE_NOT_START = 5;
    private int punchType = INIT;//1未报名 2已打卡 3可以打卡 4已经过了时间 5活动暂未开始

    @Override
    public void initData() {
        initPunchAndSignCount();
        initPunchStar();
        initCanSignUp();
        initPunchType();
        //暂时没有显示 今日参与打卡奖励
//        SheepApp.getInstance().getNetComponent().getApiService().getPunchAward()
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
//                    @Override
//                    public void onNext(BaseMessage baseMessage) {
//                    }
//
//                    @Override
//                    public void onError(BaseMessage baseMessage) {
//                    }
//                });
    }
    //初始化早起之星
    private void initPunchStar() {
        SheepApp.getInstance().getNetComponent().getApiService().getPunchStar()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        PunchStarList punchStarList = baseMessage.getData(PunchStarList.class);
                        superUserList.clear();
                        ListUtil.addAllItem(superUserList, punchStarList.getList());
                        sign_card_super_users.getAdapter().notifyDataSetChanged();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                    }
                });
    }
    private PunchAndSign punchAndSign;
    //初始化打卡数据
    private void initPunchAndSignCount() {
        SheepApp.getInstance().getNetComponent().getApiService().getPunchAndSignCount()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if(sign_card_users == null){
                            return;
                        }
                        punchAndSign = baseMessage.getData(PunchAndSign.class);
                        userList.clear();
                        if (ListUtil.isEmpty(punchAndSign.getAvatar())) {
                            userList.add(null);
                        } else {
                            ListUtil.addAll(userList, punchAndSign.getAvatar());
                        }
                        sign_card_users.setLayoutManager(new GridLayoutManager(SheepApp.getInstance(), userList.size()));
                        sign_card_users.getAdapter().notifyDataSetChanged();
                        ViewUtil.setText(sign_card_total_bonus, String.format(Locale.CHINA, "%s元", punchAndSign.getSign_up_count()));
                        ViewUtil.setText(sign_card_total_people, String.format(Locale.CHINA, "当前参与人数%s人", punchAndSign.getSign_up_count()));
                        ViewUtil.setText(sign_card_success_people, punchAndSign.getPunch_count());
                        ViewUtil.setText(sign_card_fail_people, punchAndSign.getNoPunch_count());
                        ViewUtil.setText(sign_card_award, punchAndSign.getTotal_award());
                        ViewUtil.setText(sign_card_title1, String.format(Locale.CHINA, "%s战况", punchAndSign.getDayText()));
                        ViewUtil.setText(sign_card_title2, String.format(Locale.CHINA, "%s之星", punchAndSign.getDayText()));
                        if((totalTime = punchAndSign.getCountdown()) > 0) {//有倒计时
                            handler.sendEmptyMessage(0);//开始计时
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        userList.clear();
                        userList.add(null);
                        if(sign_card_users != null)
                            sign_card_users.getAdapter().notifyDataSetChanged();
                    }
                });
    }

    private void initCanSignUp() {
        initCanSignUp = LOADING;
        SheepApp.getInstance().getNetComponent().getApiService().getPunchCanSignUp()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        initCanSignUp = SUCCESS;
                        isCanSignUp = baseMessage.getData(Boolean.class);
                        initBtnState();
                    }

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

    private void initPunchType() {
        punchType = LOADING;
        SheepApp.getInstance().getNetComponent().getApiService().getPunchCanpunch()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        punchType = baseMessage.getData(Integer.class);
                        initBtnState();
                    }

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

    @OnClick({R.id.sign_card_join, R.id.sign_card_tip, R.id.sign_card_look_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sign_card_join:
                参加打卡挑战();
                break;
            case R.id.sign_card_tip:
                显示活动说明();
                break;
            case R.id.sign_card_look_more:
                查看详细榜单();
                break;
        }
    }

    private void 查看详细榜单() {
        Jump2View.getInstance().goSignRankingsAct(activity, null);
    }

    private void 显示活动说明() {
        ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("早起也能赚钱了").setBtnLeftText("我知道了")
                .setMsgGravity(Gravity.START).setMsg("1、支付1元作为早起动力金参与早起打卡，放入早起打卡挑战奖池内。\n" +
                        "2、次日早上7:00-9:00时段为早起打卡时间，用户在此期间进入小绵羊点击打卡按钮则成功打卡成功打卡不仅能拿回您原来投入的1元动力金，还能瓜分当天所有打卡失败者的全部动力金。\n" +
                        "3、未在次日早上7:00-9:00内进行打卡视为打卡失败，打卡失败后您所投入的1元动力金将不予以退回，也不参与瓜分当天所有打卡失败者的全部动力金。\n" +
                        "4、奖金将会在当天9:00进行结算，于12小时内发放至你的账户。由于网络原因，部分用户可能出现到账不及时的情况，请与我们的客服联系（客服电话：4008-698-576）\n" +
                        "本活动最终解释权归橙风有量科技有限公司所有"));
    }

    private void 参加打卡挑战() {
        if (punchType == PUNCH_TYPE_CAN_PUNCH) {//可以打卡
            参加打卡();
        } else if (initCanSignUp == SUCCESS && isCanSignUp) {//可以报名
            参加报名();
        } else {
            ViewUtil.showMsgDialog(activity, "活动暂未开始，请于早上7点至9点来参与打卡");
        }
    }

    private void 参加打卡() {
        UMConfigUtils.Event.PUNCH_PUNCH.onEvent();
        SheepApp.getInstance().getNetComponent().getApiService().getPunch()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if ("OK".equals(baseMessage.getMsg())) {
                            ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("恭喜您").setMsg("打卡成功，活动结束后平分奖励会直接发放到个人账户中")
                                    .setBtnLeftText("好的").setBtnRightText("查看战绩")
                                    .setBtnRightOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            Jump2View.getInstance().goSignRecordAct(activity, null);
                                        }
                                    }));
                            punchType = PUNCH_TYPE_HAD_PUNCH;//1未报名 2已打卡 3可以打卡 4已经过了时间 5活动暂未开始
                            initPunchAndSignCount();//(刷新数据)获取可打卡和报名人数
                            initBtnState();
                        } else {
                            G.showToast(baseMessage);
                        }
                    }

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

    private void 参加报名() {
        UMConfigUtils.Event.PUNCH_SIGN_UP.onEvent();
        CommonUtil.getInstance().callActionWithUserInfo(new Action1<UserEntity>() {
            @Override
            public void call(UserEntity userEntity) {
                if (userEntity != null) {
                    if (NumberFormatUtils.parseFloat(userEntity.getBalance()) >= 1) {
                        SheepApp.getInstance().getNetComponent().getApiService().getPunchUp()
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                                    @Override
                                    public void onNext(BaseMessage baseMessage) {
                                        if ("OK".equals(baseMessage.getMsg())) {
                                            ViewUtil.showMsgDialog(activity, new DialogConfig().setMsg("记得明日7:00-9:00来参加打卡哦！").setTitle("恭喜你，报名成功").setBtnLeftText("设置闹铃提醒")
                                                    .setBtnLeftOnClickListener(new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View view) {
                                                            //跳转到系统闹钟
                                                            SysAppUtil.startAlermApp(activity, "小绵羊打卡任务", 7, 5);
                                                        }
                                                    }));
                                            isCanSignUp = false;
                                            initPunchType();
                                            initPunchAndSignCount();//(刷新数据)获取可打卡和报名人数
                                        } else {
                                            G.showToast(baseMessage);
                                        }
                                    }

                                    @Override
                                    public void onError(BaseMessage baseMessage) {
                                        G.showToast(baseMessage);
                                    }
                                });
                    } else {
                        ViewUtil.showMsgDialog(activity, new DialogConfig().setMsg("抱歉，你的余额不足，请先去充值再来参与打卡哦！").setBtnRightText("好的").setBtnLeftText("去充值")
                                .setBtnLeftOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        Jump2View.getInstance().goSignRechargeAct(activity, null);
                                    }
                                }));
                    }
                } else {
                    G.showToast(R.string.service_data_error);
                }
            }
        });
    }
    private Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0://UPDATE_TIME:
                    if(totalTime > 0 && !isCanSignUp) {
                        sign_card_time.setVisibility(View.VISIBLE);
                        sign_card_time.setText(String.format(Locale.CHINA, "%s后可打卡", TimeUtil.getHours(totalTime-- * 1000)));
                        sendEmptyMessageDelayed(msg.what, 1000L);
                    } else {
                        sign_card_time.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    };
    private long totalTime = INIT;
    private void initBtnState() {
        if (punchType == PUNCH_TYPE_CAN_PUNCH) {//可以打卡
            sign_card_join.setEnabled(true);
            sign_card_join.setText("立即打卡");
        } else if (initCanSignUp == SUCCESS && isCanSignUp) {//可以报名
            sign_card_join.setEnabled(true);
            sign_card_join.setText("参加打卡挑战");
        } else {
            sign_card_join.setEnabled(false);
            sign_card_join.setText("已参与");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(0);
        handler = null;
    }
}
