package com.chexiang.myhome.module.cards.card;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chexiang.myhome.R;
import com.chexiang.myhome.base.BFragment;
import com.chexiang.myhome.base.adapter.recycleview.BRAdapter;
import com.chexiang.myhome.base.adapter.recycleview.RvHolder;
import com.chexiang.myhome.base.constant.Parameter;
import com.chexiang.myhome.base.http.retrofit.client.RetrofitFactory;
import com.chexiang.myhome.base.http.retrofit.stub.CodeStub;
import com.chexiang.myhome.base.http.retrofit.stub.RMCallback;
import com.chexiang.myhome.base.http.retrofit.stub.RMResponse;
import com.chexiang.myhome.base.model.BModel;
import com.chexiang.myhome.external.pull.YRecycleview;
import com.chexiang.myhome.model.KVModel;
import com.chexiang.myhome.model.card.CardTemplateModel;
import com.chexiang.myhome.model.card.ForSellCardListInfo;
import com.chexiang.myhome.model.inquiry.SelectedListInfo;
import com.chexiang.myhome.model.order.PageModel;
import com.chexiang.myhome.service.CardService;
import com.chexiang.myhome.utils.ToastUtil;
import com.chexiang.myhome.widget.components.EmptyView;
import com.chexiang.myhome.widget.custom.SelectedButton;

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

import butterknife.BindView;
import butterknife.OnClick;

import static com.chexiang.myhome.R.id.rv_selected_card;


/**
 * 选择卡界面
 */

public class SelectCardTypeFragment extends BFragment {
    private  String tempCardTemplateName;
    private  String tempCardTemplateId;
    @BindView(R.id.tv_cardTemplate)
    TextView mCardTemplate;//卡模板
    @BindView(R.id.tv_cardName)
    EditText tv_cardName;
    @BindView(R.id.tv_cardNo)
    EditText tv_cardNo;
    @BindView(rv_selected_card)
    RecyclerView mRecyclerSelected;//显示的选中的卡集合
    @BindView(R.id.rv_select_card_type)
    YRecycleview rvSelectCardType;//展示list
    @BindView(R.id.empty_view)
    EmptyView empty_view;


    private ListPopupWindow listPopupWindow;//卡模板下拉列表
    private List<String> cardTemplateList = new ArrayList<>();//卡模板下拉列表内容
    private List<KVModel> sparseArray = new ArrayList();
    private List<SelectedListInfo> selectedList = new ArrayList<>();//选中的卡要显示的名称
    private List<ForSellCardListInfo.ForSellCardListDet> cardList = new ArrayList<>();//展示列表

    private View view;
    private BRAdapter<SelectedListInfo> selectedAdapter;
    private BRAdapter<ForSellCardListInfo.ForSellCardListDet> selectCardTypeAdapter;
    private SparseBooleanArray selected = new SparseBooleanArray();//绑定按钮样式
    private String cardTemplateId = "";//卡模板ID或key
    private int currentPage = new PageModel().currentPage;
    private boolean isRefresh = true;

    public void  setArgue(String cardTemplateId, String cardTemplateName) {
        this.tempCardTemplateName = cardTemplateName;
        this.tempCardTemplateId = cardTemplateId;
    }

    public SelectCardTypeFragment(){}
    @Override
    public void initView() {
        initAdapter();
        setTempCardIdStatus();
        getCardTemplate();
        queryData();
        initSelectedList();//显示选中的集合
    }

    //根据卡模版id对卡模版状态设置
    private void setTempCardIdStatus() {
        if (tempCardTemplateId != null && !"".equals(tempCardTemplateId)) {
            tv_cardName.setText(tempCardTemplateName);
            tv_cardName.setEnabled(false);
            tv_cardName.setBackgroundResource(R.drawable.solid_square_gray);
//            tv_cardNo.setBackgroundResource(R.drawable.shape_et_bg_white);
        }
    }

    @Override
    protected View initRootView(LayoutInflater inflater) {
        if (view == null)
            view = inflater.inflate(R.layout.fragment_select_card_type, null);
        return view;
    }

