package com.sheep.gamegroup.view.dialog;

import android.app.Activity;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.CashAwarsEntity;
import com.sheep.gamegroup.model.entity.CommendApp;
import com.sheep.gamegroup.model.entity.GiftBag;
import com.sheep.gamegroup.model.entity.GiftBagApp;
import com.sheep.gamegroup.model.entity.RobTask;
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.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.StringUtils;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.activity.ActMain;
import com.sheep.gamegroup.view.adapter.GiftCenterAdapter;
import com.sheep.gamegroup.view.adapter.WelfareAdapter;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;

import org.afinal.simplecache.ApiKey;

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

import static com.sheep.gamegroup.util.UMConfigUtils.Event.GIFT_BAG_COPY_CODE;
import static com.sheep.gamegroup.view.adapter.TryMakeMoneyAdp.PUBLIC_TAG_PREFIX_TEXTVIEW_LIST;


public class DialogGameOrTaskOrGift {
    private Activity activity;
    private String gameId;

    public DialogGameOrTaskOrGift(Activity activity, String gameId) {
        this.activity = activity;
        this.gameId = gameId;
    }
// Content View Elements

    private ImageView dialog_iv;
    private TextView dialog_name_tv;
    private ImageView dialog_iv_2;
    private TextView dialog_tip;
    private View dialog_amount_container;
    private TextView dialog_amount_tv;
    private View dialog_line;
    private TextView dialog_gift_tv;
    private TextView dialog_gift_code_tv;
    private TextView dialog_gift_info_tv;
    private TextView dialog_btn_left;
    private View dialog_btn_center;
    private TextView dialog_btn_right;

    // End Of Content View Elements


    private void resetView() {
        ViewUtil.setDefaultText(dialog_name_tv);
        ViewUtil.setDefaultText(dialog_gift_tv);
        ViewUtil.setVisibility(dialog_amount_tv, false);
        ViewUtil.setVisibility(dialog_line, false);
        ViewUtil.setVisibility2(dialog_gift_code_tv, false);
        ViewUtil.setVisibility2(dialog_gift_info_tv, false);
        dialog_btn_left.setText("换一个");
        dialog_btn_right.setText("立即下载");
        dialog_btn_right.setTag("null");
    }

    private void loadData() {
        loadData(true);
    }

