package com.rv.rvmine.traveler;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.base.utils.tools.java.DateUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.member.ConsumeRecordActivity;
import com.rv.member.MemberCenterActivity;
import com.rv.member.PurchaseRecordActivity;
import com.rv.rvmine.R2;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.BaseStatusActivity;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
import com.rv.rvmine.R;
import com.rv.rvmine.adapter.TravelerListAdapter;
import com.rv.rvmine.bean.DeleteInfo;
import com.rv.rvmine.bean.DeleteVistorBean;
import com.rv.rvmine.bean.TravelerListBean;
import com.rv.rvmine.view.DeletePopupWindow;
import com.yuyife.okgo.OkGoUtil;

import java.sql.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 选择出游人
 */
@Route(path = Constance.ACTIVITY_URL_CHOOSEAVISITOR)
public class ChooseAVisitorActivity extends BaseStatusActivity<CommonPresenter> {

    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.tv_select_result)
    TextView tvSelelctResult;
    @BindView(R2.id.btn_confirm)
    Button btnConfim;

    private TravelerListAdapter mAdapter;
    private final int TYPE_REQUEST_ADD = 105;
    private final int TYPE_REQUEST_EDIT = 2;
    private int mPage;
    private int countPage;
    private int openType;
    private DeletePopupWindow deletePopupWindow;
    private List<TravelerListBean.DataBean> visitors = new ArrayList<>();
    private TravelerListBean.DataBean deletBean = null;
    private List<TravelerListBean.DataBean> adults = null;
    private List<TravelerListBean.DataBean> childs = null;

    private String hasChoIdCards; // 传过来的已经选择的身份证
    private int adultNumber; //成人数量
    private int childBumber; // 小孩数量

    @Override
    protected int setLayout() {
        return R.layout.activity_choose_avisitor;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        openType = intent.getIntExtra("openType", 0);
        if (openType != 0) {
            adultNumber = intent.getIntExtra("adult_number", 0);
            childBumber = intent.getIntExtra("child_number", 0);
            if (adultNumber != 0) {
                StringBuilder builder = new StringBuilder();
                builder.append("请选择").append(adultNumber).append("位成人");
                if (childBumber > 0) {
                    builder.append(",").append(childBumber).append("位儿童");
                }
                tvSelelctResult.setVisibility(View.VISIBLE);
                tvSelelctResult.setText(builder.toString());
            }
            btnConfim.setVisibility(View.VISIBLE);
        }

        hasChoIdCards = intent.getStringExtra("hasChoice");
        if (openType == 0) {
            titleView.setTitle("出游人");
        } else {
            titleView.setTitle("选择出游人");
        }
        titleView.setImageResource(R.id.iv_title_right, R.drawable.rv_common_icon_thestaff);
        titleView.setChildClickListener(R.id.iv_title_right, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(AddAVisitorActivity.getIntent(mActivity, null), TYPE_REQUEST_ADD);
            }
        });

        mAdapter = new TravelerListAdapter(openType, selectListener);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_edit) {
                    startActivityForResult(AddAVisitorActivity.getIntent(mActivity, mAdapter.getItem(position)), TYPE_REQUEST_ADD);
                }
            }
        });
        mAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                deletBean = visitors.get(position);
                showDeletePopupWindow(view);
                return true;
            }
        });
    }

    private void showDeletePopupWindow(View view) {
        if (deletePopupWindow == null) {
            deletePopupWindow = new DeletePopupWindow(this, new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    deleteDriver();
                    deletePopupWindow.dismiss();
                }
            });
            deletePopupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        }
        deletePopupWindow.showAsDropDown(view, view.getWidth() / 2 - deletePopupWindow.getContentView().getMeasuredWidth() / 2,
                -deletePopupWindow.getContentView().getHeight() / 2);

    }


    @OnClick({R2.id.btn_confirm})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_confirm) {
            if (mAdapter != null) {
                int remainChild = 0;
                int remainAdult = 0;
                if (childs != null) {
                    remainChild = childBumber - childs.size();
                }
                if (adults != null) {
                    remainAdult = adultNumber - adults.size();
                }
                if (remainAdult != 0 || remainChild != 0) {
                    showToast("你还有" + (remainAdult + remainChild) + "位出游人还未选择");
                    return;
                }
                ArrayList<String> names = new ArrayList<>();
                ArrayList<String> phones = new ArrayList<>();
                ArrayList<String> idcards = new ArrayList<>();
                ArrayList<String> ids = new ArrayList<>();
                if (adults != null)
                    for (TravelerListBean.DataBean bean : adults) {
                        names.add(bean.getName());
                        phones.add(bean.getPhone());
                        idcards.add(bean.getIdCard());
                        ids.add(bean.getId() + "");
                    }

                if (childs != null)
                    for (TravelerListBean.DataBean bean : childs) {
                        names.add(bean.getName());
                        phones.add(bean.getPhone());
                        idcards.add(bean.getIdCard());
                        ids.add(bean.getId() + "");
                    }
                Intent intent1 = getIntent();
                intent1.putStringArrayListExtra("name", names);
                intent1.putStringArrayListExtra("phone", phones);
                intent1.putStringArrayListExtra("idcard", idcards);
                intent1.putStringArrayListExtra("id", ids);
                setResult(RESULT_OK, intent1);
                finish();
            }
        }
    }

