package com.taikor.investment.adapter;

import android.app.Activity;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.taikor.investment.bean.Product;
import com.taikor.investment.R;
import com.taikor.investment.base.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 智能投顾，自定义，添加产品中产品列表适配器
 * Created by Any on 2017/4/14.
 */
public class GroupProductAdapter extends BaseAdapter<Product> {

    private List<Product> mList;
    private SparseBooleanArray mSelectedPositions = new SparseBooleanArray();

    public GroupProductAdapter(Activity context) {
        super(context);
    }

    public void setList(List<Product> List) {
        this.mList = List;
    }

    @Override
    protected int getItemLayoutId(int itemViewType) {
        return R.layout.item_group_product;
    }

    @Override
    protected void handleItem(int itemViewType, final int position, Product item, ViewHolder holder, boolean reused) {
        //设置条目状态  
        holder.get(R.id.tv_product_id, TextView.class).setText(item.getProductID());
        holder.get(R.id.tv_product_name, TextView.class).setText(item.getProductName());
        CheckBox checkBox = holder.get(R.id.cb_add, CheckBox.class);
        checkBox.setChecked(isItemChecked(position));
        //checkBox的监听  
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isItemChecked(position)) {
                    setItemChecked(position, false);

                } else {
                    setItemChecked(position, true);
                }
            }
        });
    }

    //获得选中条目的结果
    public ArrayList<Product> getSelectedItem() {
        ArrayList<Product> selectList = new ArrayList<>();
        if(mList!=null){
            for (int i = 0; i < mList.size(); i++) {
                if (isItemChecked(i)) {
                    selectList.add(mList.get(i));
                }
            }
        }
        return selectList;
    }

    //设置给定位置条目的选择状态
    private void setItemChecked(int position, boolean isChecked) {
        mSelectedPositions.put(position, isChecked);
    }

    //根据位置判断条目是否选中
    private boolean isItemChecked(int position) {
        return mSelectedPositions.get(position);
    }
}