    @OnClick({R.id.tv_close, R.id.tv_cardTemplate, R.id.tv_query, R.id.tv_sure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_close:
                activity.popFragment();
                break;
            case R.id.tv_cardTemplate:
                initListPop();
                listPopupWindow.show();
                break;
            case R.id.tv_query:
                isRefresh = true;
                queryData();
                break;
            case R.id.tv_sure:
                if ("".equals(SEDCardinfo.cardId)) {
                    ToastUtil.showToast(activity, "请选择卡号!");
                    return;
                }
                activity.popFragment();
                sendBackArgument(Activity.RESULT_OK);
                break;
            default:
                break;
        }
    }


    /*
    将选中需要显示的卡列表集合回传到上一个页面去显示
     */
    public void sendBackArgument(int resultCode) {
        if (getTargetFragment() == null) {
            return;
        } else {
            Intent intent = new Intent();
            if (SEDCardinfo != null) {
                intent.putExtra(Parameter.SELECTEDCARDTYPEFRAGMENT01, SEDCardinfo.cardId);
                intent.putExtra(Parameter.SELECTEDCARDTYPEFRAGMENT02, SEDCardinfo.cardTemplateId);
                getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
            }
        }
    }

    /**
     * 选中的卡的adapter初始化
     */
    public void initSelectedList() {
        selectedAdapter = new BRAdapter<SelectedListInfo>(getContext(), R.layout.item_selected_show_list, selectedList) {
            @Override
            protected void convert(RvHolder holder, final SelectedListInfo selectedListInfo, final int position) {
                holder.setText(R.id.tv_name, selectedListInfo.name);

                holder.setOnClickListener(R.id.tv_cancle, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //取消就清空参数model
                        SEDCardinfo.cardId = "";
                        SEDCardinfo.cardTemplateId = "";
                        selectedList.clear();
                        selected.clear();
                        selectedAdapter.notifyDataSetChanged();
                        selectCardTypeAdapter.notifyDataSetChanged();
                    }
                });
            }
        };
        mRecyclerSelected.setAdapter(selectedAdapter);
        mRecyclerSelected.setLayoutManager(new GridLayoutManager(getContext(), 3));
    }

    /**
     * 初始化选择列表适配器
     */
    private SelectedListInfo SEDCardinfo = new SelectedListInfo();

    public void initAdapter() {
        selectCardTypeAdapter = new BRAdapter<ForSellCardListInfo.ForSellCardListDet>(getContext(), R.layout.item_select_card_type, cardList) {
            @Override
            protected void convert(RvHolder holder, final ForSellCardListInfo.ForSellCardListDet forSellCardListDet, final int position) {
                holder.setText(R.id.tv_cardNo, forSellCardListDet.cardNo);
                holder.setText(R.id.tv_cardName, forSellCardListDet.cardTemplateName);
                final SelectedButton tvSelect = holder.getView(R.id.tv_select);//选择按钮
                tvSelect.setSelectStatus(selected.get(position));//绑定按钮样式

                tvSelect.setOnCustomClickListener(new SelectedButton.OnCheckedChangedListener() {
                    @Override
                    public void onCheckedChanged(boolean isSelect) {

                        if (isSelect) {
                            //选择后添加到显示列表
                            SelectedListInfo selectCardinfo = new SelectedListInfo();
                            selectCardinfo.name = forSellCardListDet.cardTemplateName;
                            selectCardinfo.position = position;
                            selectCardinfo.id = forSellCardListDet.cardId;

                            //使用model存储当前选择的数据--接口需要
                            SEDCardinfo.cardId = forSellCardListDet.cardId;
                            SEDCardinfo.cardTemplateId = forSellCardListDet.cardTemplateId;


                            if (selectedList.size() > 0) {
                                tvSelect.setSelectStatus(false);//绑定按钮样式
                                ToastUtil.showToast(getContext(), "只能选择一张卡");

                            } else {
                                tvSelect.setSelectStatus(true);//绑定按钮样式
                                selectedList.add(selectCardinfo);
                                selected.put(position, true);
                            }
                        } else {
                            //取消就清空参数model
                            SEDCardinfo.cardId = "";
                            SEDCardinfo.cardTemplateId = "";
                            selectedList.clear();
                            selected.clear();
                        }
                        selectedAdapter.notifyDataSetChanged();
                    }
                });

            }
        };
        rvSelectCardType.setLayoutManager(new LinearLayoutManager(getContext()));
        rvSelectCardType.setAdapter(selectCardTypeAdapter);
        rvSelectCardType.setRefreshAndLoadMoreListener(new YRecycleview.OnRefreshAndLoadMoreListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                queryData();
            }

            @Override
            public void onLoadMore() {
                isRefresh = false;
                queryData();
            }
        });
    }


    /*
   初始化模板类型选择下拉列表
    */
    public void initListPop() {
        listPopupWindow = new ListPopupWindow(getContext());
        ArrayAdapter arrayAdapter = new ArrayAdapter(getContext(), R.layout.item_list_pop, cardTemplateList);
        listPopupWindow.setAdapter(arrayAdapter);
        listPopupWindow.setWidth(RelativeLayout.LayoutParams.WRAP_CONTENT);
        listPopupWindow.setHeight(RelativeLayout.LayoutParams.WRAP_CONTENT);
        listPopupWindow.setAnchorView(mCardTemplate);
        listPopupWindow.setModal(true);
        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mCardTemplate.setText(cardTemplateList.get(position));
                if ("2".equals(sparseArray.get(position).key)) {//虚拟卡
                    setEnabledStatus(false);
                } else {
                    setEnabledStatus(true);
                }
                cardTemplateId = sparseArray.get(position).key;
                listPopupWindow.dismiss();
            }
        });
    }

    /*
        卡模板类型
     */
    public void getCardTemplate() {
        CardTemplateModel.getCardPlatType(new BModel.Transit<CardTemplateModel>(activity) {
            @Override
            public void onBorn(CardTemplateModel serializable, String code, String message) {
                if (code.equals(CodeStub.B_OK)) {
                    if (null != serializable) {
                        List<KVModel> cardTemplateDetList = serializable.cardTemplateTypeList;
                        if (null != cardTemplateDetList && cardTemplateDetList.size() > 0) {
                            for (KVModel cardTemplateDet : cardTemplateDetList) {
                                cardTemplateList.add(cardTemplateDet.value);
                                sparseArray.add(cardTemplateDet);
                                if ("2".equals(cardTemplateDet.key)) {//虚拟卡
                                    mCardTemplate.setText(cardTemplateDet.value);
                                    cardTemplateId = cardTemplateDet.key;
                                    setEnabledStatus(false);
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    //改变卡号输入框状态
    private void setEnabledStatus(boolean b) {
        tv_cardNo.setText("");
        tv_cardNo.setEnabled(b);
        if (b == true) {
            tv_cardNo.setBackgroundResource(R.drawable.shape_et_bg_white);
        } else {
            tv_cardNo.setBackgroundResource(R.drawable.solid_square_gray);
        }
    }

    /*
    查询按钮接口
     */
    public void queryData() {
        showProgress();
        if (isRefresh) {
            cardList.clear();
            selected.clear();
            selectedList.clear();
            selectCardTypeAdapter.notifyDataSetChanged();
            currentPage = new PageModel().currentPage;
        }
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        map2.put("currentPage", currentPage);
        map1.put("pager", map2);
        map1.put("cardTemplateType", cardTemplateId);
        map1.put("cardTemplateName", getStrValue(tv_cardName));
        map1.put("cardNo", getStrValue(tv_cardNo));
        RetrofitFactory.getInstance()
                .create(CardService.class)
                .postForCardSell(map1)
                .enqueue(new RMCallback<RMResponse<ForSellCardListInfo>>(getContext()) {
                    @Override
                    protected void onSuccess(RMResponse<ForSellCardListInfo> result) {
                        dismissProgress();
                        if (null != result) {
                            if (null != result.content.cardList && result.content.cardList.size() > 0) {
                                currentPage++;
                                cardList.addAll(result.content.cardList);
                                selectCardTypeAdapter.notifyDataSetChanged();
                                if (cardList.size() == 0) {
                                    empty_view.setVisibility(View.VISIBLE);
                                } else {
                                    empty_view.setVisibility(View.GONE);
                                }
                            }
                        }
                        if (isRefresh) {
                            rvSelectCardType.setReFreshComplete();
                        } else {
                            rvSelectCardType.setloadMoreComplete();
                        }
                    }

                    @Override
                    protected void onFail(String errorCode, String errorInfo) {
                        dismissProgress();
                        ToastUtil.showToast(getContext(), errorInfo);
                        if (isRefresh) {
                            rvSelectCardType.setReFreshComplete();
                        } else {
                            rvSelectCardType.setloadMoreComplete();
                        }
                    }
                });
    }

}