package com.sheep.jiuyan.samllsheep.ui.activity;

import android.content.Intent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.BounceInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.sheep.gamegroup.absBase.BaseUMActivity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.Lp;
import com.sheep.gamegroup.model.entity.PunchAndSign;
import com.sheep.gamegroup.model.entity.RechargeLogEntity;
import com.sheep.gamegroup.model.entity.RobTask;
import com.sheep.gamegroup.model.entity.SheepSignResult;
import com.sheep.gamegroup.model.entity.UserSign;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataKey;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.share.ShareLinkConfig;
import com.sheep.gamegroup.util.viewHelper.LayoutParamsUtil;
import com.sheep.gamegroup.view.customview.ErasableTextView;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.jiuyan.samllsheep.ui.view.EggView;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Collections;
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;

/**
 * Created by: zhoujuncai.
 * Created date: 2018/10/31.
 * Description: 签到
 */
public class SignActivity extends BaseUMActivity {

    @BindView(R.id.eggs_view)
    EggView eggsView;
    @BindView(R.id.sign_info_text)
    TextView signInfoText;
    @BindView(R.id.sign_day_list)
    LinearLayout signDayList;
    @BindView(R.id.sign_now_but)
    TextView sign_now_but;
    @BindView(R.id.sign_card_num)
    TextView sign_card_num;
    @BindView(R.id.act_sign_ask_friend_tv)
    TextView act_sign_ask_friend_tv;
    @BindView(R.id.sheep_sign_machine)
    ImageView sheep_sign_machine;
    @BindView(R.id.sheep_sign_out)
    ImageView sheep_sign_out;
    @BindView(R.id.act_sign_eras_iv)
    ImageView act_sign_eras_iv;
    @BindView(R.id.act_sign_ask_friend_iv)
    ImageView act_sign_ask_friend_iv;
    @BindView(R.id.sheep_sign_rectangle)
    ImageView sheep_sign_rectangle;
    @BindView(R.id.sheep_sign_egg_rl)
    View sheep_sign_egg_rl;//中奖的球与文本的容器
    //    @BindView(R.id.sheep_sign_egg)
//    ImageView sheep_sign_egg;//中奖的球
    @BindView(R.id.sheep_sign_egg_msg)
    TextView sheep_sign_egg_msg;//中奖的球的文本
    @BindView(R.id.sign_gua_jiang_qu)
    RelativeLayout sign_gua_jiang_qu;
    @BindView(R.id.sign_etv)
    ErasableTextView sign_etv;
    /* 是否有漏签 */
    private boolean hasMissSign = false;

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

    private float per;//图片每像素在屏幕上的距离

    @Override
    public void initView() {
        TitleBarUtils.getInstance().setTitleFinish(this)
                .setShowOrHide(this, true)
                .setTitle(this, "签到");
        ViewUtil.setText(sign_card_num, ViewUtil.BLOCK);
        ViewUtil.setImage(sheep_sign_machine, ViewUtil.getNetImgByName("sheep_sign_machine"));
        ViewUtil.setImage(sheep_sign_rectangle, ViewUtil.getNetImgByName("sheep_sign_rectangle"));
        ViewUtil.setImage(sheep_sign_out, ViewUtil.getNetImgByName("sheep_sign_out"));
        ViewUtil.setImage(act_sign_ask_friend_iv, ViewUtil.getNetImgByName("shoutu"));
        ViewUtil.setImage(act_sign_eras_iv, ViewUtil.getNetImgByName("guajiang"));
        ViewUtil.setColorMapText(act_sign_ask_friend_tv, "收徒大狂欢", "大狂欢", "#FE5864");
        //sheep_sign_bg 宽 1500 高 1768
        //eggsView 宽为 864，高度为 608，距离上面 600
        //sheep_sign_rectangle 宽为 864，高度为 608 距离上面 350，距离左面 300
        //sheep_sign_out 宽为 218，高度为 284 距离上面 1290，距离左面 974
        per = G.WIDTH / 1500f;
        LayoutParamsUtil.resetLayoutParams(sheep_sign_out, new Lp(per).setTopMargin(1290).setLeftMargin(974).setWidth(218).setHeight(284));
        LayoutParamsUtil.resetLayoutParams(sheep_sign_rectangle, new Lp(per).setTopMargin(600).setWidth(864).setHeight(608));
        LayoutParamsUtil.resetLayoutParams(eggsView, new Lp(per).setTopMargin(600).setWidth(864).setHeight(608));
        LayoutParamsUtil.resetLayoutParams(sheep_sign_egg_rl, new Lp(per).setTopMargin(1290 - 184).setLeftMargin(974 + (218 - 182) / 2).setWidth(182).setHeight(184));
//        ViewUtil.setEnabled(signNowBut, false);
        sign_etv.setStokeWidth(G.getRealPix(20));
        sign_etv.setErasable(true);
        sign_etv.setOnTouchUpCountChangeListener(new Action1<Integer>() {
            @Override
            public void call(Integer count) {
                if (count >= 4) {
                    sign_etv.setFinish(true);
                    if (canSignGuaJiang())
                        onSignGuaJiangquClicked();
                }
            }
        });
        if (TestUtil.isDev())
            sign_gua_jiang_qu.setVisibility(View.VISIBLE);
    }

