package com.rv.rvmine.traveler;

import android.content.Intent;
import android.os.Bundle;
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 com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.base.bus.LoginSuccessfulEvent;
import com.frame.base.bus.Observer;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.rvmine.R2;
import com.rv.home.rv.module.ApiConfig;
import com.ruiwenliu.wrapper.base.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.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 选择出游人 / 选择出游人
 * <p>
 * 添加
 */
@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<Integer> adults;
    private List<Integer> childs;

    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);
        initRxBus();
        if (openType != 0) {
            adultNumber = intent.getIntExtra("adult_number", 0);
            childBumber = intent.getIntExtra("child_number", 0);
            if (adultNumber > 0) {
                adults = new ArrayList<>(adultNumber);
            }
            if (childBumber > 0) {
                childs = new ArrayList<>(childBumber);
            }
            String hasChoiceAdults = intent.getStringExtra("hasChoiceAdults");
            if (!TextUtils.isEmpty(hasChoiceAdults)) {
                String[] choiceAdult = hasChoiceAdults.split(";");
                if (adults != null && choiceAdult.length > 0) {
                    for (String s : choiceAdult) {
                        adults.add(Integer.valueOf(s));
                    }
                }
            }
            String hasChoiceChilds = intent.getStringExtra("hasChoiceChilds");
            if (!TextUtils.isEmpty(hasChoiceChilds)) {
                String[] choiceChilds = hasChoiceChilds.split(";");
                if (childs != null && choiceChilds.length > 0) {
                    for (String s : choiceChilds) {
                        childs.add(Integer.valueOf(s));
                    }
                }
            }

            StringBuilder builder = new StringBuilder();
            builder.append("请选择");

            if (adultNumber != 0) {
                builder.append(adultNumber).append("位成人");
            }
            if (childBumber > 0) {
                if (builder.length() == 3) {
                    builder.append(",");
                }
                builder.append(childBumber).append("位儿童");
            }
            tvSelelctResult.setVisibility(View.VISIBLE);
            tvSelelctResult.setText(builder.toString());
            btnConfim.setVisibility(View.VISIBLE);
        }

        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());
    }


    @OnClick({R2.id.btn_confirm})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_confirm) {
            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<>();
            for (TravelerListBean.DataBean bean : visitors) {
                if (adults != null && adults.contains(bean.getId())) {
                    names.add(bean.getName());
                    phones.add(bean.getPhone());
                    idcards.add(bean.getIdCard());
                    ids.add(bean.getId() + "");
                }
            }
            for (TravelerListBean.DataBean bean : visitors) {
                if (childs != null && childs.contains(bean.getId())) {
                    names.add(bean.getName());
                    phones.add(bean.getPhone());
                    idcards.add(bean.getIdCard());
                    ids.add(bean.getId() + "");
                }

            }
            Intent intent = getIntent();
            intent.putStringArrayListExtra("name", names);
            intent.putStringArrayListExtra("phone", phones);
            intent.putStringArrayListExtra("idcard", idcards);
            intent.putStringArrayListExtra("id", ids);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    @Override
    public void finish() {
        super.finish();
    }

    private void initRxBus() {
        RxBus.tObservable(LoginSuccessfulEvent.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginSuccessfulEvent>(disposable) {
                    @Override
                    public void onNext(LoginSuccessfulEvent event) {
                        getDrivingList();
                    }
                });

    }

    @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.getId());
                        if (childs != null)
                            childs.remove(deletBean.getId());
                        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();

        for (TravelerListBean.DataBean b : bean.getData()) {
            if (b.getIsChild() == 0) { // 成人
                if (adults != null && adults.contains(b.getId())) {
                    b.setStatus(true);
                }
            } else { // 儿童
                if (childs != null && childs.contains(b.getId())) {
                    b.setStatus(true);
                }
            }
            visitors.add(b);
        }
        dealAdults();
        dealChilds();

        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 dealAdults() {
        if (adults != null) {
            Iterator<Integer> iterator = adults.iterator();
            while (iterator.hasNext()) {
                Integer integer = iterator.next();
                boolean isContain = false;
                for (TravelerListBean.DataBean bean : visitors) {
                    if (bean.getId() == integer.intValue()) {
                        isContain = true;
                    }
                }
                if (!isContain) {
                    iterator.remove();
                }
            }
        }
    }

    private void dealChilds() {
        if (childs != null) {
            Iterator<Integer> iterator = childs.iterator();
            while (iterator.hasNext()) {
                Integer integer = iterator.next();
                boolean isContain = false;
                for (TravelerListBean.DataBean bean : visitors) {
                    if (bean.getId() == integer.intValue()) {
                        isContain = true;
                    }
                }
                if (!isContain) {
                    iterator.remove();
                }
            }
        }
    }


    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 (adultNumber == 0) return false;
                    if (action == 0) return adults.remove(bean.getId());
                    else {  // 选中
                        if (adults.contains(bean.getId())) return false;
                        if (adults.size() >= adultNumber) return false;
                        return adults.add(bean.getId());
                    }
                } else {  // 儿童
                    if (childBumber == 0) return false;

                    if (action == 0) return childs.remove(bean.getId());

                    else {
                        if (childs.contains(bean.getId())) return false;
                        if (childs.size() >= childBumber) return false;
                        return childs.add(bean.getId());
                    }
                }
            }
            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());
        }
    };

}
