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

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.viewpager.widget.ViewPager;

import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.snackbar.Snackbar;
import com.mgq.base.utils.customview.CircleImageView;
import com.mgq.base.utils.logger.LogRecorder;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
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.base.C;
import com.tofly.ghrq_route.base.MainModule;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.base.URLResponseCode;
import com.tofly.ghrq_route.common.ui.adapter.GridViewAdapter;
import com.tofly.ghrq_route.common.ui.adapter.MessagePageAdapter;
import com.tofly.ghrq_route.common.ui.view.BottomMainConnectInfo;
import com.tofly.ghrq_route.common.ui.view.IconPageIndicator;
import com.tofly.ghrq_route.common.ui.view.MyGridView;
import com.tofly.ghrq_route.common.util.dialog.DialogUtil;
import com.tofly.ghrq_route.module.OfflineWork.OfflineWorkTool;
import com.tofly.ghrq_route.module.OfflineWork.domain.OfflineWorkEvent;
import com.tofly.ghrq_route.module.buildManage.domain.BuildSignDataBean;
import com.tofly.ghrq_route.module.deviceInfo.DeviceInfoTool;
import com.tofly.ghrq_route.module.download.DownloadTool;
import com.tofly.ghrq_route.module.message.MessageTool;
import com.tofly.ghrq_route.module.message.controller.MessageCallBack;
import com.tofly.ghrq_route.module.message.controller.MessageController;
import com.tofly.ghrq_route.module.message.domain.InMessageBean;
import com.tofly.ghrq_route.module.notifyManage.NotifyManageBean;
import com.tofly.ghrq_route.module.pipeAnalyze.domain.FieldsBean;
import com.tofly.ghrq_route.module.plan.PlanTool;
import com.tofly.ghrq_route.module.service.NetStateService;
import com.tofly.ghrq_route.module.sign.SignTool;
import com.tofly.ghrq_route.module.sign.controller.SignCallBack;
import com.tofly.ghrq_route.module.sign.domain.SignDataBean;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.systemConfig.SystemConfigTool;
import com.tofly.ghrq_route.module.systemConfig.domain.SystemConfigEvent;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.module.user.domain.UserMapDataBean;
import com.tofly.ghrq_route.module.user.domain.UserOnlineMapDataBean;
import com.tofly.ghrq_route.common.util.EventBusUtil;
import com.tofly.ghrq_route.common.util.app.UpdateManager;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.net.NetUtil;
import com.tofly.ghrq_route.common.util.sharedPreference.SharePreUtil;

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

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

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

import static com.tofly.ghrq_route.common.util.net.NetUtil.NETWORN_MOBILE;
import static com.tofly.ghrq_route.common.util.net.NetUtil.NETWORN_NONE;
import static com.tofly.ghrq_route.common.util.net.NetUtil.NETWORN_WIFI;

/**
 * Created by zombiexq on 2016/6/14.
 */
