package com.wasu.cs.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.wasu.authsdk.AuthSDK;
import com.wasu.common.WError;
import com.wasu.cs.model.DemandRecommand;
import com.wasu.cs.model.RecommendListEntry;
import com.wasu.cs.module.ScreenSaverModule;
import com.wasu.cs.utils.ActivityManager;
import com.wasu.cs.utils.BitmapUtils;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.module.datafetch.DataFetchListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.datafetch.ObjectBase;
import com.wasu.module.log.WLog;
import com.wasu.widgets.adapter.BaseFocusRecyclerViewAdapter;
import com.wasu.widgets.adapter.BaseFocusRecyclerViewHolder;
import com.wasu.widgets.focuswidget.FocusRecyclerView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import basic.BuilderTypeManager.BuildType;
import basic.app.TvAppLike;
import cn.com.wasu.main.AppUtil;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

import static android.view.View.VISIBLE;
import static cn.com.wasu.main.R.id.BottomView;

/**
 * apk退出页 - 资产推荐
 * @author chenliang
 * 2016.12.21
 * */
public class DialogAssetExitApp extends Dialog implements View.OnFocusChangeListener{
    private Context mContext;
    private DialogAssetExitApp mDialog;
    private RecommendAdapter mAdapter;

    //view
    private TextView mCanel, mAgain, mPrompt;
    private FocusRecyclerView mRecycleView;
    private LinearLayout backGround,innerBackground;

    private String TAG = "DialogAssetExitApp";
    private List<RecommendListEntry> mList;
    private Bitmap mBackgroundBitmap;
    private Bitmap mInnerBackgroundBitmap;
    /**
     * 网络数据请求重试次数
     **/
    private int fetchDataRetryCount = 3;

    /**
     * 退出对话框视图
     */
    protected View view;

