package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
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.di.components.DaggerSignCardComponent;
import com.sheep.gamegroup.di.modules.SignCardModule;
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.UserEntity;
import com.sheep.gamegroup.presenter.SignCardContract;
import com.sheep.gamegroup.presenter.SignCardPresenter;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.util.ViewUtil;
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.Calendar;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 每日打卡
 */

public class SignCardAct extends BaseActivity implements SignCardContract.View {

    Activity activity;
    @Inject
    SignCardPresenter presenter;
    @BindView(R.id.sign_tv_kpf)
    TextView signTvKpf;
    @BindView(R.id.sign_tv_ljdk)
    TextView signTvLjdk;
    @BindView(R.id.sign_tv_jrcyrs)
    TextView signTvJrcyrs;//今日打卡人数
    @BindView(R.id.sign_tv_jrbmrs)
    TextView signTvJrbmrs;//今日报名人数
    @BindView(R.id.sign_tv_dkjl)
    TextView signTvDkjl;
    @BindView(R.id.sign_tv_mrcyrs)
    TextView signTvMrcyrs;
    @BindView(R.id.sign_tv_yybm)
    TextView signTvYybm;
    @BindView(R.id.sign_tv_kf)
    TextView signTvKf;
    @BindView(R.id.sign_band_bg)
    ImageView sign_band_bg;

    private int punchType = 0;//打卡状态 //1未报名 2已打卡 3可以打卡 4已经过了时间 5活动暂未开始


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