    private void aEggGoOut(String msg, final Action1<Animation> animationAction1) {
        ViewUtil.setText(sheep_sign_egg_msg, msg);
        ViewUtil.setVisibility(sheep_sign_egg_rl, true);
        Animation translateAnimation = new TranslateAnimation(0, 0, 0, per * 284);//平移动画  从0,0,平移到 0 , 284
        translateAnimation.setDuration(1500);//动画持续的时间为1.5s
        translateAnimation.setFillEnabled(true);//使其可以填充效果从而不回到原地
        translateAnimation.setFillAfter(true);//不回到起始位置
        translateAnimation.setInterpolator(new BounceInterpolator());//accelerated(加速)，decelerated(减速),repeated(重复),bounced(弹跳)等
//        translateAnimation.setInterpolator(new AccelerateInterpolator());
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (animationAction1 != null)
                    animationAction1.call(animation);
                ViewUtil.setVisibility(sheep_sign_egg_rl, false);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        //如果不添加setFillEnabled和setFillAfter则动画执行结束后会自动回到远点
        sheep_sign_egg_rl.startAnimation(translateAnimation);

    }

    @Override
    public void initData() {
        initSigns();
        initUserSignScratchAmount();
        initUserSignLastScratch();
        initSignCardData();
    }

    private void initUserSignScratchAmount() {
        SheepApp.getInstance().getNetComponent().getApiService().getUserSignScratch_amount()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        Float result = baseMessage.getData(Float.class);
                        if (result == null) {
                            result = 0.01f;
                        }
                        sign_etv.setText(String.format(Locale.CHINA, "绵羊币：%s", NumberFormatUtils.retainMost2(result)));
                    }

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

    //是否完成最后一次刮奖数据的获取
    private boolean isFinishInitLastScratch = false;
    //最后一次刮奖数据
    private RechargeLogEntity rechargeLogEntity;

    private void initUserSignLastScratch() {
        SheepApp.getInstance().getNetComponent().getApiService().getUserSignLastScratch()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        rechargeLogEntity = baseMessage.getData(RechargeLogEntity.class);
                        isFinishInitLastScratch = true;
                        updateSignGuaJiang();

                    }

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

    private void initSignCardData() {
        SheepApp.getInstance().getNetComponent().getApiService().getPunchAndSignCount()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        PunchAndSign punchAndSign = baseMessage.getData(PunchAndSign.class);
                        ViewUtil.setText(sign_card_num, punchAndSign.getSign_up_count());
                    }

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

    //签到记录列表
    private List<UserSign> userSignList = ListUtil.emptyList();
    //最后一次签到记录
    private UserSign lastUserSign;

