package com.kfzs.duanduan.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.android.volleyplus.Response;
import com.android.volleyplus.VolleyError;
import com.kf.utils.ToastBuilder;
import com.kfzs.android.view.tag.TagFlowLayout;
import com.kfzs.appstore.utils.restful.KFZSNetwork;
import com.kfzs.appstore.utils.restful.KFZSRestfulError;
import com.kfzs.appstore.utils.restful.KFZSRestfulErrorCallBack;
import com.kfzs.duanduan.KFZSApp;
import com.sheep.jiuyan.samllsheep.R;
import com.kfzs.duanduan.adp.FilterWindowAdapter;
import com.kfzs.duanduan.bean.QueryCondition;
import com.kfzs.duanduan.bll.UrlBll;
import com.kfzs.duanduan.proto.ApiResponseOuterClass;
import com.kfzs.duanduan.proto.GameTypeOuterClass;
import com.kfzs.duanduan.utils.net.ResponseNetworkTask;
import com.kfzs.duanduan.utils.net.APIRequest;
import com.kfzs.duanduan.utils.net.APIRequestInstance;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 游戏分类检索条件
 * Created by HooRang on 2017/2/16.
 */
public class FilterWindow implements View.OnClickListener {
    private static final String TAG = FilterWindow.class.getSimpleName();
    private Context mContext ;

    private View vAnchor ;
    private View contentView;

    private PopupWindow popupWindow;

    private Button btnReset , btnSubmit ;

    private ListView lvConditions;
    private FilterWindowAdapter qcAdapter ;

    private OnPopupWinListener onPopupWinListener;

    private List<QueryCondition> conditions;

    private static Map<Integer , Set<Integer>> mCheckedTagsContainer = new HashMap<>();

    public FilterWindow(Context ctx, View anchor,OnPopupWinListener listener){

        this.mContext = ctx;
        this.vAnchor  = anchor;
        this.onPopupWinListener = listener;
    }


   public FilterWindow createWindow(){

        if (popupWindow != null){
            return this;
        }
        contentView = LayoutInflater.from(mContext).inflate(R.layout.popupwindow_query_condition,null);

        initConditionList();


        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            popupWindow.setAnimationStyle(0);
        }

        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                onPopupWinListener.dismiss();
            }
        });

       lvConditions = contentView.findViewById(R.id.popupwindow_query_condition_listview);
       lvConditions.addFooterView(initListViewFooterButtonArea());
       qcAdapter = new FilterWindowAdapter(mContext);

        return this;
    }



    public void show(){
        if (popupWindow != null){
            setTagListViewSelectedStatus();
            popupWindow.showAsDropDown(vAnchor, 2, 0);
        }

    }


    private void initConditionList(){

        final Response.ErrorListener errorListener = KFZSRestfulError.job(new KFZSRestfulErrorCallBack() {
            @Override
            public void callErrorJob(boolean flag, int code, VolleyError error) {
                ToastBuilder.make(KFZSApp.context, R.string.toast_init_data_fail, ToastBuilder.DEFAULT_TOAST_SINGLE);
            }
        });


        APIRequest bannerRequest = APIRequestInstance.getReq(TAG, UrlBll.AppStoreApi.GAME_TYPES, null, new ResponseNetworkTask() {

            @Override
            public void onSuccess(ApiResponseOuterClass.ApiResponse apiResponse) {

                conditions = new ArrayList<>();
                QueryCondition qcTheme = new QueryCondition();
                qcTheme.setCategoryIcon(R.mipmap.icon_category_theme);
                qcTheme.setTags(apiResponse.getGameTypeClass().getTypeThreeList());

                QueryCondition qcPlay = new QueryCondition();
                qcPlay.setCategoryIcon(R.mipmap.icon_category_play);
                qcPlay.setTags(apiResponse.getGameTypeClass().getTypeTwoList());

                QueryCondition qcGame = new QueryCondition();
                qcGame.setCategoryIcon(R.mipmap.icon_category_game);
                qcGame.setTags(apiResponse.getGameTypeClass().getTypeOneList());


                conditions.add(qcGame);
                conditions.add(qcPlay);
                conditions.add(qcTheme);

                qcAdapter.addMoreDatas(conditions);
                lvConditions.setAdapter(qcAdapter);


            }

            @Override
            public void onFail(int code, String msg) {

            }

        }, errorListener);

        KFZSNetwork.addRequest(bannerRequest);


    }


    private void setTagListViewSelectedStatus(){

        for(Integer index : mCheckedTagsContainer.keySet()){
            Set<Integer> subCollectionSet = mCheckedTagsContainer.get(index);
            for(Integer subIndex : subCollectionSet){
                Log.d(TAG , "subIndex#" + subIndex );
            }
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.popupwindow_query_condition_btn_reset:
                if(null != popupWindow){
                    popupWindow.dismiss();
                    mCheckedTagsContainer.clear();
                    onPopupWinListener.onReset();
                }
                break;

            case R.id.popupwindow_query_condition_btn_submit:

                if(null != popupWindow){
                    popupWindow.dismiss();
                }


                StringBuilder selectedTagIndex = new StringBuilder();
                for(int i = 0 ; i < conditions.size() ; i ++){
                    TagFlowLayout tflContent = contentView.findViewWithTag(FilterWindowAdapter.FLOW_LAYOUT_TAG + i);
                    if (tflContent == null){
                        return ;
                    }
                    Set<Integer> selectedList =  tflContent.getSelectedList();
                    selectedTagIndex.append(getGameTypesIndex(i, selectedList));

                    mCheckedTagsContainer.put(i , selectedList);
                }

                if ("".equals(selectedTagIndex.toString())){
                    return ;
                }

                onPopupWinListener.onSubmit(selectedTagIndex.substring(0 , selectedTagIndex.length() - 1));

                break;
        }
    }


    private View initListViewFooterButtonArea(){

        View tvFooter = LayoutInflater.from(mContext).inflate(R.layout.listview_item_query_condition_footer,null);

        btnReset  = tvFooter.findViewById(R.id.popupwindow_query_condition_btn_reset);
        btnSubmit = tvFooter.findViewById(R.id.popupwindow_query_condition_btn_submit);
        btnReset.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);

        return tvFooter ;
    }

    private String getGameTypesIndex(int category , Set<Integer> selectedList){
        List<GameTypeOuterClass.GameType> types = conditions.get(category).getTags();

        StringBuilder strTempIndex = new StringBuilder();
        for(Integer index : selectedList){
            strTempIndex.append(types.get(index).getId()).append(",");
        }

        return strTempIndex.toString();
    }

    public static Map<Integer , Set<Integer>> getCheckedTagsContainer(){
        return mCheckedTagsContainer;
    }

   public interface OnPopupWinListener{

        void onReset();

        void onSubmit(String selectedIndexs);

        void dismiss();

    }

    public boolean isShow(){
        return popupWindow.isShowing() ;
    }



}