    @Override
    public void initView() {
        activity = this;
        TitleBarUtils
                .getInstance()
                .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);
                    }
                });
        DaggerSignCardComponent.builder()
                .netComponent(SheepApp.getInstance().getNetComponent())
                .signCardModule(new SignCardModule(this))
                .build()
                .inject(this);
        GlideImageLoader.setImage(sign_band_bg, "http://cdngame.kuaifazs.com/sign_band_bg.png");

    }


    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        presenter.goPunchCanSignUp();
        presenter.goPunchCanpunch();
        presenter.goPunchAward();//获取可获得的奖励
        presenter.goPunchAndSignCount();//获取可打卡和报名人数
    }

    /**
     * 打卡返回
     *
     * @param o
     */
    @Override
    public void succSignPunch(BaseMessage o) {
//        {"code":200,"msg":"OK"}
        if ("OK".equals(o.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);
                        }
                    }));
            presenter.goPunchAndSignCount();//(刷新数据)获取可打卡和报名人数
            punchType = 2;//1未报名 2已打卡 3可以打卡 4已经过了时间 5活动暂未开始
            signTvLjdk.setEnabled(false);
            signTvLjdk.setText("已打卡");
        } else {
            G.showToast(o.getMsg());
            presenter.goPunchCanpunch();
        }
    }

    /**
     * 一元报名返回
     *
     * @param o
     */
    @Override
    public void succSignUp(BaseMessage o) {
//        {"code":200,"msg":"OK"}
        if ("OK".equals(o.getMsg())) {
            signTvYybm.setEnabled(false);
            signTvYybm.setText("已报名");
            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);
                        }
                    }));
            presenter.goPunchAndSignCount();//(刷新数据)获取可打卡和报名人数
        } else {
            G.showToast(o.getMsg());
            presenter.goPunchCanSignUp();
        }
    }

    /**
     * 可获得的奖励返回
     *
     * @param o
     */
    @Override
    public void succPunchAward(BaseMessage o) {
        String text = o.getData().toString();
        float award = 0;
        try {
            award = o.getData(Float.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        if (TextUtils.isEmpty(text) || award <= 0 || hour < 9) {
            signTvDkjl.setText("系统计算中");
        } else {
            signTvDkjl.setText(getString(R.string.sign_jppj, o.getData().toString()));//平分的金额
            signTvDkjl.setTextColor(0xffff0006);
        }
    }

    /**
     * 获取是否可以打卡
     * 1未报名 2已打卡 3可以打卡,4 超出打卡时间
     *
     * @param o
     */
    @Override
    public void succPunchCanpunch(BaseMessage o) {
        punchType = o.getData(Integer.class);
        if (punchType == 2) {//1未报名 2已打卡 3可以打卡 4已经过了时间 5活动暂未开始
            signTvLjdk.setEnabled(false);
            signTvLjdk.setText("已打卡");
        } else {
            signTvLjdk.setEnabled(true);
        }
    }


    /**
     * 判断今日是否能报名
     * true可以 false不可以
     *
     * @param o
     */
    @Override
    public void succPunchCanSignUp(BaseMessage o) {
        boolean isSignUp = o.getData(Boolean.class);
        signTvYybm.setEnabled(isSignUp);
        signTvYybm.setText(isSignUp ? "一元报名" : "已报名");
    }

    /**
     * 获取可打卡和报名人数
     *
     * @param o
     */
    @Override
    public void succPunchAndSignCount(BaseMessage o) {
        PunchAndSign punchAndSign = o.getData(PunchAndSign.class);
        signTvJrcyrs.setText(String.format(getString(R.string.sign_number), punchAndSign.getPunch_count()));
        signTvJrbmrs.setText(
                String.format(
                        getString(R.string.sign_number1
                        ),
                        punchAndSign.getSign_up_count()
                )
        );

        signTvKpf.setText(getSpannableString(punchAndSign.getTotal_award()));//今日可分
        signTvMrcyrs.setText(getSpannableString(punchAndSign.getSign_up_count()));//明日可分
    }

    @Override
    public void failRequest(BaseMessage o) {
        G.showToast(o.getMsg());
    }

    @OnClick({R.id.sign_tv_ljdk, R.id.sign_tv_yybm, R.id.sign_tv_kf})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sign_tv_ljdk://打卡
                tryPunch();
                break;
            case R.id.sign_tv_yybm://一元报名
                trySignUp();
                break;
            case R.id.sign_tv_kf:
                G.showToast("028-8888888");
                break;
        }
    }

    private UserEntity userEntity;

    private void trySignUp() {
        UMConfigUtils.Event.PUNCH_PUNCH.onEvent();
        if (userEntity == null) {
            userEntity = DataUtil.getInstance().getUserEntity();
        }
        if (userEntity == null || TextUtils.isEmpty(userEntity.getBalance())) {
            G.showToast(R.string.unknown_error);
        } else if (NumberFormatUtils.parseFloat(userEntity.getBalance()) >= 1) {
            presenter.goSignUp();
        } else {
            ViewUtil.showMsgDialog(activity, new DialogConfig().setMsg("抱歉，你的余额不足，请先去充值再来参与打卡哦！").setBtnRightText("好的").setBtnLeftText("去充值")
                    .setBtnLeftOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Jump2View.getInstance().goSignRechargeAct(activity, null);
                        }
                    }));
        }
    }

    private void tryPunch() {
        UMConfigUtils.Event.PUNCH_SIGN_UP.onEvent();
        switch (punchType) {//1未报名 2已打卡 3可以打卡 4已经过了时间 5活动暂未开始
            case 1:
                ViewUtil.showMsgDialog(activity, "您昨日未报名，无法获取今日打卡资格，先去报名吧！");//未报名
                break;
            case 2:
                ViewUtil.showMsgDialog(activity, "您已经打卡，活动结束后平分奖励会直接发放到个人账户中");
                break;
            case 3:
                presenter.goSignPunch();
                break;
            case 4:
                ViewUtil.showMsgDialog(activity, "今日打卡活动已结束，请先去报名，明日再来哦！");
                break;
            case 5:
                ViewUtil.showMsgDialog(activity, "活动暂未开始，请于早上7点至9点来参与打卡");
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.ECLAIR)
    private SpannableString getSpannableString(String price) {
        String text = String.format(getString(R.string.x_yuan), price);
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new AbsoluteSizeSpan(14, true), text.length() - 1, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

}
