package com.navinfo.outdoor.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.interfaces.OnMenuItemClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.util.DialogSettings;
import com.kongzue.dialog.v3.BottomMenu;
import com.kongzue.dialog.v3.MessageDialog;
import com.lzy.okgo.model.HttpParams;
import com.navinfo.outdoor.R;
import com.navinfo.outdoor.activity.FragmentManagement;
import com.navinfo.outdoor.adapter.StaySubmitAdapter;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.base.BaseFragment;
import com.navinfo.outdoor.bean.UnPolygonTaskBean;
import com.navinfo.outdoor.http.Callback;
import com.navinfo.outdoor.http.HttpInterface;
import com.navinfo.outdoor.http.OkGoBuilder;
import com.navinfo.outdoor.room.PoiDao;
import com.navinfo.outdoor.room.PoiDatabase;
import com.navinfo.outdoor.room.PoiEntity;
import com.navinfo.outdoor.util.PoiSaveUtils;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

/**
 * 记录-待提交的fragment
 */
public class StaySubmitFragment extends BaseFragment implements View.OnClickListener {
    private RecyclerView stayXrv;
    private CheckBox cbSelect;
    private TextView tvDelete;
    private Button btnStaySubmit;
    private StaySubmitAdapter staySubmitAdapter;
    private PoiDatabase roadDatabase;
    private PoiDao roadDao;
    private TextView tvStayType;
    private List<PoiEntity> roadEntities;
    private ArrayList<PoiEntity> newEntities;
    private ArrayList<PoiEntity> poiEntities;