    private void initSigns() {
        SheepApp.getInstance().getNetComponent().getApiService().getUserSignSigns()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        List<UserSign> data = baseMessage.getDataList(UserSign.class);
                        if (data != null) {
                            userSignList.clear();
                            ListUtil.addAll(userSignList, data);
                            ViewUtil.setText(signInfoText, String.format(Locale.CHINA, "已签到%d天，连续%d天签到可参与刮奖", data.size(), SIGN_PERIOD));
                            int max = 0;
                            lastUserSign = null;
                            /* 遍历最大签到周期 */
                            for (UserSign item : data) {
                                if (item.getDay() > max) {
                                    max = item.getDay();
                                    lastUserSign = item;
                                }
                                /* 设置已签到的天数状态 */
                                TextView childAt = (TextView) signDayList.getChildAt(item.getDay() - 1);
                                childAt.setBackground(getResources().getDrawable(R.drawable.shape_sign_bg_select));
                                if (item.getDay() == SIGN_PERIOD) {
                                    childAt.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, getResources().getDrawable(R.drawable.giftbox_open));
                                } else {
                                    childAt.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, getResources().getDrawable(R.drawable.qiandao));
                                }
                            }
                            /* 判断是否有漏签 */
                            hasMissSign = max > userSignList.size();
                            //设置今日签到状态
                            boolean isSignToday = lastUserSign != null && lastUserSign.isToday();
                            ViewUtil.setText(sign_now_but, isSignToday ? "已签到" : "签到");
                            if (canSignInSupplement())//今日已经签到，并且有漏签、且今日没有进行补签，就设置复活补签
                                ViewUtil.setText(sign_now_but, "复活补签");
                            updateSignGuaJiang();
                        } else {
                            G.showToast(R.string.service_data_error);
                        }
                        ViewUtil.setEnabled(sign_now_but, true);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                        ViewUtil.setEnabled(sign_now_but, true);
                    }
                });
    }

    //更新刮奖显示状态
    private void updateSignGuaJiang() {
        if (TestUtil.isDev())
            return;
        //一个周期完成且这个周期内没有刮奖时，可以进行刮奖
        ViewUtil.setVisibility(sign_gua_jiang_qu, canSignGuaJiang());
    }

    private boolean canSignGuaJiang() {
        return isFinishInitLastScratch && ListUtil.size(userSignList) == SIGN_PERIOD && (rechargeLogEntity == null || TimeUtil.isTimeXDay(rechargeLogEntity.getCreate_time(), -SIGN_PERIOD));
    }

    //签到周期
    public static final int SIGN_PERIOD = 6;

    /**
     * 补签
     */
    private void signInSupplement() {
        UserSign willUserSign;
        if (ListUtil.isEmpty(userSignList)) {
            willUserSign = new UserSign();
            willUserSign.setSign_date(TimeUtil.TimeStamp2Date(System.currentTimeMillis(), "yyyy-MM-dd"));
            willUserSign.setDay(1);
        } else {
            Collections.sort(userSignList);
            int i = 0;
            for (UserSign item : userSignList) {
                if (item.getDay() > i + 1) {//item.getDay()应该等于i + 1,不等于代表这天漏签了
                    break;
                }
                i++;
            }
            willUserSign = new UserSign();
            willUserSign.setDay(i + 1);
            willUserSign.resetSignDate(lastUserSign);
        }
        SheepApp.getInstance().getNetComponent().getApiService().postUserSignSignInSupplement(willUserSign.getSign_date(), willUserSign.getDay())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        SheepSignResult sheepSignResult = baseMessage.getData(SheepSignResult.class);
                        if (sheepSignResult != null) {
                            tryShowSignResultAndTask("补签成功", sheepSignResult.getAmount());
                            hasMissSign = false;
                        }
                        // 重新请求签到状态接口
                        initSigns();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                        ViewUtil.setEnabled(sign_now_but, true);
                    }
                });
    }

    /**
     * 签到
     */
    private void signNow() {
        SheepApp.getInstance().getNetComponent().getApiService().postUserSignSignIn()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        final SheepSignResult sheepSignResult = baseMessage.getData(SheepSignResult.class);
                        if (sheepSignResult != null) {
                            if (sheepSignResult.isSign()) {
                                tryShowSignResultAndTask("签到成功", sheepSignResult.getAmount());
                            } else {
                                aEggGoOut(NumberFormatUtils.retainMost2(sheepSignResult.getAmount()), new Action1<Animation>() {

                                    @Override
                                    public void call(Animation animation) {
                                        tryShowSignResultAndTask("签到成功", sheepSignResult.getAmount());
                                    }
                                });
                            }
                        }
                        initSigns();
                        ViewUtil.setEnabled(sign_now_but, true);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                        ViewUtil.setEnabled(sign_now_but, true);
//                                makeAndShowWindow("已签到", signDay.getData());
                    }
                });
    }

    private void showSignResultAndTask(final String title, final double money, RobTask robTask) {
        ViewUtil.newInstance().showRobDutyDialog(this, robTask, R.layout.dialog_sign_result_and_task, new Action1<View>() {
            @Override
            public void call(View view) {
                ViewUtil.setText((TextView) view.findViewById(R.id.sign_window_title), title);
                ViewUtil.setText((TextView) view.findViewById(R.id.sign_money_number), String.format(Locale.CHINA, "+%s", NumberFormatUtils.retainMost2(money)));
            }
        });
    }

    private void tryShowSignResultAndTask(final String title, final double money) {
        CommonUtil.getInstance().robTask(new Action1<RobTask>() {
            @Override
            public void call(RobTask robTask) {
                if (robTask != null) {
                    DataUtil.putAsInt(DataKey.KEY_ORDER, robTask.getOrder());
                    try {
                        showSignResultAndTask(title, money, robTask);
                    } catch (Exception e) {
                        e.printStackTrace();
                        G.showToast(e.getMessage());
                    }
                } else {
                    G.showToast("任务已被抢光！请实时关注任务发布！");
                }
            }
        });
    }

    @OnClick(R.id.active_info)
    public void onActiveInfoClicked() {
        startActivity(new Intent(SignActivity.this, ActiveRuleActivity.class));
    }

    @OnClick(R.id.sign_now_but)
    public void onSignNowButClicked() {
        ViewUtil.setEnabled(sign_now_but, false);
        if (canSignInSupplement()) {
            //该操作前提是lastUserSign是今天的数据，且没有进行过补签
            if (lastUserSign.signShared()) {//可以进行补签且进行过分享操作，可以直接补签
                signInSupplement();
            } else {
                new ShareLinkConfig().setAction1(new Action1<View>() {
                    @Override
                    public void call(View view) {
                        if (view == null) {
                            ViewUtil.setEnabled(sign_now_but, true);
                        } else {
                            ViewUtil.setText((TextView) view.findViewById(R.id.ask_share_title), "邀请获得复活机会");
                        }
                    }
                }).toShare(this);
            }
        } else {
            signNow();
        }
    }

    //判断 是否可以补签
    private boolean canSignInSupplement() {
        return hasMissSign && lastUserSign != null && lastUserSign.isToday() && !lastUserSign.signSupplemented();//有漏签并且今日已经签到、今日没有进行过补签，才能进行最近的补签
    }

    @OnClick(R.id.go_to_pack_but)
    public void onGoToPackButClicked() {
        Jump2View.getInstance().goSignCardAct(this, null);
    }

    //默认最小奖励
    public static final float DEFAULT_FLOAT = 0.01f;

    public void onSignGuaJiangquClicked() {
        SheepApp.getInstance().getNetComponent().getApiService().postUserSignScratchCard()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        SheepSignResult sheepSignResult = baseMessage.getData(SheepSignResult.class);
                        if (sheepSignResult != null) {
                            tryShowSignResultAndTask("刮奖成功", sheepSignResult.getAmount());
                        }
                        sign_gua_jiang_qu.setVisibility(View.GONE);
                        initUserSignLastScratch();
                    }

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

    @OnClick(R.id.go_to_yaoqing)
    public void onGoToYaoqingClicked() {
        Jump2View.getInstance().goAskGetMoney(this, null);
    }

    @Override
    public void onStart(SHARE_MEDIA share_media) {
//        LogUtil.println("SignActivity", "share", "onStart", share_media.getName());
    }

    @Override
    public void onResult(SHARE_MEDIA share_media) {
//        LogUtil.println("SignActivity", "share", "onResult", share_media.getName());
        SheepApp.getInstance().getNetComponent().getApiService().postUserSignShare()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if (canSignInSupplement())
                            signInSupplement();
                    }

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

    @Override
    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
        String msg = throwable.getMessage();
        G.showToast(msg != null && msg.contains("没有安装应用") ? "没有安装应用" : msg);
//        LogUtil.println("SignActivity", "share", "onError", share_media.getName(), throwable.getMessage());
    }

    @Override
    public void onCancel(SHARE_MEDIA share_media) {
//        LogUtil.println("SignActivity", "share", "onCancel", share_media.getName());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(SheepApp.getInstance()).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        if (eggsView != null) {
            eggsView.onDestroy();
        }
        super.onDestroy();
    }
}
