package com.gensee.multi_instance.demo.player.holder;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gensee.callback.IHongbaoCallBack;
import com.gensee.hongbao.GrabInfo;
import com.gensee.hongbao.HongbaoInfo;
import com.gensee.hongbao.UserGrabInfo;
import com.gensee.multi_instance.R;
import com.gensee.service.IRedEnvelopes;
import com.gensee.service.RedEnvelopes;
import com.gensee.utils.DateUtil;
import com.gensee.utils.GenseeLog;

/**
 * 课堂系统功能逻辑中，学生端只能收红包，不能发红包，因此这里只展现收红包的逻辑代码
 * 只有加入直播成功且红包对象注册给player（player.registerRedEnvelop(hongbao)）的情况下才能调用红包相关的接口，否则无效
 */
public class HongbaoHolder implements IHongbaoCallBack {
    private static final String TAG = "HongbaoHolder";

    private RedEnvelopes hongbao;
    private Activity activity;
    private Handler handler;
    private long selfUserId;

    public HongbaoHolder(Activity activity,Handler handler){
        hongbao = new RedEnvelopes(this);
        this.activity = activity;
        this.handler = handler;
    }

    public IRedEnvelopes getHongbao(){
        return hongbao;
    }


    /**
     * 加成功之后设置过来
     * @param userId 当前用户id
     */
    public void setUserId(long userId){
        selfUserId = userId;
    }

    /**
     * 抢过的红包的列表
     */
    public void showSelfHongbaoList(){
        hongbao.querySelfGrabList();
    }

    private void showGrab(final HongbaoInfo result,final Handler handler){
        final String msg = "祝福语：" + result.getComment() + "\n剩余时间:";
        final AlertDialog.Builder builder= new AlertDialog.Builder(activity);
        View v = LayoutInflater.from(activity).inflate(R.layout.gs_hb_layout,null);
        builder.setView(v);
        TextView txtComment = (TextView) v.findViewById(R.id.txtComment);
        final  TextView txtTime = (TextView)v.findViewById(R.id.txtTimeOut);
        TextView txtTip = (TextView)v.findViewById(R.id.txtTip);
        Button b = (Button) v.findViewById(R.id.btnGrab);
        txtTip.setText("收到"+result.getUserName()+"的红包");
        String comment = result.getComment();
        txtComment.setText(comment == null?"":comment);


        final AlertDialog dialog = builder.create();
        final Runnable r = new Runnable() {
            int time = result.getTimeLimit();
            @Override
            public void run() {
                txtTime.setText(""+ time);
                if(time == 0){
                    if(dialog.isShowing()){
                        dialog.dismiss();
                    }
                }else {
                    time --;
                    handler.postDelayed(this,1000);
                }

            }
        };
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                handler.removeCallbacks(r);
                hongbao.grabHongbao(result.getHongbaoId());//抢的结果回调 onHongbaoGrabHongbao
                //用户自行去做抢的动作开始到抢红包结果通知（onHongbaoGrabHongbao）的动画效果
            }
        });