    private void loadData(boolean isChangeNextShow) {
        if (commendApp == null) {
            resetView();
        } else {
            if(isChangeNextShow)
                commendApp.changNextShow();
            dialog_btn_left.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    initData();
                }
            });
            if (commendApp.isShow(CommendApp.SHOW_GIFT)) {
                final GiftBagApp giftBagApp = commendApp.getHas_gift_bag().get(0);
                final GiftBag giftBag = giftBagApp.getGift_bag();
                ViewUtil.setVisibility(dialog_amount_tv, false);
                ViewUtil.setVisibility(dialog_line, false);
                ViewUtil.setVisibility2(dialog_gift_code_tv, giftBagApp.isReceived());
                ViewUtil.setVisibility2(dialog_gift_info_tv, true);
                GlideImageLoader.setGameImage(dialog_iv, commendApp.getApp().getIcon());
                ViewUtil.setText(dialog_name_tv, commendApp.getApp().getName());
                ViewUtil.setText(dialog_gift_tv, giftBag.getGiftName());
                ViewUtil.setText(dialog_gift_code_tv, activity.getString(R.string.gift_bag_code, giftBagApp.getCode()));
                ViewUtil.setText(dialog_gift_info_tv, giftBag.getUseMethod());
                dialog_btn_right.setTag("null");
                if (giftBagApp.isReceived()) {//已经领取礼包
                    ViewUtil.setText(dialog_btn_right, "复制礼包码");
                    dialog_btn_right.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (TextUtils.isEmpty(giftBagApp.getCode())) {
                                G.showToast(R.string.error_data);
                            } else {
                                GIFT_BAG_COPY_CODE.onEvent("gift_bag_id", giftBag.getId(), "gift_bag_code", giftBagApp.getCode());
                                StringUtils.CopyText(giftBagApp.getCode());
                                G.showToast(R.string.success_copy_code);
                            }
                        }
                    });
                } else {
                    ViewUtil.setText(dialog_btn_right, "领取礼包");
                    dialog_btn_right.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ViewUtil.setText(dialog_btn_right, "正在领取");
                            GiftCenterAdapter.receiveGiftBag(null, giftBagApp, new Action1<Integer>() {
                                @Override
                                public void call(Integer integer) {
                                    switch (integer) {
                                        case WelfareAdapter.TO_REFRESH://刷新界面(注：giftBagApp中已经添加了code)
                                            loadData(false);//重新加载
                                            break;
                                        case WelfareAdapter.RECEIVE_FAILED://领取失败
                                            ViewUtil.setText(dialog_btn_right, "领取礼包");
                                            break;
                                    }
                                }
                            });
                        }
                    });
                }
            } else if (commendApp.isShow(CommendApp.SHOW_TASK)) {
                ViewUtil.setVisibility(dialog_amount_tv, true);
                ViewUtil.setVisibility(dialog_line, true);
                ViewUtil.setVisibility2(dialog_gift_code_tv, false);
                ViewUtil.setVisibility2(dialog_gift_info_tv, false);
                GlideImageLoader.setGameImage(dialog_iv, commendApp.getRelease_task().getTask().getIcon());
                ViewUtil.setText(dialog_name_tv, commendApp.getRelease_task().getName());
                ViewUtil.setText(dialog_amount_tv, activity.getString(R.string.plus_x_yuan, commendApp.getRelease_task().getBonusText()));
                ViewUtil.setText(dialog_gift_tv, "现金");
                ViewUtil.setText(dialog_btn_right, "立即赚钱");
                dialog_btn_right.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Jump2View.getInstance().goTaskDetailView(activity, commendApp.getRelease_task().getId());
                    }
                });
            } else if (commendApp.isShow(CommendApp.SHOW_GAME)) {
                ViewUtil.setVisibility(dialog_amount_tv, false);
                ViewUtil.setVisibility(dialog_line, false);
                ViewUtil.setVisibility2(dialog_gift_code_tv, false);
                ViewUtil.setVisibility2(dialog_gift_info_tv, false);
                GlideImageLoader.setGameImage(dialog_iv, commendApp.getApp().getIcon());
                ViewUtil.setText(dialog_name_tv, commendApp.getApp().getName());
                ViewUtil.setText(dialog_gift_tv, commendApp.getApp().getManufacturer());//这里显示的是开发商名字
                commendApp.getApp().getFindAppHelper().getDownloadHelper().updateDownloadTaskView(activity, commendApp.getApp(), dialog_btn_right);
                dialog_btn_right.setTag(PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + commendApp.getApp().getDownload_url());
                if(activity instanceof ActMain){
                    ((ActMain) activity).setDownloadHelper(commendApp.getApp().getFindAppHelper().getDownloadHelper());
                    ((ActMain) activity).setUrl(commendApp.getApp().getDownload_url());
                    ((ActMain) activity).setPackageName(commendApp.getApp().getPackage_name());
                }
            } else {
                if (BuildConfig.DEBUG)
                    G.showToast("不是礼包，不是现金任务，不是游戏，还可能是什么");
            }
        }
    }

    private void bindViews(View view) {
        dialog_iv = (ImageView) view.findViewById(R.id.dialog_iv);
        dialog_name_tv = (TextView) view.findViewById(R.id.dialog_name_tv);
        dialog_iv_2 = (ImageView) view.findViewById(R.id.dialog_iv_2);
        dialog_tip = (TextView) view.findViewById(R.id.dialog_tip);
        dialog_amount_container = view.findViewById(R.id.dialog_amount_container);
        dialog_amount_tv = (TextView) view.findViewById(R.id.dialog_amount_tv);
        dialog_line =  view.findViewById(R.id.dialog_line);
        dialog_gift_tv = (TextView) view.findViewById(R.id.dialog_gift_tv);
        dialog_gift_code_tv = (TextView) view.findViewById(R.id.dialog_gift_code_tv);
        dialog_gift_info_tv = (TextView) view.findViewById(R.id.dialog_gift_info_tv);
        dialog_btn_left = (TextView) view.findViewById(R.id.dialog_btn_left);
        dialog_btn_center = view.findViewById(R.id.dialog_btn_center);
        dialog_btn_right = (TextView) view.findViewById(R.id.dialog_btn_right);
        if(activity instanceof ActMain){
            ((ActMain) activity).setProgressView(view);
        }
    }

    private AlertDialog mAlertDialog;

    public AlertDialog showDialog() {
        View view = View.inflate(activity, R.layout.dialog_game_or_task_or_gift, null);
        mAlertDialog = new AlertDialog.Builder(activity, R.style.MyDialogActivityTheme)
                .setView(view)
                .create();
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAlertDialog.dismiss();
                onCancelOrClickClose();
            }
        };

        bindViews(view);
        mAlertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if(activity instanceof ActMain){
                    ((ActMain) activity).setProgressView(null);
                    ((ActMain) activity).setDownloadHelper(null);
                    ((ActMain) activity).setUrl(null);
                    ((ActMain) activity).setPackageName(null);
                }
            }
        });
        mAlertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                onCancelOrClickClose();
            }
        });
        final View dialog_close = view.findViewById(R.id.dialog_close);
        dialog_close.setOnClickListener(onClickListener);
        try {
            mAlertDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
        resetView();
        initData();
        return mAlertDialog;
    }

    private void onCancelOrClickClose() {
        if(activity instanceof ActMain) {
            if (DataUtil.getAsBoolean("tryShowHalfScreenAd", false)) {
                DataUtil.putAsBoolean("tryShowHalfScreenAd", false);
                Jump2View.getInstance().tryShowHalfScreenAd(activity, ((ActMain) activity).getContainer());
            }
        }
    }

    private CommendApp commendApp;
    public static final int FIRST_ORDER = 1;//第一次调用会长推广游戏的接口时，传入的order的默认值

    private void initData() {
        if (commendApp != null && commendApp.needChange()) {
            showChange();
        } else if(commendApp != null && commendApp.hasNextShow()){
            loadData();
        } else {
            SheepApp.getInstance().getNetComponent().getApiService().getCommendApp(gameId, commendApp == null ? FIRST_ORDER : commendApp.getOrder())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                        @Override
                        public void onNext(BaseMessage baseMessage) {
                            CommendApp newCommendApp = baseMessage.getData(CommendApp.class);
                            if(newCommendApp == null || (newCommendApp.getApp() != null && newCommendApp.getApp().getId() == 0)){//为空或者为无效数据
                                onError(baseMessage);
                            } else {
                                commendApp = newCommendApp;
                                loadData();
                            }
                        }

                        @Override
                        public void onError(BaseMessage baseMessage) {
                            if(commendApp == null){//没有获取到过commendApp的情况下，直接弹出抢任务弹出框
                                mAlertDialog.dismiss();
                                showTaskDialog();
                            } else {
                                showChange();
                            }
                        }
                    });
        }
    }

    //显示换个频道去赚钱
    private void showChange() {
        ViewUtil.setVisibility(dialog_iv_2, true);//显示换个频道去赚钱图标
        ViewUtil.setVisibility(dialog_tip, true);//显示文字【当前现金任务剩余%s元】
        ViewUtil.setVisibility(dialog_iv, false);//隐藏应用图标
        ViewUtil.setVisibility(dialog_btn_left, false);//隐藏应用图标
        ViewUtil.setVisibility(dialog_btn_center, false);//隐藏应用图标
        ViewUtil.setVisibility(dialog_name_tv, false);//隐藏应用名字
        ViewUtil.setVisibility2(dialog_amount_container, false);//不显示礼包和现金的父控件
        ViewUtil.setVisibility2(dialog_gift_code_tv, false);//不显示礼包码
        ViewUtil.setVisibility2(dialog_gift_info_tv, false);//不显示礼包详情
        CashAwarsEntity cashAwarsEntity = DataUtil.getInstance().getCacheResult(ApiKey.CAN_RECEIVE_AWARD, CashAwarsEntity.class);
        ViewUtil.setText(dialog_tip, activity.getString(R.string.cur_xian_jin_amount, cashAwarsEntity == null ? "0" : NumberFormatUtils.retainMost2(cashAwarsEntity.getCash())));
        dialog_btn_right.setText("立即去赚钱");
        dialog_btn_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAlertDialog.dismiss();
                showTaskDialog();
            }
        });
    }

    //显示抢任务弹出框
    private void showTaskDialog() {
        CommonUtil.getInstance().robTask(new Action1<RobTask>() {
            @Override
            public void call(RobTask robTask) {
                if (robTask != null) {
                    DataUtil.putAsInt(DataKey.KEY_ORDER, robTask.getOrder());
                    ViewUtil.newInstance().showRobDutyDialog(activity, robTask);
                } else {
                    G.showToast("任务已被抢光！请实时关注任务发布！");
                    if (activity instanceof ActMain && DataUtil.getAsBoolean("tryShowHalfScreenAd", false)) {
                        DataUtil.putAsBoolean("tryShowHalfScreenAd", false);
                        Jump2View.getInstance().tryShowHalfScreenAd(activity, ((ActMain) activity).getContainer());
                    }
                }
            }
        });
    }
}