//    @Override
//    public void finish() {
//        if (openType != 0) {
//            Intent intent = new Intent();
//            ArrayList<TravelerListBean.DataBean> selects;
////            if (selectBean == null) {
////                selectBean = mAdapter.getHasSelectBean();
////            }
////            if (selectBean != null) {
//                intent.putExtra("name", selectBean.getName());
//                intent.putExtra("phone", selectBean.getPhone());
//                intent.putExtra("idcard", selectBean.getIdCard());
//                intent.putExtra("id", selectBean.getId());
//                setResult(RESULT_OK, intent);
////            }
//
//        }
//        super.finish();
//    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        getDrivingList();
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        if (requestType == 0) {
            processData((TravelerListBean) result);
        } else if (requestType == 1) {
            DeleteVistorBean bean = (DeleteVistorBean) result;
            if (bean != null) {
                if (bean.isRel()) {
                    if (deletBean != null) {
                        int index = visitors.indexOf(deletBean);
                        if (index != -1) {
                            visitors.remove(index);
                            mAdapter.notifyDataSetChanged();
                        }
                        if (adults != null)
                            adults.remove(deletBean);
                        if (childs != null)
                            childs.remove(deletBean);
                        deletBean = null;
                    }
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TYPE_REQUEST_ADD && resultCode == RESULT_OK) {
            getDrivingList();
        }
    }

    /**
     *
     */
    private void getDrivingList() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.getDataHead(RvFrameConfig.VEHICLE_TOURUSER, 0, ApiConfig.HTTP_URL_GETTOURUSERLIST, TravelerListBean.class, headMap, true);
    }


    private void processData(TravelerListBean bean) {
        if (bean.getData() == null || bean.getData().size() == 0) {
            mAdapter.setEmptyView(getEmptyView(recyclerView, -1, "您还没有出游人信息哦"));
            return;
        }
        visitors.clear();
//        if (adults != null) adults.clear();
//        if (childs != null) childs.clear();
        for (TravelerListBean.DataBean b : bean.getData()) {
            if (!TextUtils.isEmpty(hasChoIdCards) && hasChoIdCards.contains(b.getIdCard())) {
                b.setStatus(true);
                if (b.getIsChild() == 0) {
                    if (adults == null && adultNumber > 0) {
                        adults = new ArrayList<>(adultNumber);
                    }
                    if (adults != null)
                        adults.add(b);
                } else {
                    if (childs == null && childBumber > 0) {
                        childs = new ArrayList<>(childBumber);
                    }
                    if (childs != null)
                        childs.add(b);
                }
            }
            visitors.add(b);
        }

        Collections.sort(visitors, new Comparator<TravelerListBean.DataBean>() {
            @Override
            public int compare(TravelerListBean.DataBean bean, TravelerListBean.DataBean t1) {

                long crT = Long.valueOf(bean.getCrtTime());
                long crT1 = Long.valueOf(t1.getCrtTime());
                return (int) (crT1 - crT);
            }
        });

        if (visitors.isEmpty()) {
            mAdapter.setEmptyView(getEmptyView(recyclerView, -1, "您还没有出游人信息哦"));
        } else {
            mAdapter.setNewData(visitors);
        }
    }

    private void deleteDriver() {
        if (deletBean != null) {
            Map<String, Object> headMap = new LinkedHashMap<>();
            if (OkGoUtil.getToken() != null)
                headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.postBodyData(1, ApiConfig.HTTP_URL_DELETEDRIVER, DeleteVistorBean.class, new DeleteInfo(deletBean.getId()), headMap, true);
        }
    }

    private TravelerListAdapter.SelectListener selectListener = new TravelerListAdapter.SelectListener() {
        @Override
        public boolean select(TravelerListBean.DataBean bean, int action) {
            if (bean != null) {
                if (bean.getIsChild() == 0) {  // 成人
                    if (adults == null && adultNumber > 0) {
                        adults = new ArrayList<>(adultNumber);
                    }
                    if (adultNumber == 0) {
                        return false;
                    }
                    if (action == 0) { // 取消选中
                        return adults.remove(bean);
                    } else {  // 选中
                        if (adults.contains(bean)) {
                            return false;
                        }
                        if (adults.size() >= adultNumber) {
                            return false;
                        }
                        return adults.add(bean);
                    }
                } else {  // 儿童
                    if (childBumber == 0) {
                        return false;
                    }
                    if (childs == null && childBumber > 0) {
                        childs = new ArrayList<>(childBumber);
                    }
                    if (action == 0) {
                        return childs.remove(bean);
                    } else {
                        if (childs.contains(bean)) {
                            return false;
                        }
                        if (childs.size() >= childBumber) {
                            return false;
                        }
                        return childs.add(bean);
                    }
                }
            }
            return false;
        }

        @Override
        public void showError() {
            StringBuilder builder = new StringBuilder();
            builder.append("只可选择").append(adultNumber).append("位成人");
            if (childBumber > 0) {
                builder.append(",").append(childBumber).append("位儿童");
            }
            showToast(builder.toString());
        }
    };

}