    private void init(Context context){
        mContext = context;
        LayoutInflater layoutInflater = getLayoutInflater();
        view = layoutInflater.inflate(R.layout.app_dialog_aeest_exit, null);

        mList = new ArrayList<>();

        mCanel = (TextView) view.findViewById(R.id.exit);
        mAgain = (TextView) view.findViewById(R.id.again);
        mPrompt = (TextView) view.findViewById(R.id.prompt);
        mPrompt.setVisibility(VISIBLE);
        mRecycleView = (FocusRecyclerView) view.findViewById(R.id.recycleview);
        // 设置退出背景页
        backGround = (LinearLayout) view.findViewById(R.id.exit_layout);
        mBackgroundBitmap = BitmapUtils.readBitMapByDecodeStream(context, R.drawable.exit_bg, Bitmap.Config.ARGB_8888);
        backGround.setBackgroundDrawable(new BitmapDrawable(context.getResources(),mBackgroundBitmap));
        innerBackground = (LinearLayout) view.findViewById(R.id.exit_inner_layout);
        mInnerBackgroundBitmap = BitmapUtils.readBitMapByDecodeStream(context, R.drawable.background_down);
        innerBackground.setBackgroundDrawable(new BitmapDrawable(context.getResources(),mInnerBackgroundBitmap));

        mCanel.setOnFocusChangeListener(this);
        mAgain.setOnFocusChangeListener(this);


        mCanel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ScreenSaverModule.getInstance().clearTask();
//                getOwnerActivity().finish();
                ActivityManager.getInstance().exitApp();
                TvAppLike.getInstance().onTerminate();
                System.exit(0);
            }
        });
        mAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
            }
        });
        /**
         * initRecycleview
         * **/
        mAdapter = new RecommendAdapter(mRecycleView);
        mRecycleView.setAdapter(mAdapter);
        mRecycleView.setNextFocusDownId(mCanel.getId());
        mRecycleView.setClipChildren(true);
        mRecycleView.setClipToPadding(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecycleView.setLayoutManager(linearLayoutManager);
        mRecycleView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.left = mContext.getResources().getDimensionPixelSize(R.dimen.d_10dp);
                outRect.top = mContext.getResources().getDimensionPixelSize(R.dimen.d_10dp);
                outRect.right = mContext.getResources().getDimensionPixelSize(R.dimen.d_10dp);
                outRect.bottom = mContext.getResources().getDimensionPixelSize(R.dimen.d_10dp);
            }
        });
        mAdapter.setOnItemListener(new BaseFocusRecyclerViewAdapter.OnItemListener() {
            @Override
            public void onItemClick(int position) {
                AppUtil.playEnter = "退出页推荐位";
                mDialog.dismiss();
                Intent intent = new Intent();
                IntentMap.startIntent(getContext(), intent, mList.get(position).getLayout(), mList.get(position).getJsonUrl(), null);
            }

            @Override
            public void onItemLongClick(int position) {

            }

            @Override
            public void onItemFocusChange(View itemView, int position, boolean hasFocus) {
                View bottom = itemView.findViewById(R.id.BottomView);
                if (bottom != null) {
                    if (hasFocus) {
                        bottom.setVisibility(VISIBLE);
                    } else {
                        bottom.setVisibility(View.INVISIBLE);
                    }
                }
            }
        });

        /**
         * show之后开始请求数据
         * */
        this.setOnShowListener(new OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                getRecommendData();
            }
        });

        mAgain.requestFocus();
    }

    /**
     * 关闭时调用
     * */
    public void DestoryDialog(){
        backGround.setBackgroundResource(0);
        mBackgroundBitmap.recycle();
        innerBackground.setBackgroundResource(0);
        mInnerBackgroundBitmap.recycle();
    }


    /**
     * 计算观看时间
     * */
    public void setStartTime(long starttime) {
        long startTime = starttime;
        long currTime = System.currentTimeMillis();

        String unVipPrompt="登陆VIP帐号";
        if (checkIsVip()) {
            unVipPrompt = "可";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm", Locale.CHINA);
        String currTimeStr = simpleDateFormat.format(new Date(currTime));
        String durationStr = getColorViewTime((int) (currTime - startTime) / 1000);

        String content = "HI~您已观看" + durationStr + "，"+unVipPrompt+"获取金币兑换奖励哦！";
        mPrompt.setText(Html.fromHtml(content));
    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        mCanel.setTextColor(0xffffffff);
        mAgain.setTextColor(0xffffffff);

        if (hasFocus) {
            switch (v.getId()) {
                case R.id.exit:
                    mCanel.setTextColor(0xffffff00);
                    break;
                case R.id.again:
                    mAgain.setTextColor(0xffffff00);
                    break;
            }
        }
    }

    /**---------------------------自定义方法非重写--------------------------------------------------**/

    private String getColorViewTime(int var0){
        String content = "";
        if(var0 == 0) {
            content = "<font color='#ffff00'>"+0+"</font>"+"秒";
        }else {
            int var2 = var0 / 3600;
            int var3 = var0 % 3600 / 60;
            int var4 = var0 % 60;
            if(var2 > 0) {
                content = "<font color='#ffff00'>"+String.format("%d", new Object[]{Integer.valueOf(var2)})+"</font>"+"小时";
            }
            if(var3 > 0) {
                content = content+"<font color='#ffff00'>"+String.format("%2d", new Object[]{Integer.valueOf(var3)})+"</font>"+"分";
            }
            if(var4 > 0) {
                content = content+"<font color='#ffff00'>"+String.format("%2d", new Object[]{Integer.valueOf(var4)})+"</font>"+"秒";
            }
        }
        return content;
    }

    /**
     * 网络请求
     */
    private synchronized void getRecommendData() {
        DataFetchListener.ObjectListener objectListener = new DataFetchListener.ObjectListener() {
            @Override
            public void onObjectGet(int retcode, String extraMsg, ObjectBase data) {

                // 重试检查
                if (retcode == WError.ERROR_INVALID_DATA || retcode == WError.ERROR_NET) {
                    if (fetchDataRetryCount > 0) {
                        DataFetchModule.getInstance().fetchObjectGet(BuildType.Exit_Recommend_Data, DemandRecommand.class, this);
                        fetchDataRetryCount--;
                        return;
                    }
                }

                if (retcode != 0) {
                    WLog.e(TAG, extraMsg);
                    return;
                }
                fetchDataRetryCount = 3;
                RecommendListEntry listEntry = (RecommendListEntry) data;
                mList.clear();

                if (listEntry.getmList() != null && listEntry.getmList().size() > 0) {
                    mList.addAll(listEntry.getmList());
                    loadDataSuccess();
                }else{
//                    mCanel.requestFocus();
                    WLog.d(TAG, "退出页没有获取到资产信息！");
                }
            }
        };

        WLog.e(TAG, "开始获取数据");
        DataFetchModule.getInstance().fetchObjectGet(BuildType.Exit_Recommend_Data, RecommendListEntry.class, objectListener);
    }

    /**
     * 推荐数据获取成功
     **/
    private void loadDataSuccess() {
        WLog.e(TAG, "数据获取成功！mList =  " + mList.toString());
        mAdapter.setData(mList);
        mAdapter.notifyDataSetChanged();

        // 第一个资产获取焦点
//        Handler handler = new Handler();
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                if (mRecycleView.getChildCount() > 0 && mRecycleView.getChildAt(0) != null) {
//                    mRecycleView.getChildAt(0).requestFocus();
//                }
//            }
//        }, 200);
    }


    /**
     * adapter
     */
    private class RecommendAdapter extends BaseFocusRecyclerViewAdapter<RecommendListEntry> {
        public RecommendAdapter(FocusRecyclerView recyclerView) {
            super(recyclerView);
        }

        @Override
        protected BaseFocusRecyclerViewHolder createItem(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.activity_exit_item, null);
            RecommendAdapter.MyViewHolder viewHolder = new RecommendAdapter.MyViewHolder(view, getItemParent(), getItemListener());
            return viewHolder;
        }

        @Override
        protected void bindData(BaseFocusRecyclerViewHolder holder, int position) {
            SimpleDraweeView img = ((RecommendAdapter.MyViewHolder) holder).img;
            TextView title = ((RecommendAdapter.MyViewHolder) holder).title;
            TextView point = ((RecommendAdapter.MyViewHolder) holder).point;

            if (getItemData(position) == null) {
                img.setImageResource(R.drawable.default_wasu_bg);
                title.setText("");
                point.setText("");
            } else {
                FrescoImageFetcherModule.getInstance().attachImage(getItemData(position).getPicUrl(), img);
                title.setText(getItemData(position).getTitle());
                point.setText(getItemData(position).getPoints());
            }
        }


        // viewHolder
        public class MyViewHolder extends BaseFocusRecyclerViewHolder {
            View view;
            SimpleDraweeView img;
            RelativeLayout bottomView; //底部view
            TextView title; // 标题
            TextView point; // 评分

            /**
             * 创建FocusRecyclerView的itemView
             *
             * @param itemView          item View
             * @param focusRecyclerView item parent ViewGroup(Parent must instanceof FocusRecyclerView)
             * @param mOnItemListener   item click、longClick、focusChange listener
             */
            public MyViewHolder(View itemView, FocusRecyclerView focusRecyclerView, OnItemListener mOnItemListener) {
                super(itemView, focusRecyclerView, mOnItemListener);
                view = itemView;
                img = (SimpleDraweeView) view.findViewById(R.id.img);
                bottomView = (RelativeLayout) view.findViewById(BottomView);
                title = (TextView) view.findViewById(R.id.title);
                point = (TextView) view.findViewById(R.id.point);
            }

            @Override
            protected View getView() {
                return view;
            }
        }
    }

    // 获取vip信息
    private boolean checkIsVip() {
        String isvip= AuthSDK.getInstance().getValue("vipState");
        return isvip.isEmpty()?false:true;
    }



    /********************************************************************************************/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDialog = this;
        setContentView(view);
        Window window = getWindow();
        window.setWindowAnimations(R.style.dialogInOutAnim);
    }


    public DialogAssetExitApp(Context context) {
        super(context,R.style.error_dialog);
        init(context);
    }

    public DialogAssetExitApp(Context context, int themeResId) {
        super(context, themeResId);
        init(context);
    }

    protected DialogAssetExitApp(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        init(context);
    }
}