    public static StaySubmitFragment newInstance(Bundle bundle) {
        StaySubmitFragment fragment = new StaySubmitFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }

    }


    @Override
    protected int getLayout() {
        return R.layout.fragment_stay_submit;
    }

    @Override
    protected void initView() {
        super.initView();
        roadDatabase = PoiDatabase.getInstance(getContext());
        roadDao = roadDatabase.getPoiDao();
        ConstraintLayout clStayType = findViewById(R.id.cl_stay_type);
        clStayType.setOnClickListener(this::onClick);
        stayXrv = (RecyclerView) findViewById(R.id.stay_xrv);
        cbSelect = (CheckBox) findViewById(R.id.cb_select);
        cbSelect.setOnClickListener(this::onClick);
        tvDelete = (TextView) findViewById(R.id.tv_delete);
        tvDelete.setOnClickListener(this::onClick);
        tvStayType = findViewById(R.id.tv_stay_type);
        btnStaySubmit = (Button) findViewById(R.id.btn_stay_submit);
        btnStaySubmit.setOnClickListener(this::onClick);
        stayXrv.setLayoutManager(new LinearLayoutManager(getActivity()));
        stayXrv.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        staySubmitAdapter = new StaySubmitAdapter(getContext());
        stayXrv.setAdapter(staySubmitAdapter);
        //点击条目跳转
        staySubmitAdapter.setOnClickItem(new StaySubmitAdapter.onClickItem() {
            @Override
            public void item(int position, PoiEntity poiEntity) {
                Message subObtain = Message.obtain();
                subObtain.what = Constant.EVENT_WORK_HOME;
                subObtain.obj = true;
                EventBus.getDefault().post(subObtain);

                Message obtain = Message.obtain();
                obtain.what = Constant.EVENT_WHAT_COMPLETE_TASK;
                obtain.obj = poiEntity;
                EventBus.getDefault().post(obtain);

            }
        });
        cbSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                staySubmitAdapter.setAllDataChecked(isChecked);
                staySubmitAdapter.notifyDataSetChanged();
            }
        });
        refreshData();
    }

    @Subscribe
    public void onEvent(Message data) {
        if (data.what == Constant.EVENT_STAY_REFRESH) {
            Toast.makeText(getActivity(), (String) data.obj, Toast.LENGTH_SHORT).show();
            dismissLoadingDialog();
            refreshData();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        dismissLoadingDialog();
    }

    public List<PoiEntity> initRoadWord(int type) {
        newEntities.clear();
        for (int i = 0; i < roadEntities.size(); i++) {
            PoiEntity poiEntity = roadEntities.get(i);
            if (type == 0) {
                newEntities.add(poiEntity);
            } else {
                if (poiEntity.getType() == type) {
                    newEntities.add(poiEntity);
                }
            }

        }
        return newEntities;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cl_stay_type://1 "POI"2 "充电站"3 "POI录像"4 "道路录像"5 "其他"6 "面状任务"
                BottomMenu.show((AppCompatActivity) getContext(), new String[]{"全部", "poi", "充电站", "poi录像", "道路录像", "其他"}, new OnMenuItemClickListener() {
                    @Override
                    public void onClick(String text, int index) {
                        switch (index) {
                            case 0:
                                List<PoiEntity> entities = initRoadWord(0);
                                staySubmitAdapter.setAllRoad(entities);
                                break;
                            case 1:
                                List<PoiEntity> poiEntities = initRoadWord(1);
                                staySubmitAdapter.setAllRoad(poiEntities);
                                break;
                            case 2:
                                List<PoiEntity> stationEntities = initRoadWord(2);
                                staySubmitAdapter.setAllRoad(stationEntities);
                                break;
                            case 3:
                                List<PoiEntity> poiVideoEntities = initRoadWord(3);
                                staySubmitAdapter.setAllRoad(poiVideoEntities);
                                break;
                            case 4:
                                List<PoiEntity> roadEntities = initRoadWord(4);
                                staySubmitAdapter.setAllRoad(roadEntities);
                                break;
                            case 5:
                                List<PoiEntity> otherEntities = initRoadWord(5);
                                staySubmitAdapter.setAllRoad(otherEntities);
                                break;
                        }
                        tvStayType.setText(text);
                    }
                });
                break;

            case R.id.tv_delete:
                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                MessageDialog.show((AppCompatActivity) getContext(), "提示", "是否删除", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        initRequest(staySubmitAdapter.getAllRoad());
                        return false;
                    }
                });
                break;
            case R.id.btn_stay_submit://提交
                if (poiEntities == null) {
                    poiEntities = new ArrayList<>();
                }
                poiEntities.clear();
                List<PoiEntity> allRoad = staySubmitAdapter.getAllRoad();
                for (int i = 0; i < allRoad.size(); i++) {
                    if (allRoad.get(i).isChecked()) {
                        poiEntities.add(allRoad.get(i));
                    }
                }
                if (poiEntities.size() > 0) {
                    showLoadingDialog();
                    setLoadingDialogText("提交中...");
                    PoiSaveUtils.getInstance(getActivity()).uploadPoiEntityBatch(poiEntities);
                } else {
                    Toast.makeText(getActivity(), "请选择要删除的条目数据", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }

    private void initRequest(List<PoiEntity> allRoad) {
        showLoadingDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList<PoiEntity> poiEntities = new ArrayList<>();
                synchronized (allRoad) {
                    Iterator iterator = allRoad.iterator();
                    while (iterator.hasNext()) {
                        PoiEntity poiEntity = (PoiEntity) iterator.next();
                        if (poiEntity.isChecked()) {
                            poiEntities.add(poiEntity);
                        }
                    }
                    ;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String taskIds = "";
                        String auditIds = "";
                        for (int i = 0; i < poiEntities.size(); i++) {
                            if (poiEntities.get(i).getTaskStatus() == 2) {
                                taskIds += poiEntities.get(i).getTaskId()+",";
                            } else if (poiEntities.get(i).getTaskStatus() == 3) {
                                auditIds += poiEntities.get(i).getBodyId()+",";
                            }
                        }
                        if (taskIds!=null&&!taskIds.equals("")){
                            taskIds = taskIds.substring(0,taskIds.length() - 1);
                        }
                        if (auditIds!=null&&!auditIds.equals("")){
                            auditIds = auditIds.substring(0,auditIds.length() - 1);
                        }
                        HttpParams httpParams = new HttpParams();
                        httpParams.put("taskIds", taskIds);
                        httpParams.put("auditIds", auditIds);
                        OkGoBuilder.getInstance()
                                .Builder(getActivity())
                                .url(HttpInterface.UNRECEIVED_POLYGON_TASK)
                                .params(httpParams)
                                .token(Constant.ACCESS_TOKEN)
                                .cls(UnPolygonTaskBean.class)
                                .getRequest(new Callback<UnPolygonTaskBean>() {
                                    @Override
                                    public void onSuccess(UnPolygonTaskBean response, int id) {
                                        dismissLoadingDialog();
                                        if (response.getCode()==200){
                                            staySubmitAdapter.setAllCheckedDelete();
                                        }else {
                                            Toast.makeText(getActivity(), response.getMessage() + "", Toast.LENGTH_SHORT).show();
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e, int id) {
                                        dismissLoadingDialog();
                                        Toast.makeText(getActivity(), e.getMessage() + "", Toast.LENGTH_SHORT).show();

                                    }
                                });
                    }
                });
            }
        }).start();
    }

    public void refreshData() {

        if (roadEntities == null) {
            roadEntities = new ArrayList<>();
        } else {
            roadEntities.clear();
        }
        if (newEntities == null) {
            newEntities = new ArrayList<>();
        } else {
            newEntities.clear();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                List<PoiEntity> roadAll = roadDao.getAllPoiByRecoder();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        roadEntities.clear();
                        roadEntities.addAll(roadAll);
//                      for (int i = 0; i < roadAll.size(); i++) {
//                           if (roadAll.get(i).getType()!=6){
//                               roadEntities.add(roadAll.get(i));
//                           }
//                      }
                        Log.d("TAG", "run: " + roadEntities.toString());
                        staySubmitAdapter.setAllRoad(roadEntities);
                        staySubmitAdapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this))//加上判断
            EventBus.getDefault().unregister(this);
        super.onDestroy();
        dismissLoadingDialog();
    }
}