public class UiMain extends BaseUi implements View.OnClickListener {
    @BindView(R.id.layout_app_bar)
    AppBarLayout appBarLayout;
    @BindView(R.id.layout_collapse_toolbar)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.layout_top_content)
    FrameLayout layoutTopContent;
    @BindView(R.id.image_user_icon)
    CircleImageView imageUserIcon;
    @BindView(R.id.image_sign_status)
    ImageView imageSignStatus;
    @BindView(R.id.image_main_online_mode)
    ImageView imageOnlineMode;
    @BindView(R.id.text_main_date)
    TextView textMainDate;
    @BindView(R.id.text_main_today)
    TextView textMainToday;
    @BindView(R.id.view_pager_message)
    ViewPager viewPagerMessage;
    @BindView(R.id.ipi_labels)
    IconPageIndicator ipiLabels;
    @BindView(R.id.text_assignment_count)
    TextView textAssignmentCount;

    private static final String TAG = UiMain.class.getName();

    private GridViewAdapter mGridViewAdapter;

    private MyGridView mGridView;

    private TextView textExit;

    private BottomMainConnectInfo bottomConnectInfo;

    private final int GRID_VIEW_SIGN_POSITION = 4;

    private LinearLayout layoutMainRoot;

    private ImageLoader loader;

    private SignTool signTool;

    private UserInfoTool userInfoTool;

    private DBDaoHelper dbDaoHelper;

    private PermissionHelper permissionHelper;

    private MenuItem carMenuItem;

    private static boolean bHasCheckTodayPlan = false;

    private static boolean bHasAlertSign = false;

    /*检测是否程序有新版本需要升级。 现在默认设置为检查并提示。*/
    private static boolean bHasAlertUpdate = false;

    /*检测是否管线数据有更新。现在默认设置为不检查*/
    private static boolean bHasAlertMapUpdate = true;

    private boolean bFirstNetworkAlert = true;

    private int connect_error_count = 0;

    private int connect_mapconfig_error_count = 0;

    private int connect_usersign_error_count = 0;

    private final static int SERVER_CONNECT_ERROR_COUNT = 2;

    private NetStateService netStateService;

    private boolean mBound = false;

    private AlertDialog updateAlertDialog = null;

    private AlertDialog updateErrAlertDialog = null;

    private Snackbar snackbarSign = null;

    private MessagePageAdapter messagePageAdapter;

    public static final int MAIN_GRID_DANGER = 0;
    public static final int MAIN_GRID_BUILD = 1;
    public static final int MAIN_GRID_ROUTE = 2;
    public static final int MAIN_GRID_PHOTO = 3;
    public static final int MAIN_GRID_SIGN = 4;
    public static final int MAIN_GRID_MESSAGE = 5;
    public static final int MAIN_GRID_UPDATE = 6;
    public static final int MAIN_GRID_MAPTOOL = 7;
    public static final int MAIN_GRID_TRACK = 8;
    private MessageController messageController;
    private Handler handler = new Handler();
    private int size1 = -1;
    private Runnable runnable = this::getUnread;

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

        setContentView(R.layout.ui_main);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();

        EventBusUtil.register(this);

        if (!bHasAlertUpdate || BaseApp.isAppMustUpdate()) {
            if (isNetworkConnected()) {
                new UpdateManager(this).checkUpdate();
                bHasAlertUpdate = true;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_carmode, menu);
        carMenuItem = menu.findItem(R.id.action_carmode);
        boolean isCarMode = BaseApp.getInstance().isCarMode();
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            isCarMode = userBean.isCarMode();
        }
        carMenuItem.setVisible(isCarMode);
        return super.onCreateOptionsMenu(menu);
    }

    private void getUnread() {
        if (messageController == null) {
            messageController = new MessageController(this);
        }
        messageController.getRecvMsgList("", -1, 1, C.DEFAULT_MAX_LOAD_PAGESIZE, new MessageCallBack() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onGetRecvMsgList(boolean isSuccess, int errorCode, String errMsg, List<InMessageBean> messageList, int total) {
                super.onGetRecvMsgList(isSuccess, errorCode, errMsg, messageList, total);
                int size = 0;
                if (isSuccess && messageList != null) {
                    for (InMessageBean inMessageBean : messageList) {
                        if (inMessageBean.getFlag().equals("0")) {
                            size++;
                        }
                    }
                }
                if (size1 != size) {
                    size1 = size;
                    textAssignmentCount.setText("" + size1 + "项");
                }
                handler.postDelayed(runnable, 10 * 1000);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getSignStatusToday();
        if (C.bLoginCheckServerConfig_debug)
            checkServerConfigData();
        checkTodayPlan();
        checkTodayBuildLogPlan();

        DeviceInfoTool deviceInfoTool = DeviceInfoTool.getInstance();
        deviceInfoTool.checkMessage();
        deviceInfoTool.checkUnhandledJob();

        if (bottomConnectInfo != null) {
            bottomConnectInfo.checkUnuploadCount();
            bottomConnectInfo.setNetworkConnected();

            OfflineWorkTool offlineWorkTool = OfflineWorkTool.getInstance();
            boolean isServerConnected = offlineWorkTool.isServerConnected();
            bottomConnectInfo.setServerConnected(isServerConnected);
        }
    }

    @Override
    protected void onDestroy() {
        EventBusUtil.unregister(this);
        unbind();
        
        super.onDestroy();
        handler.removeCallbacks(runnable);

        if (mMessageTimer != null)
            mMessageTimer.cancel();
    }

    @Subscribe()
    public void onMessageEvent(UiUserInfo.MessageEvent messageEvent) {
        if (messageEvent.message.equals(UiUserInfo.USER_ACCOUNT_CHANGED)) {
            initUserInfo();
        }
    }

    @Subscribe()
    public void onMessageEvent(SystemConfigEvent messageEvent) {
        if (messageEvent.getEvent().equals(SystemConfigEvent.SYSTEM_CONFIG_CHANGED)) {
            forwartToUiSysConfig();
        }
    }

    @Subscribe()
    public void onMessageEvent(DownloadTool.DownloadEvent messageEvent) {
        if (messageEvent.message.equals(DownloadTool.DOWNLOAD_PIPEDATA_CHANGED)) {
            forwartToUiDownloadMap();
        }
    }

    @Subscribe()
    public void onMessageEvent(OfflineWorkEvent messageEvent) {
        switch (messageEvent.getEvent()) {
            case OfflineWorkEvent.SERVER_IS_REACHABLE: {
                boolean isReachable = (boolean) messageEvent.getObject();
                if (bottomConnectInfo != null)
                    bottomConnectInfo.setServerConnected(isReachable);
            }
            break;
            case OfflineWorkEvent.OFFLINE_JOB_UPLOAED: {
                if (bottomConnectInfo != null)
                    bottomConnectInfo.checkUnuploadCount();
            }
            break;
            case OfflineWorkEvent.DEVICE_IS_OFFLINE: {
                imageOnlineMode.setSelected(false);
            }
            break;
            case OfflineWorkEvent.DEVICE_IS_ONLINE: {
                imageOnlineMode.setSelected(true);
            }
            break;
        }
    }

    @Subscribe()
    public void onMessageEvent(UiPlan.PlanEvent messageEvent) {
        if (messageEvent.message.equals(UiPlan.PLAN_POINT_OVER)) {
            if (bottomConnectInfo != null)
                bottomConnectInfo.checkUnuploadCount();
        }
    }

    @Subscribe()
    public void onMessageEvent(DeviceInfoTool.DeviceInfoToolEvent event) {
        if (event.message.equals(DeviceInfoTool.DEVICEINFO_UNREAD_MESSAGE)) {
            List<InMessageBean> messageList = (List<InMessageBean>) event.arg;
            if (messageList != null) {
                int unreadCount = messageList.size();
                String strUnreadCount = unreadCount > 99 ? "99+" : unreadCount + "";
                textAssignmentCount.setText(String.format("%s项", strUnreadCount));
                setMessagePageAdapter(messageList);
            }
        } else if (event.message.equals(DeviceInfoTool.DEVICEINFO_CONNECTION_INFO)) {
            int resCode = (int) event.arg;
            boolean isConnected = (resCode == URLResponseCode.ErrorCode.SUCCESS);
            if (isConnected) {
                connect_error_count = 0;
            } else {
                connect_error_count++;
            }
//            boolean is_server_error = connect_error_count > SERVER_CONNECT_ERROR_COUNT;
//            bottomConnectInfo.setServerConnected(!is_server_error);
//            showTopErrorBar(is_server_error);
            DialogUtil.showTokenFailedDialog(this, resCode);
        } else if (event.message.equals(DeviceInfoTool.DEVICEINFO_TODAY_PLAN_CHANGED)) {
            String className = getForegroundClassName();
            boolean isForeground = this.isForeground() || className.equals(HomeActivity.class.getName());
            if (isForeground) {
                showUpdatePlanPointDialog();
            } else {
                if (!UiPlan.class.getName().equals(className)) {
                    needTodayPlanPoint();
                }
            }
        } else if (event.message.equals(DeviceInfoTool.DEVICEINFO_PLAN_DOWN_ERR_MAX)) {
            boolean isForeground = this.isForeground();
            if (isForeground) {
                showUpdatePlanPointErrDialog();
            }
        } else if (event.message.equals(DeviceInfoTool.DEVICEINFO_NEW_SAVED_GPS)) {
            if (bottomConnectInfo != null)
                bottomConnectInfo.checkUnuploadCount();
        }
    }

    private Timer mMessageTimer = null;
    private void setMessagePageAdapter(List<InMessageBean> messages) {
        boolean hasNewUnreadMessage = checkHasNewUnreadMessage();
        if (hasNewUnreadMessage || messagePageAdapter == null) {
            int total = messages.size();
            List<InMessageBean> subMessageList = messages.subList(0, total >= 10 ? 9 : total);
            messagePageAdapter = new MessagePageAdapter(this, subMessageList);
            viewPagerMessage.setAdapter(messagePageAdapter);
            ipiLabels.setVisibility(View.VISIBLE);
            ipiLabels.setViewPager(viewPagerMessage);
            ipiLabels.setItemSpace(BaseApp.dip2px(15));
        }else {
            if (messages == null || messages.isEmpty()) {
                viewPagerMessage.removeAllViews();
                ipiLabels.setVisibility(View.GONE);
            }
        }
    }

    private void startCheckMessageTimer() {
        mMessageTimer = new Timer();
        mMessageTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (messagePageAdapter != null && messagePageAdapter.getCount() > 1) {
                    runOnUiThread(() -> {
                        int index = viewPagerMessage.getCurrentItem();
                        index = (index + 1) % messagePageAdapter.getCount();
                        viewPagerMessage.setCurrentItem(index, true);
                    });
                }
            }
        }, 100, 5000);
    }

    private boolean checkHasNewUnreadMessage() {
        boolean hasNewMessage = false;
        MessageTool messageTool = MessageTool.getInstance();
        List<NotifyManageBean> unNotifyMessages= messageTool.getUnNotifyMsgBean();
        if (unNotifyMessages != null && unNotifyMessages.size() > 0) {
            hasNewMessage = true;
            messageTool.setMsgBeanNotified(unNotifyMessages);
        }
        return hasNewMessage;
    }

    private void showUpdatePlanPointDialog() {
        if (updateAlertDialog == null) {
            updateAlertDialog = showAlertWithConfirmButton(R.string.plan_title, R.string.plan_need_update_confirm, false,
                    (dialog, which) -> {
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putBoolean(UiPlan.KEY_ALERT_NEW_PLAN, true);
                        intent.putExtras(bundle);
                        intent.setClass(UiMain.this, UiPlan.class);
                        startActivity(intent);
                    });
        } else {
            updateAlertDialog.show();
        }
    }

    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 bind() {
        Intent intent = new Intent(this, NetStateService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);//通过服务中的广播获取网络状态，返回UiSetting中，显示不同的文字和文字颜色来提示用户网络状态
    }

    private void unbind() {
        if (mBound) {
            unbindService(serviceConnection);
            mBound = false;
            System.out.println("解绑service");
        }
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            netStateService = ((NetStateService.MyBinder) service)
                    .getService();
            mBound = true;
            // 添加接口实例获取连接状态
            netStateService.setOnGetConnectState(isConnected -> runOnUiThread(() -> {
                /*网络连接状态*/
                int networkState = NetUtil.getNetworkState(BaseApp.getInstance());
                showTopErrorBar(false);
                switch (networkState) {
                    case NETWORN_NONE:
                        showTopErrorBar(true);
                        break;
                    case NETWORN_MOBILE:
                        if (!bFirstNetworkAlert)
                            toast("切换网络到手机网络");
                        break;
                    case NETWORN_WIFI:
                        if (!bFirstNetworkAlert)
                            toast("切换网络到WIFI");
                        break;
                }
                bFirstNetworkAlert = false;

                if (bottomConnectInfo != null) {
                    bottomConnectInfo.setNetworkConnected();
                    if (!isConnected) {
                        bottomConnectInfo.setServerConnected(false);
                    }
                }

                if (!isConnected) {
                    OfflineWorkTool offlineWorkTool = OfflineWorkTool.getInstance();
                    offlineWorkTool.setServerConnected(false);
                }

                if (isConnected && !bHasAlertUpdate) {
                    new UpdateManager(UiMain.this).checkUpdate();
                    bHasAlertUpdate = true;
                }
            }));
        }
    };

    private void initView() {
        layoutMainRoot = findViewById(R.id.layout_main_root);
        textExit = findViewById(R.id.text_exit_app);
        bottomConnectInfo = findViewById(R.id.bottom_main_connect_info);

        //grid view
        mGridView = findViewById(R.id.ui_index_gridview);
        initGridView();
        initTopContent();

        /*屏幕是否锁定*/
        //boolean isScreenLocked = PowerUtils.isScreenLocked(this);
        startCheckMessageTimer();
    }

    private void initGridView() {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        List<MainModule.MainModuleBean> moduleBeans = userInfoTool.getUserMainModules();
        mGridViewAdapter = new GridViewAdapter(this, moduleBeans);
        mGridView.setAdapter(mGridViewAdapter);
    }

    private void initUserInfo() {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        String avatar = userBean.getAvatar();
        if (avatar != null && !avatar.isEmpty()) {//根据用户名下载头像
            String faceurl = NetRequestURL.newApi_dyrq.getFormattedPicture(avatar);
            ImageLoader loader = ImageLoader.getInstance();
            DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder()
                    .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
                    .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
                    .considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                    .build();
            loader.displayImage(faceurl, imageUserIcon, defaultDisplayImageOptions, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {
                    //showLoadBar();
                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {
                    imageUserIcon.setImageResource(R.mipmap.user_default_icon);
                    hideLoadBar();
                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    if (bitmap != null) {
                        imageUserIcon.setImageBitmap(bitmap);
                    }
                    hideLoadBar();
                }

                @Override
                public void onLoadingCancelled(String s, View view) {
                    hideLoadBar();
                }
            });
        }
    }

    private void initTopContent() {
        // 4.4及以上版本开启
        setTranslucentStatus();
        setToolbarPadding();
        setLightStatusBar();

        initAppBar();

        String date = DateUtils.getChinaYMD();
        textMainDate.setText(date);

        String today = DateUtils.getToday();
        textMainToday.setText(today);

        boolean isOffline = OfflineWorkTool.isOffline();
        imageOnlineMode.setSelected(!isOffline);

        boolean isSignedUp = BaseApp.getSignState() == UiSign.SIGN_CHECKED_ON_TYPE;
        imageSignStatus.setSelected(isSignedUp);

        initUserInfo();
    }

    private void initAppBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayHomeAsUpEnabled(false);
        }
        appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            if (verticalOffset == 0) {
                if (state != CollapsingToolbarLayoutState.EXPANDED) {
                    collapsingToolbarLayout.setTitle("");//设置title不显示
                    layoutTopContent.setVisibility(View.VISIBLE);
                    state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                }
            } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                    collapsingToolbarLayout.setTitle(getString(R.string.app_name));
                    layoutTopContent.setVisibility(View.GONE);
                    state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                }
            } else {
                if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                    if (state == CollapsingToolbarLayoutState.COLLAPSED) {
                        collapsingToolbarLayout.setTitle("");//设置title不显示
                        layoutTopContent.setVisibility(View.VISIBLE);
                    }
                    state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                }
            }
        });
    }

    private void initData() {
        dbDaoHelper = DBDaoHelper.getInstance();
        signTool = SignTool.getInstance();
        userInfoTool = UserInfoTool.getInstance();
        permissionHelper = new PermissionHelper(this);

//        当用户打开主界面，自动清除 45天前的gps轨迹和签到记录
        userInfoTool.removeLocalLocationGpsData();
        userInfoTool.removeLocalSignHistoryData();
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            String user_id = userBean.getUserid();
            LogRecorder.clearLogBeforeDay(user_id);
            userInfoTool.removePlansOverTime();
        }
        resetTodayPlan();

        Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null && bundle.containsKey(DeviceInfoTool.DEVICEINFO_PLAN_DOWN_ERR_MAX)) {
            boolean isPlanDownMax = bundle.getBoolean(DeviceInfoTool.DEVICEINFO_PLAN_DOWN_ERR_MAX, false);
            if (isPlanDownMax) {
                showUpdatePlanPointErrDialog();
            }
        }
        if (userBean != null) {
            getUserMapConfigData();
            checkServerMapData();
            getMapLayerIndexConfig();
            getUserGisToken();
            getSignListToday();
        } else {
            checkLogin();
        }

        bind();

        /* index gridview 业务 */
        mGridView.setOnItemClickListener((parent, view, position, id) -> {
            if (BaseApp.getSignState() != UiSign.SIGN_CHECKED_ON_TYPE) {
                if (mGridViewAdapter != null) {
                    MainModule.MainModuleBean moduleBean = (MainModule.MainModuleBean) mGridViewAdapter.getItem(position);
                    if (moduleBean.isNeedSign()) {
                        toast("未签到，请签到后再使用该功能");
                        return;
                    }
                }
            }

            Intent intent1 = new Intent();
            MainModule.MainModuleBean menu = (MainModule.MainModuleBean) mGridView.getAdapter().getItem(position);
            String title = getString(menu.getTitle());
            intent1.putExtra("title", title);
            intent1.setClass(UiMain.this, menu.getAclass());
            startActivity(intent1);
        });
        //getUnread();
    }

    private void initListener() {
        //batteryOptimizeWarn();
        textExit.setOnClickListener(this);
    }

    private void batteryOptimizeWarn() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String packageName = getPackageName();
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + packageName));
                startActivity(intent);
            }
        }
    }

    private void checkLogin() {
        boolean hasToken = false;
        boolean hasName = false;
        boolean bRemembered = false;
        String token = "";
        String name = "";
        String userid = "";

        /*判断用户是否登陆过，并且拿到数据库中的用户token，否则则视为未登录过*/
        UserBean rememberedUser = SharePreUtil.getLoginInfo(this);
        bRemembered = SharePreUtil.getIsLogined(this);
        if (!bRemembered) {
            return;
        }

        if (rememberedUser != null) {
            String saveName = rememberedUser.getUsername();
            if (saveName != null && !saveName.isEmpty()) {
                hasName = true;
                name = saveName;
            }

            String saveUserId = rememberedUser.getUserid();
            if (saveUserId != null && !saveUserId.isEmpty()) {
                userid = saveUserId;
                UserBean savedUser = dbDaoHelper.queryUserByUserId(userid);
                if (savedUser != null) {
                    hasToken = true;
                    token = savedUser.getToken();
                }
            }
        }

        /*如果获取到token，向服务器请求用户信息*/
        if (bRemembered && hasToken && hasName) {
            getUserInfo(name, token);
            getSignListToday();
        }
    }

    private void getUserInfo(String username, final String token) {
        userInfoTool.getUserInfo(this, username, token, new UserCallBack() {
            @Override
            public void onGetAccountInfo(boolean isSuccess, int errorCode, String errMsg, UserBean user) {
                super.onGetAccountInfo(isSuccess, errorCode, errMsg, user);
                if (isSuccess) {
                    initUserInfo();
                }
            }
        });
    }

    private void getSignListToday() {
        OfflineWorkTool.getInstance().checkTodayWorkNeeds(this);
    }

    private void getSignStatusToday() {
        signTool.getSignStatusToday(this, new SignCallBack() {
            @Override
            public void onGetSignStatusToday(boolean isSuccess, int errorCode, String errMsg, int signState, int section) {
                super.onGetSignStatusToday(isSuccess, errorCode, errMsg, signState, section);
                if (isSuccess) {
                    onGetSingStatusOk(signState);
                    EventBus.getDefault().post(new UiUserInfo.MessageEvent(UiUserInfo.USER_SIGN_STATUS_CHANGED));
                } else {
                    /*未获取到签到状态时，提示用户重新获取用户签到信息*/
                    if (BaseApp.getSignState() == -1) {
                        //onGetSignStatusError();
                    }
                    DialogUtil.showTokenFailedDialog(UiMain.this, errorCode);
                }
            }
        });
    }

    private void onGetSignStatusError() {
        if (snackbarSign == null) {
            String msg = getResources().getString(R.string.main_load_usersign_err);
            snackbarSign = Snackbar.make(layoutMainRoot, msg, Snackbar.LENGTH_SHORT)
                    .setAction(getResources().getString(R.string.retry), v -> getSignStatusToday())
                    .setDuration(Snackbar.LENGTH_INDEFINITE);
        }
        snackbarSign.show();
    }

    private void onGetSingStatusOk(int signState) {
        if (snackbarSign != null)
            snackbarSign.dismiss();

        boolean isSignedUp = signState == UiSign.SIGN_CHECKED_ON_TYPE;
        imageSignStatus.setSelected(isSignedUp);

        if (signState == UiSign.SIGN_CHECKED_ON_TYPE) {
            mGridViewAdapter.setItemText(UiSign.class, R.string.sign_xb);
            if (!bHasCheckTodayPlan) {
                bHasCheckTodayPlan = true;
                DeviceInfoTool deviceInfoTool = DeviceInfoTool.getInstance();
                deviceInfoTool.checkTodayPlanCount(true, null);
            }
        } else {
            mGridViewAdapter.setItemText(UiSign.class, R.string.sign_sb);
        }

        if (signState == UiSign.SIGN_UNCHECKED_TYPE) {
            //未提醒过签到，则提醒签到
            if (!bHasAlertSign) {
                bHasAlertSign = true;
                forwardToUiSign();
            }
        }
    }

    private void signOffAndExit() {
        if (BaseApp.getSignState() == UiSign.SIGN_CHECKED_ON_TYPE) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.exit);
            builder.setMessage(R.string.dialog_exit_need_resign);
            builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
                String strUploading = getString(R.string.sign_off_ing);
                ProgressManager.getInstance().showProgress(UiMain.this, null, strUploading, false);
                signTool.signOff(UiMain.this, (isSuccess, errMsg, erroCode) -> {
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                        String messge = getString(R.string.sign_off_ok_exit);
                        ProgressManager.getInstance().showProgress(UiMain.this, null, messge, false);
                        /*设置下次进入系统首先进入登录界面*/
                        SharePreUtil.setIsNeedReLogin(UiMain.this, true);
                        /*退出系统*/
                        BaseApp.getInstance().exitAppDelayed(BaseApp.DELAYED_EXIT_SECOND);
                    } else {
                        String msg = getResources().getString(R.string.sign_off_failed_err) + errMsg;
                        toast(errMsg);
                    }
                });
            });
            builder.setNegativeButton(android.R.string.cancel, null);
            builder.show();
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.exit);
            builder.setMessage(R.string.dialog_exit_message);
            builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
                /*设置下次进入系统首先进入登录界面*/
                SharePreUtil.setIsNeedReLogin(UiMain.this, true);
                BaseApp.getInstance().exitApp();
            });
            builder.setNegativeButton(android.R.string.cancel, null);
            builder.show();
        }
    }

    private void forwardToUiSign() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.dialog_onsign_on_title);
        builder.setMessage(R.string.dialog_onsign_no_message);
        builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
            Intent intent = new Intent();
            intent.putExtra("title", getString(R.string.index_gridview_sign));
            intent.setClass(UiMain.this, UiSign.class);
            startActivity(intent);
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void checkServerConfigData() {
        SystemConfigTool systemConfigTool = SystemConfigTool.getInstance();
        systemConfigTool.checkConfigUpdate(this);
    }

    private void checkServerMapData() {
        if (!bHasAlertMapUpdate) {
            DownloadTool downloadTool = DownloadTool.getInstance();
            downloadTool.checkConfigUpdate(this);
            bHasAlertMapUpdate = true;
        }
    }


    private void checkTodayPlan() {
        SignDataBean onSign = dbDaoHelper.getTodaySignOn();
        UserBean user = BaseApp.getInstance().getLoginUser();
        if (onSign != null && user != null) {
            int car_mode = user.getCar_mode();
            int needUpdate = (car_mode == UserBean.PATROL_TYPE_CAR ?
                    onSign.getCarNeedUpdate() : onSign.getNeedUpdate());
            if (needUpdate == 1) {
                showUpdatePlanPointDialog();
            }
        }
    }

    private void needTodayPlanPoint() {
        PlanTool planTool = PlanTool.getInstance();
        planTool.needTodayPlanPoint();
    }

    private void resetTodayPlan() {
        PlanTool planTool = PlanTool.getInstance();
        planTool.resetTodayPlan();
    }

    private void checkTodayBuildLogPlan() {
        BuildSignDataBean buildSignData = new BuildSignDataBean();
        String todayDate = DateUtils.getYMD();
        buildSignData.setPlanDate(todayDate);
        dbDaoHelper.insertOrUpdateBuildSignData(buildSignData);
    }

    private void forwartToUiSysConfig() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.server_config_change_title);
        builder.setMessage(R.string.server_config_changed);
        builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
            Intent intent = new Intent();
            intent.setClass(UiMain.this, UiSystemConfig.class);
            startActivity(intent);
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void forwartToUiDownloadMap() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.update_map_change_title);
        builder.setMessage(R.string.update_map_change_alert);
        builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
            Intent intent = new Intent();
            intent.setClass(UiMain.this, DownloadMapActivity.class);
            startActivity(intent);
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }


    private void getUserMapConfigData() {
        userInfoTool.getUserMapConfigData(this, new UserCallBack() {
            @Override
            public void onGetMapConfigData(boolean isSuccess, int errorCode, String errMsg, List<UserOnlineMapDataBean> urlConfigDataBean, List<UserMapDataBean> userMapDataBeanList) {
                super.onGetMapConfigData(isSuccess, errorCode, errMsg, urlConfigDataBean, userMapDataBeanList);
                if (isSuccess) {
                    connect_mapconfig_error_count = 0;
                } else {
                    if (connect_mapconfig_error_count > 3) {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        String strWarn = getResources().getString(R.string.main_load_usermap_err) + errMsg;
                        toast(strWarn);
                        connect_mapconfig_error_count = 0;
                        checkUserMapConfig();
                    } else {
                        connect_mapconfig_error_count++;
                        getUserMapConfigData();
                    }
                }
            }
        });
    }

    private void getMapLayerIndexConfig() {
        userInfoTool.getMapLayerIndexConfig(this, new UserCallBack() {
            @Override
            public void onGetMapLayerIndexConfigData(boolean isSuccess, int errorCode, String errMsg, List<FieldsBean> results) {
                super.onGetMapLayerIndexConfigData(isSuccess, errorCode, errMsg, results);
            }
        });
    }

    private void getUserGisToken() {
        //userInfoTool.getUserGisToken(this, null);
    }

    //双击退出程序
    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        gotoSystemHome();
    }

    public void delayForward(final Class<?> classObj, final Bundle bundle) {
        //设置延迟时间
        final int SKIP_DELAY_TIME = 300;
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.setClass(UiMain.this, classObj);
                if (bundle != null) {
                    intent.putExtras(bundle);
                }
                startActivity(intent);
                overridePendingTransition(0, R.anim.anim_leftout);
            }
        };
        timer.schedule(task, SKIP_DELAY_TIME);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_exit_app:
                signOffAndExit();
                break;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        permissionHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
    }

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

    @OnClick(R.id.text_assignment_more)
    public void onViewClicked() {
        Intent intent = new Intent(this, HomeActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(HomeActivity.INDEX_HOME_ACTIVITY_KEY, R.id.radio_btn_message);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
