package com.tofly.ghrq_route.common.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.lcp.arecyclerview.widget.ARecycleView;
import com.mgq.base.utils.logger.LogRecorder;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.common.ui.adapter.PlanAdapter;
import com.tofly.ghrq_route.common.ui.dialog.DownloadDialogProgressUtil;
import com.tofly.ghrq_route.module.OfflineWork.OfflineWorkTool;
import com.tofly.ghrq_route.module.deviceInfo.DeviceInfoTool;
import com.tofly.ghrq_route.module.plan.PlanTool;
import com.tofly.ghrq_route.module.plan.controller.PlanCallBack;
import com.tofly.ghrq_route.module.plan.domain.ChildPlanCountBean;
import com.tofly.ghrq_route.module.plan.domain.OfflinePathBean;
import com.tofly.ghrq_route.module.plan.domain.PlanBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.EventBusUtil;
import com.tofly.ghrq_route.common.util.sharedPreference.SharePreUtil;

import org.greenrobot.eventbus.Subscribe;

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

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 巡检页面
 * Created by Amu on 2017/7/5.
 */
public class UiPlan extends BaseUi {
    @BindView(R.id.layout_select_state)
    FrameLayout layoutSelectState;
    @BindView(R.id.text_select_state)
    TextView textSelectState;
    @BindView(R.id.text_hint)
    TextView textHint;
    @BindView(R.id.recycler_view)
    ARecycleView recyclerView;
    @BindView(R.id.layout_plan_transfer_note)
    LinearLayout layoutTransferNote;
    @BindView(R.id.edit_plan_transfer_note)
    EditText editTransferNote;
    @BindArray(R.array.plan_select_state)
    String[] selectStates;

    private PlanAdapter planAdapter;
    private PlanTool planTool;

    private ActionMode mActionMode;
    private ActionMode.Callback mCallback;
    private MenuItem menuSelectAll;
    private boolean isAllSelect = false;

    private final int STATE_TODAY_PLAN = 3;
    private final int STATE_ALL = 4;

    private int mPlanState = STATE_TODAY_PLAN;

    private int mOldPlanState = STATE_TODAY_PLAN;

    private boolean bNoPlanWarn = false;

    private boolean bHasAlertNewPlan = false;

    private boolean bNeedTransfer = false;

    private AlertDialog updateAlertDialog = null;

    private AlertDialog updateErrAlertDialog = null;

    public static final String KEY_ALERT_NEW_PLAN = "has_alert_new_plan";