//        b.setBackgroundResource(R.drawable.ic_hb_reconnet_bg);
        dialog.show();
        handler.post(r);


    }

    @Override
    public void onHongbaoCreate(int result, String hongbaoId) {
        GenseeLog.d(TAG,"onHongbaoCreate result = " + result + " hongbaoId = " + hongbaoId);
    }

    @Override
    public void onHongbaoGrabHongbao(final int result, final String id, final int money) {
        //抢红包的结果回调
        //更新抢到界面，显示抢到多少钱或没抢到，result要匹配，result为0时，代表抢到红包
        //IHongbaoCallBack.GRAB_RESULT_ 系列的错误码，
        handler.post(new Runnable() {
            @Override
            public void run() {
                showGrabResult(result,id,money,false);
            }
        });

    }

    private void showGrabResult(int result, final String id, int money,boolean isDiretHongbao){
        //复用布局文件
        final AlertDialog.Builder builder= new AlertDialog.Builder(activity);
        View v = LayoutInflater.from(activity).inflate(R.layout.gs_hb_layout,null);
        builder.setView(v);
        TextView txtComment = (TextView)v.findViewById(R.id.txtComment);
        final  TextView txtTime = (TextView)v.findViewById(R.id.txtTimeOut);
        TextView txtTip = (TextView)v.findViewById(R.id.txtTip);
        Button button = (Button) v.findViewById(R.id.btnGrab);
        txtComment.setText("");
        txtTime.setText("");

        final AlertDialog dialog = builder.create();
        button.setBackgroundDrawable(null);
        button.setText("查看大家手气");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取红包被瓜分的列表信息（手气）
                hongbao.queryHongbaoGrabList(id);//查看手气的回调onHongbaoQueryHongbaoGrabList
                dialog.dismiss();
            }
        });
        //不能查看手气的情况下关闭对话框
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        };
        String msg = "没有抢到";
        switch (result){//目前只有这几种情况，暂无其他case
            case GRAB_RESULT_DIRECT:
                msg = "抱歉，定向红包不是给你的，不能抢";
                button.setText("确定");
                button.setOnClickListener(clickListener);
                break;
            case GRAB_RESULT_EXPIRE:
                msg ="红包已经失效";
                break;
            case GRAB_RESULT_REPEAT:
                msg = "你已经抢过了";
                break;
                 case GRAB_RESULT_IS_EMPTY:
                msg = "红包已经被抢完";
                break;
            case GRAB_RESULT_SUCCESS:
                msg = String.format("抢到%.2f元",money/100f); //money 单位是分
                if (isDiretHongbao) {
                    button.setText("确定");
                    button.setOnClickListener(clickListener);
                }
                break;
            case -1:
                msg = "没有抢到，请检查网络";
                button.setText("确定");
                button.setOnClickListener(clickListener);
                break;
        }
        txtTip.setText(msg);
        dialog.show();
    }

    @Override
    public void onHongbaoQueryHongbaoList(HongbaoInfo[] hongbaoInfos) {
        GenseeLog.d(TAG,"onHongbaoQueryHongbaoList " + hongbaoInfos);
    }

    @Override
    public void onHongbaoQueryHongbaoGrabList(final String hongbaoId, final GrabInfo[] grabs) {

        //显示红包被抢列表
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (grabs == null || grabs.length == 0) {
                    Toast.makeText(activity,"没有获得瓜分列表",Toast.LENGTH_SHORT).show();
                }else {
                    showGrabList(hongbaoId,grabs);
                }
            }
        });
    }
    //显示红包被抢列表
    private void showGrabList(String hongbaoId, final GrabInfo[] grabs) {
        final AlertDialog.Builder builder= new AlertDialog.Builder(activity);
        builder.setTitle("红包争抢信息");
        builder.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return grabs.length;
            }

            @Override
            public Object getItem(int position) {
                return grabs[position];
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ItemHolder holder= null;
                if(convertView == null ){
                    convertView = LayoutInflater.from(activity).inflate(R.layout.gs_hongbao_grab_item,null);
                    holder = new ItemHolder(convertView);
                    convertView.setTag(holder);
                }else {
                    holder = (ItemHolder) convertView.getTag();
                }
                holder.bindData((GrabInfo)getItem(position));
                return convertView;
            }

            class ItemHolder{
                private TextView txtTime,txtName,txtMoney;
                private ImageView imageView;
                public ItemHolder(View v){
                    txtMoney = (TextView) v.findViewById(R.id.txtMoney);
                    txtTime = (TextView) v.findViewById(R.id.txtTime);
                    txtName = (TextView)v.findViewById(R.id.txtName);
                    imageView = (ImageView) v.findViewById(R.id.imgBest);
                }

                public void bindData(GrabInfo item) {
                    txtMoney.setText(item.getMoney() + "分");
                    txtName.setText(item.getUserName());
                    txtTime.setText(DateUtil.getTimeShort(item.getGrabTime()));
                    imageView.setVisibility(item.isBest()?View.VISIBLE:View.INVISIBLE);
                }
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    public void onHongbaoQuerySelfGrabList(final UserGrabInfo[] userGrabInfos) {
        GenseeLog.d(TAG,"onHongbaoQuerySelfGrabList " + userGrabInfos);
        handler.post(new Runnable() {
            @Override
            public void run() {
        if(userGrabInfos != null && userGrabInfos.length>0){

                    int bestCount = 0;
                    int total = 0;
                    for (UserGrabInfo info:userGrabInfos) {
                        if(info.isBest()){
                            bestCount ++;
                        }
                        int money = info.getMoney();
                        if(money<0){
                            money = 0;
                        }
                        total += money;
                    }
                    final AlertDialog.Builder builder= new AlertDialog.Builder(activity);
                    builder.setTitle("我参与的红包"+ userGrabInfos.length+"个，共抢到"+total+",最佳"+ bestCount+"次");
                    builder.setAdapter(new BaseAdapter() {
                        @Override
                        public int getCount() {
                            return userGrabInfos.length;
                        }

                        @Override
                        public Object getItem(int position) {
                            return userGrabInfos[position];
                        }

                        @Override
                        public long getItemId(int position) {
                            return position;
                        }

                        @Override
                        public View getView(int position, View convertView, ViewGroup parent) {
                            ItemHolder holder= null;
                            if(convertView == null ){
                                convertView = LayoutInflater.from(activity).inflate(R.layout.gs_hongbao_grab_item,null);
                                holder = new ItemHolder(convertView);
                                convertView.setTag(holder);
                            }else {
                                holder = (ItemHolder) convertView.getTag();
                            }
                            holder.bindData((UserGrabInfo)getItem(position));
                            return convertView;
                        }

                        class ItemHolder{
                            private TextView txtTime,txtName,txtMoney;
                            private ImageView imageView;
                            public ItemHolder(View v){
                                txtMoney = (TextView)v.findViewById(R.id.txtMoney);
                                txtTime = (TextView)v.findViewById(R.id.txtTime);
                                txtName = (TextView)v.findViewById(R.id.txtName);
                                imageView = (ImageView) v.findViewById(R.id.imgBest);
                            }

                            public void bindData(UserGrabInfo item) {
                                txtMoney.setText(item.getMoney() + "分");
                                txtName.setText(item.getUserName());
                                txtTime.setText(DateUtil.getTimeShort(item.getGrabTime()));
                                imageView.setVisibility(item.isBest()?View.VISIBLE:View.INVISIBLE);
                            }
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();

        } else {
            Toast.makeText(activity,"还没参与过抢红包",Toast.LENGTH_SHORT).show();
        }
            }
        });
    }

    @Override
    public void onHongbaoQueryBalance(boolean ok, int balance) {
        GenseeLog.d(TAG,"onHongbaoQueryBalance 课堂可用红包余额" + balance);
    }

    //收到红包
    @Override
    public void onHongbaoComingNotify(final HongbaoInfo hongbaoInfo) {
        if(HONGBAO_TYPE_DIRECT == hongbaoInfo.getType()){
            //定向红包不用抢，红包自动到接收人“帐”上
            return;
        }
        //收到新的红包，弹出抢红包界面
        handler.post(new Runnable() {
            @Override
            public void run() {
                showGrab(hongbaoInfo, handler);
            }
        });
    }

    //红包的所有被抢记录
    @Override
    public void onHongbaoGrabbedNotify(final String hongbaoId, final GrabInfo grabInfo, int hongbaoType) {
        //有一个人抢就会回调一次，包括自己

        if (HONGBAO_TYPE_DIRECT == hongbaoType && grabInfo.getUserId() == selfUserId) {
            //是定向红包且接收人是自己，说明给自己的定向红包已经到账，直接展现金额
            handler.post(new Runnable() {
                @Override
                public void run() {
                    showGrabResult(GRAB_RESULT_SUCCESS, hongbaoId, grabInfo.getMoney(), true);
                }
            });
        }
    }

}