    private MenuItem menuReset;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ui_plan);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();

        EventBusUtil.register(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_plan, menu);
        boolean isCarMode = BaseApp.getInstance().isCarMode();
        //menu.findItem(R.id.action_transfer).setVisible(!isCarMode);
        menuReset = menu.findItem(R.id.action_reset);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (OfflineWorkTool.isOffline()){
            toast(getResources().getString(R.string.offline_operation_forbid));
            return super.onOptionsItemSelected(item);
        }
        switch (item.getItemId()){
            case R.id.action_transfer:{
                if (mActionMode == null){
                    mActionMode = startSupportActionMode(mCallback);
                    if (planAdapter != null){
                        planAdapter.clear();
                        planAdapter.setChoiceMode();
                    }
                    onActionModeShow();
                }
            }
            break;
            case R.id.action_download:{
                needTodayPlanPoint();
            }
            break;
            case R.id.action_reset:{
                showAlertWithConfirmCancelButton(R.string.plan_reset, R.string.plan_reset_alert, true,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                resetPlanPointData();
                            }
                        });
            }
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void resetPlanPointData(){
        ResetPlanPointTask resetPlanPointTask = new ResetPlanPointTask();
        resetPlanPointTask.execute();
    }

    class ResetPlanPointTask extends AsyncTask{
        @Override
        protected void onPreExecute() {
            menuReset.setEnabled(false);
            String strUploading = getResources().getString(R.string.deleting_data);
            ProgressManager.getInstance().showProgress(UiPlan.this, null, strUploading, false);
        }

        @Override
        protected Object doInBackground(Object[] objects) {
            long result = -1;
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            if (userBean != null) {
                final int carmode = userBean.isCarMode() ? 1 : 0;
                String userid = userBean.getUserid();
                String msg = "计划重置, 开始 ----------";
                LogRecorder.writeDeviceToolLog(UiPlan.this, msg, userid);

                /*清除本地离线点数据*/
                planTool.clearAllLocalOfflinePath(userid, carmode);

                msg = "计划重置--清除本地离线点数据。";
                LogRecorder.writeDeviceToolLog(UiPlan.this, msg, userid);

                msg = "计划重置--清0每条计划的离线下载错误次数。";
                LogRecorder.writeDeviceToolLog(UiPlan.this, msg, userid);
                /*当天所需要下载的计划的下载错误次数清0*/
                StringBuilder builder = new StringBuilder();
                builder.append("需要清0的计划：");
                List<ChildPlanCountBean> todayPlans = SharePreUtil.getPlanPointTodayPlan();
                if (todayPlans != null && todayPlans.size() > 0){
                    for (ChildPlanCountBean countBean : todayPlans){
                        String planId = countBean.getPlan_id();
                        SharePreUtil.setPlanPointPlanDownTimes(planId, 0);
                        builder.append(" id: ");
                        builder.append(planId);
                        builder.append(", ");
                    }
                }
                LogRecorder.writeDeviceToolLog(UiPlan.this, builder.toString(), userid);

                msg = "计划重置--当天总的下载错误次数清0。";
                LogRecorder.writeDeviceToolLog(UiPlan.this, msg, userid);
                /*当天总的下载错误次数清0*/
                SharePreUtil.setPlanPointDownErrTimes(0);

                msg = "计划重置, 完成 ----------";
                LogRecorder.writeDeviceToolLog(UiPlan.this, msg, userid);

                result = 0;
            }
            return result;
        }

        @Override
        protected void onPostExecute(Object obj) {
            ProgressManager.getInstance().cancelProgress();
            menuReset.setEnabled(true);

            long result = (long) obj;
            if (result == 0) {
                /*重新下载计划的离线点数据*/
                bHasAlertNewPlan = true;
                String strUploading = getResources().getString(R.string.updating_data);
                ProgressManager.getInstance().showProgress(UiPlan.this, null, strUploading, false);
                checkHasNewPlan(false, (retCode, errMsg, bAlertNew, count) -> {
                    ProgressManager.getInstance().cancelProgress();
                    if (retCode < 0){
                        toast(errMsg);
                    } else {
                        if (retCode == 0){
                            needTodayPlanPoint();
                        }else if (retCode == 1){
                            toast("没有需要更新的计划！");
                        }
                    }
                });
            }
        }
    }

    @Subscribe
    public void onMessageEvent(UiPlan.PlanEvent event){
        boolean isForeground = this.isForeground();
        switch (event.message) {
            case UiPlan.PLAN_POINT_OVER:
                Map<String, List<OfflinePathBean>> overMaps = (Map<String, List<OfflinePathBean>>) event.arg0;
                updatePlanPercent(overMaps);
                //getLocalPlanList();
                break;
            case UiPlan.PLAN_NEED_REFRESH:
                if (mPlanState == PlanBean.SELECT_STATE_UNSTARTED){
                    getPlanUnStartedList();
                }else {
                    getLocalPlanList();
                    //checkHasNewPlan(true, null);
                }
                break;
            case PLAN_POINT_DOWNLOAD_STARTED:
                if (isForeground) {
                    runOnUiThread(() -> {
                        String strUploading = getResources().getString(R.string.updating_plan_point_data);
                        DownloadDialogProgressUtil.getInstance().showDownloadDialog(UiPlan.this, strUploading);
                    });
                }
                //ProgressManager.getInstance().showProgress(this, null, strUploading, false);
                break;
            case PLAN_POINT_DOWNLOAD_CURRENT:
                if (isForeground) {
                    runOnUiThread(() -> {
                        int current = (int ) event.arg0;
                        int total = (int ) event.arg1;
                        int progress = (int ) event.arg2;
                        DownloadDialogProgressUtil.getInstance().updateDownloadProgress(current, total, progress, "");
                    });
                }
                break;
            case PLAN_POINT_DOWNLOAD_FINISHED:
                if (isForeground) {
                    runOnUiThread(() -> {
                        boolean success = (boolean) event.arg0;
                        DownloadDialogProgressUtil.getInstance().updateDownloadFinish("", success ? 1 : 0);
                    });
                    //ProgressManager.getInstance().cancelProgress();
                }
                boolean isSuccess = (boolean) event.arg0;
                String msg = "获取当天的巡检计划：" + (isSuccess ? "成功" : "失败");
                toast(msg);
                getOnlinePlanList(true);
                break;
        }
    }

    @Subscribe
    public void onMessageEvent(DeviceInfoTool.DeviceInfoToolEvent event){
        switch (event.message) {
            case DeviceInfoTool.DEVICEINFO_TODAY_PLAN_CHANGED: {
                bNoPlanWarn = false;
                bHasAlertNewPlan = !((boolean) event.arg);
                getOnlinePlanList(false);
                boolean isForeground = this.isForeground();
                if (isForeground) {
                    showUpdatePlanPointDialog();
                }
                break;
            }
            case DeviceInfoTool.DEVICEINFO_TODAY_NO_PLAN:
                if (bNoPlanWarn) {
                    toast("没有需要更新的计划！");
                    bNoPlanWarn = false;
                }
                break;
            case DeviceInfoTool.DEVICEINFO_PLAN_DOWN_ERR_MAX: {
                boolean isForeground = this.isForeground();
                if (isForeground) {
                    showUpdatePlanPointErrDialog();
                }
                break;
            }
            case DeviceInfoTool.DEVICEINFO_CHECK_TODAY_PLAN_FINISHED:
                if (menuReset != null) {
                    menuReset.setVisible(true);
                    menuReset.setEnabled(true);
                }
                break;
        }
    }

    private void updatePlanPercent(Map<String, List<OfflinePathBean>> overMaps){
        if (overMaps != null) {
            for (final String plan_id : overMaps.keySet()){
                if (plan_id != null && !plan_id.isEmpty()) {
                    /*planTool.getPlanInfo(this, plan_id, new PlanCallBack(){
                        @Override
                        public void onGetChildPlanInfo(boolean isSuccess, int errorCode, String errMsg, PlanBean childPlan) {
                            super.onGetChildPlanInfo(isSuccess, errorCode, errMsg, childPlan);
                            if (isSuccess) {
                                if (planAdapter != null && childPlan != null) {
                                    String percent = childPlan.getPercent1();
                                    planAdapter.updateItemPercent(plan_id, percent);
                                }
                            }
                        }
                    });*/
                    PlanBean planBean = planTool.getLocalPlan(plan_id);
                    if (planBean != null){
                        planAdapter.setData(planBean);
                    }
                }
            }
        }
    }

    private void checkHasNewPlan(boolean alertNew, DeviceInfoTool.CheckTodayPlanCountCallback callback){
        DeviceInfoTool deviceInfoTool = DeviceInfoTool.getInstance();
        if (!deviceInfoTool.isChedingTodayPlanCount()){
            if (BaseApp.isNetworkConnected()) {
                if (menuReset != null)
                    menuReset.setEnabled(false);
                deviceInfoTool.checkTodayPlanCount(alertNew, callback);
            }
        }else{
            if (menuReset != null)
                menuReset.setEnabled(false);
        }
    }

    private void showUpdatePlanPointDialog() {
        if (bHasAlertNewPlan){
            needTodayPlanPoint();
        }else {
            if (updateAlertDialog == null){
               updateAlertDialog = showAlertWithConfirmButton(R.string.plan_title, R.string.plan_need_update, false,
                       (dialog, which) -> needTodayPlanPoint());
            }else {
                updateAlertDialog.show();
            }
            bHasAlertNewPlan = true;
        }

    }

    private void showUpdatePlanPointErrDialog(){
        if (updateAlertDialog != null && updateAlertDialog.isShowing()){
            updateAlertDialog.dismiss();
        }

        if (updateErrAlertDialog == null){
            updateErrAlertDialog = showAlertWithConfirmButton(R.string.download_failed,
                    R.string.plan_down_err_max, false, null);
        }else {
            updateErrAlertDialog.show();
        }
    }

    private void initView() {
        String hintText = getResources().getString(R.string.text_transfer_hint);

        SpannableStringBuilder builder = new SpannableStringBuilder(hintText);
        String key = "未开始";
        int start = hintText.indexOf(key);
        int end = start + key.length();
        int color = getResources().getColor(R.color.colorAccent);
        if (start != -1) {
            builder.setSpan(new ForegroundColorSpan(color), start, end,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置 字体颜色
        }
        key = "正在执行";
        start = hintText.indexOf(key);
        end = start + key.length();
        if (start != -1) {
            builder.setSpan(new ForegroundColorSpan(color), start, end,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置 字体颜色
        }
        textHint.setText(builder);

        if (mPlanState == STATE_ALL){
            textSelectState.setText(R.string.text_label_status);
            textSelectState.setTextColor(getResources().getColor(R.color.text));
        }else {
            int position = mPlanState - 1;
            String state = selectStates[position];
            textSelectState.setText(state);
            textSelectState.setTextColor(getResources().getColor(R.color.colorAccent));
        }
    }

    private void initData() {
        planTool = PlanTool.getInstance();

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null){
            bHasAlertNewPlan = bundle.getBoolean(KEY_ALERT_NEW_PLAN, false);
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        ArrayList<PlanBean> list = new ArrayList<>();
        planAdapter = new PlanAdapter(this, list);
        recyclerView.setAdapter(planAdapter);

        startRefreshing();
        getOnlinePlanList(true);
        //needTodayPlanPoint();
    }

    private void initListener() {
        recyclerView.setOnRefreshListener(() -> {
            if (mPlanState == PlanBean.SELECT_STATE_UNSTARTED){
                if (bNeedTransfer) {
                    getPlanTransferableList();
                }else {
                    getPlanUnStartedList();
                }
            }else {
                getOnlinePlanList(true);
            }
        });

/*        recyclerView.setOnLoadMoreListener(new ARecycleView.OnLoadMoreListener() {
            @Override
            public void loadMore() {
                pageindex++;
                getLocalPlanList();
            }
        });*/

        if (planAdapter != null){
            planAdapter.setItemClickListener(new PlanAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (mActionMode != null){
                        toggleSelection(position);
                    }else {
                        PlanBean planBean = planAdapter.getItem(position);
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("plan", planBean);
                        intent.setClass(UiPlan.this, UiPlanDetail.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                }

                @Override
                public void onItemLongClick(View view, int position) {

                }
            });

            mCallback = new ActionMode.Callback() {
                @Override
                public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                    mode.setTitle(getResources().getString(R.string.plan_transfer));
                    mode.setSubtitle("");
                    getMenuInflater().inflate(R.menu.menu_confirm, menu);
                    menuSelectAll = menu.findItem(R.id.action_all);
                    return true;
                }

                @Override
                public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                    switch (item.getItemId()){
                        case R.id.action_confirm:{
                            boolean bNeedTransfer = false;
                            if (planAdapter != null){
                                Set<Integer> selectedPos = planAdapter.getSelectedPositionSet();
                                if (selectedPos.size() > 0){
                                    List<String> idPlans = new ArrayList<>();
                                    for (int pos : selectedPos) {
                                        PlanBean planBean = planAdapter.getItem(pos);
                                        if (planBean != null) {
                                            String plan_id = planBean.getPlan_id();
                                            idPlans.add(plan_id);
                                        }
                                    }
                                    if (idPlans.size() > 0) {
                                        bNeedTransfer = true;

                                        String note = editTransferNote.getText().toString();
                                        if (!note.isEmpty()){
                                            transferPlanApply(idPlans, note);
                                        }else {
                                            editTransferNote.requestFocus();
                                            toast(getString(R.string.plan_transfer_note_hint));
                                        }
                                    }
                                }
                            }
                            if (!bNeedTransfer)
                                mActionMode.finish();
                            return true;
                        }
                        case R.id.action_all:{
                            if (planAdapter != null){
                                if (isAllSelect) {
                                    planAdapter.cancelSelected();
                                }else {
                                    planAdapter.allSelected();
                                }
                                updateSelectionCount();
                            }
                            return true;
                        }
                    }
                    return false;
                }

                @Override
                public void onDestroyActionMode(ActionMode mode) {
                    mActionMode = null;
                    planAdapter.cancelSelectedExitChoice();
                    onActionModeOff();
                }
            };
        }
    }

    private void toggleSelection(int position){
        planAdapter.toggleSelection(position);
        updateSelectionCount();
    }

    private void updateSelectionCount() {
        // 更新 ActionMode 上的计数
        int size = planAdapter.getSelectedPositionSet().size();
        mActionMode.setSubtitle("已选中" + size + "个");

        if (planAdapter.getItemCount() == size) {
            isAllSelect = true;
            menuSelectAll.setTitle("全不选");
        }else {
            isAllSelect = false;
            menuSelectAll.setTitle("全选");
        }
    }

    private void onActionModeShow(){
        textSelectState.setVisibility(View.GONE);
        textHint.setVisibility(View.VISIBLE);
        layoutSelectState.setEnabled(false);
        bNeedTransfer = true;
        mOldPlanState = mPlanState;
        mPlanState = PlanBean.SELECT_STATE_UNSTARTED;
        layoutTransferNote.setVisibility(View.VISIBLE);
        getPlanTransferableList();
    }

    private void onActionModeOff(){
        textSelectState.setVisibility(View.VISIBLE);
        textHint.setVisibility(View.GONE);
        editTransferNote.setText("");
        layoutTransferNote.setVisibility(View.GONE);
        layoutSelectState.setEnabled(true);
        mPlanState = mOldPlanState;
        bNeedTransfer = false;
        if (mPlanState == PlanBean.SELECT_STATE_UNSTARTED){
            getPlanUnStartedList();
        }else {
            getLocalPlanList();
        }
    }

    private void startRefreshing(){
        recyclerView.setRefreshing(true);
    }

    private void stopRefreshing(){
        recyclerView.setRefreshing(false);
        recyclerView.hideMoreProgress();
    }

    private void getOnlinePlanList(boolean checkNewPlan){
        final List<String> planIds = planTool.getLocalPlanIds();
        planTool.getPlanListToday(this, new PlanCallBack(){
            @Override
            public void onGetPlanList(boolean isSuccess, int errorCode, String errMsg, List<PlanBean> planList, int total) {
                super.onGetPlanList(isSuccess, errorCode, errMsg, planList, total);

                if (isSuccess && planList != null) {
                    boolean hasNewPlan = false;
                    for (PlanBean planBean : planList) {
                        String plan_id = planBean.getPlan_id();
                        boolean newPlan = !planIds.contains(plan_id);
                        if (newPlan) {
                            hasNewPlan = true;
                            break;
                        }

                        boolean isPlanFinished = planBean.getPercent1().equals("1") || planBean.getPercent2().equals("1");
                        if (isPlanFinished)
                            continue;

                        long pointCount = planTool.getLocalPlanPointCount(plan_id);
                        boolean newPlanPoint = planBean.getPoint_num() != pointCount;
                        if (newPlanPoint) {
                            hasNewPlan = true;
                            break;
                        }
                    }
                    if (checkNewPlan && hasNewPlan) {
                        checkHasNewPlan(true, null);
                    }
                }

                /*加载本地保存的计划*/
                getLocalPlanList();
            }
        });
    }

    private void getLocalPlanList() {
        int planState = mPlanState;
        if (planState == STATE_ALL){
            planState = PlanBean.SELECT_STATE_ALL;
        }
        startRefreshing();
        /*加载本地计划之前，先检测其完成率*/
        planTool.checkLocalPlanIsOver();
        planTool.getPlanListTodayOffline(this, planState, new PlanCallBack(){
            @Override
            public void onGetPlanList(boolean isSuccess, int errorCode, String errMsg, List<PlanBean> planList, int total) {
                super.onGetPlanList(isSuccess, errorCode, errMsg, planList, total);
                stopRefreshing();
                if (isSuccess){
                    recyclerView.setTotal(total);
                    planAdapter.clear();
                    if (planList != null) {
                        planAdapter.addAll(planList);
                    }
                }
            }
        });
    }

    private void getPlanUnStartedList() {
        startRefreshing();
        planTool.getPlanUnStartedList(this, new PlanCallBack(){
            @Override
            public void onGetPlanList(boolean isSuccess, int errorCode, String errMsg, List<PlanBean> planList, int total) {
                super.onGetPlanList(isSuccess, errorCode, errMsg, planList, total);
                stopRefreshing();
                planAdapter.clear();
                if (isSuccess){
                    recyclerView.setTotal(total);
                    if (planList != null) {
                        planAdapter.addAll(planList);
                    }
                }
            }
        });
    }

    private void getPlanTransferableList() {
        startRefreshing();
        planTool.getPlanTransferableList(this, new PlanCallBack(){
            @Override
            public void onGetPlanList(boolean isSuccess, int errorCode, String errMsg, List<PlanBean> planList, int total) {
                super.onGetPlanList(isSuccess, errorCode, errMsg, planList, total);
                stopRefreshing();
                planAdapter.clear();
                if (isSuccess){
                    recyclerView.setTotal(total);
                    if (planList != null) {
                        planAdapter.addAll(planList);
                    }
                }
            }
        });
    }

    private void transferPlanApply(List<String> planids, String note){
        if (planids != null && planids.size() > 0){
            String strUploading = getString(R.string.uploading_data);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            planTool.transferPlan(this, planids, note, new PlanCallBack(){
                @Override
                public void onTransferPlanApply(boolean isSuccess, int errorCode, String errMsg) {
                    super.onTransferPlanApply(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess){
                        if (mActionMode != null)
                            mActionMode.finish();
                    }
                }
            });
        }
    }

    private void checkTodayPlan(){
        boolean needUpdate = planTool.isNeedUpdatePlan();
        boolean isUpdating = planTool.isUpdatingPlan();  //计划正在下载
        if (needUpdate && !isUpdating){
            getLocalPlanList();
            showUpdatePlanPointDialog();
        }
    }

    private void needTodayPlanPoint(){
        planTool.needTodayPlanPoint();
    }

    @OnClick({R.id.layout_select_state})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.layout_select_state:{
                showPlanStatePopupWindow();
            }
            break;
        }
    }

    private void showPlanStatePopupWindow(){
        final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
        listPopupWindow.setAdapter(new ArrayAdapter<>(this, R.layout.popup_content_item, selectStates));
        listPopupWindow.setOnItemClickListener((parent, view, position, id) -> {
            boolean bNeedReload = false;
            if (mPlanState != position + 1){
                bNeedReload = true;
            }
            mPlanState = position + 1;
            if (bNeedReload){
                if (mPlanState == PlanBean.SELECT_STATE_UNSTARTED){
                    getPlanUnStartedList();
                }else {
                    getLocalPlanList();
                }
            }
            listPopupWindow.dismiss();
            if (mPlanState == STATE_ALL){
                textSelectState.setText(R.string.text_label_status);
                textSelectState.setTextColor(getResources().getColor(R.color.text));
            }else {
                String state = selectStates[position];
                textSelectState.setText(state);
                textSelectState.setTextColor(getResources().getColor(R.color.colorAccent));
            }
        });
        listPopupWindow.setAnchorView(layoutSelectState);
        listPopupWindow.setVerticalOffset(5);
        listPopupWindow.setModal(true);
        listPopupWindow.show();
    }

    public final static String PLAN_POINT_DOWNLOAD_STARTED = "planPointDownloadStarted";
    public final static String PLAN_POINT_DOWNLOAD_CURRENT = "planPointDownloadCurrent";
    public final static String PLAN_POINT_DOWNLOAD_FINISHED = "planPointDownloadFinished";
    public final static String PLAN_POINT_OVER = "planPointOver";
    public final static String PLAN_SERVICE_LOCATION = "planServiceLocation";
    public final static String PLAN_NEED_REFRESH = "planNeedRefresh";
    public static class PlanEvent {
        public String message;
        public Object arg0;
        public Object arg1;
        public Object arg2;
        public PlanEvent(String message, Object arg0) {
            this.message = message;
            this.arg0 = arg0;
        }

        public PlanEvent(String message, Object arg0, Object arg1) {
            this(message, arg0);
            this.arg1 = arg1;
        }

        public PlanEvent(String message, Object arg0, Object arg1, Object arg2) {
            this(message, arg0, arg1);
            this.arg2 = arg2;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkTodayPlan();
    }

    @Override
    protected void onStop() {
        super.onStop();
        BaseApp.cancelRequest(getClass().getName());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregister(this);
    }
}
