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

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.mgq.base.utils.Number.NumberUtils;
import com.mgq.base.utils.customview.CircleImageView;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
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.url.NetRequestURL;
import com.tofly.ghrq_route.common.ui.dialog.UserBindCarDailog;
import com.tofly.ghrq_route.module.dasData.ui.UiDasData;
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.DeviceBean;
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 butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.view.KeyEvent.KEYCODE_BACK;

/**
 * Created by zombiexq on 2016/7/1.
 */
public class UiProfile extends BaseUi {
    @BindView(R.id.layout_main_root)
    LinearLayout layouMainRoot;
    @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.layout_action_bar)
    RelativeLayout layoutTitleBar;
    @BindView(R.id.action_bar_face)
    CircleImageView imageActionFace;
    @BindView(R.id.face)
    CircleImageView imageUserFace;
    @BindView(R.id.text_user_name)
    TextView textUserName;
    @BindView(R.id.text_user_group)
    TextView textUserGroup;
    @BindView(R.id.image_sign_status)
    ImageView imageUserStatus;
    @BindView(R.id.switch_car_mode)
    SwitchCompat switchCarMode;
    @BindView(R.id.switch_big_font)
    SwitchCompat switchBigFont;
    @BindView(R.id.switch_loc_alert)
    SwitchCompat switchLocAlert;
    @BindView(R.id.switch_loc_vibrate)
    SwitchCompat switchLocVibrate;
    @BindView(R.id.edit_vibrate_wake_time)
    EditText editVibrateTime;
    @BindView(R.id.switch_screen_on)
    SwitchCompat switchScreenOn;

    //private final static String TAG = UiProfile.class.getSimpleName();

    private boolean bShouldDialogReact = true;

    private boolean bShouldVibrateReact = true;

    private UserInfoTool userInfoTool;

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

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

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

        EventBusUtil.register(this);
    }

    @Subscribe()
    public void onMessageEvent(UiUserInfo.MessageEvent messageEvent) {
        if (messageEvent.message.equals(UiUserInfo.USER_ACCOUNT_CHANGED)) {
            initUserInfo();
        } else if (messageEvent.message.endsWith(UiUserInfo.USER_SIGN_STATUS_CHANGED)) {
            boolean isSignedUp = BaseApp.getSignState() == UiSign.SIGN_CHECKED_ON_TYPE;
            imageUserStatus.setSelected(isSignedUp);
        }
    }

    private void initView() {
        initAppBar();
    }

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

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayHomeAsUpEnabled(false);
        }

        appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            if (verticalOffset == 0) {
                if (state != CollapsingToolbarLayoutState.EXPANDED) {
                    state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                }
            } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                    layoutTitleBar.setVisibility(View.VISIBLE);//隐藏播放按钮
                    state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                    setDarkStatusBar();
                }
            } else {
                if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                    if(state == CollapsingToolbarLayoutState.COLLAPSED){
                        layoutTitleBar.setVisibility(View.GONE);//由折叠变为中间状态时隐藏播放按钮
                        setLightStatusBar();
                    }
                    state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                }
            }
        });
    }

    private void initSwitchBtns() {
        /*车载模式设置*/
        boolean isCarMode = false;
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null)
            isCarMode = userBean.isCarMode();
        switchCarMode.setChecked(isCarMode);
        switchCarMode.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (bShouldDialogReact) {
                if (isChecked) {
                    showBindCarDialog();
                } else {
                    showUnbindCarDialog();
                }
            }
            clearEditFocus();
        });

        /*字体大小设置*/
        boolean isBigFont = BaseApp.getInstance().isUseBigFont();
        switchBigFont.setChecked(isBigFont);
        switchBigFont.setOnCheckedChangeListener((buttonView, isChecked) -> {
            clearEditFocus();

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("程序退出");
            builder.setMessage("设置生效！程序即将退出，请手动重启程序。");
            builder.setCancelable(false);
            builder.show();
            BaseApp.getInstance().setUseBigFont(isChecked);
        });

        /*坐标实时提示设置*/
        boolean isGpsNotify = BaseApp.getInstance().isGpsNotifyOpen();
        switchLocAlert.setChecked(isGpsNotify);
        switchLocAlert.setOnCheckedChangeListener((buttonView, isChecked) -> {
            clearEditFocus();
            BaseApp.getInstance().setGpsNotifyOpen(isChecked);
        });


        /*坐标震动提示设置*/
        boolean isGpsVibrate = BaseApp.getInstance().isGpsVibrateOn();
        int iGpsVibrateTimes = BaseApp.getInstance().getiGpsVibratePeriodTime();
        switchLocVibrate.setChecked(isGpsVibrate);
        editVibrateTime.setText(NumberUtils.intToString(iGpsVibrateTimes));
        switchLocVibrate.setOnCheckedChangeListener((buttonView, isChecked) -> {
            clearEditFocus();
            String period = editVibrateTime.getText().toString();
            if (isChecked){
                if (period.isEmpty()){
                    bShouldVibrateReact = false;
                    switchLocVibrate.setChecked(false);
                }else {
                    BaseApp.getInstance().setGpsVibrateOn(true, Integer.parseInt(period));
                    bShouldVibrateReact = true;
                }
            }else {
                if (bShouldVibrateReact){
                    BaseApp.getInstance().setGpsVibrateOn(false, 0);
                }
                bShouldVibrateReact = true;
            }
        });

        /*是否设置屏幕常亮*/
        boolean isKeepScreenOn = BaseApp.getInstance().isbKeepScreenOn();
        switchScreenOn.setChecked(isKeepScreenOn);
        switchScreenOn.setOnCheckedChangeListener((buttonView, isChecked) -> {
            clearEditFocus();
            BaseApp.getInstance().setKeepScreenOnMode(isChecked);
        });
    }

    private void initData() {
        userInfoTool = UserInfoTool.getInstance();

        initUserInfo();
        getUserInfo();
    }

    private void initUserInfo() {
        UserBean user = BaseApp.getInstance().getLoginUser();
        textUserName.setText(user.getRealName());
        textUserGroup.setText(user.getDepartmentName());

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

        String avatar = user.getAvatar();
        if (avatar != null && !avatar.isEmpty()) {//根据用户名下载头像
            String faceurl = NetRequestURL.newApi_dyrq.getFormattedPicture(avatar);
            ImageLoader loader = ImageLoader.getInstance();
            DisplayImageOptions.Builder builder = BaseApp.getDefaultDisplayOptionsBuilder();
            builder.showImageOnFail(R.mipmap.user_default_icon);
            loader.displayImage(faceurl, imageUserFace, builder.build());
            loader.displayImage(faceurl, imageActionFace, builder.build());
        }

        initSwitchBtns();
    }

    private void initListener() {

    }

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

    private void getUserInfo() {
        showLoadBar();
        userInfoTool.getUserInfoOnline(this, new UserCallBack() {
            @Override
            public void onGetAccountInfo(boolean isSuccess, int errorCode, String errMsg, UserBean user) {
                super.onGetAccountInfo(isSuccess, errorCode, errMsg, user);
                hideLoadBar();
                if (isSuccess) {
                    initUserInfo();
                } else {
                    //showTokenFailedDialog(errorCode);
                }
            }
        });
    }

    private void showBindCarDialog() {
        UserBindCarDailog userBindCarDailog = new UserBindCarDailog(this);
        userBindCarDailog.setClicklistener(new UserBindCarDailog.ClickListenerInterface() {
            @Override
            public void doOk(String carno) {
                userBindCar(carno);
            }

            @Override
            public void doCancel() {
                setCarModeOn(false);
            }
        });
        userBindCarDailog.show();
    }

    private void userBindCar(final String carno) {
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        userInfoTool.userBindCar(this, carno, new UserCallBack(){
            @Override
            public void onUserBindCar(boolean isSuccess, int errorCode, String errMsg) {
                super.onUserBindCar(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess){
                }else {
                    setCarModeOn(false);
                }
            }

            @Override
            public void onGetUserInfo(boolean isSuccess, int errorCode, String errMsg, UserBean user, DeviceBean device) {
                super.onGetUserInfo(isSuccess, errorCode, errMsg, user, device);
                if (isSuccess){
                    initUserInfo();
                }
            }
        });
    }

    private void showUnbindCarDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.dialog_unbindcar_title);
        builder.setMessage(R.string.dialog_unbindcar_hint);
        builder.setPositiveButton(android.R.string.ok, (dialog, which) -> userUnBindCar());
        builder.setNegativeButton(android.R.string.cancel, (dialog, which) -> setCarModeOn(true));
        builder.setOnKeyListener((dialog, keyCode, event) -> {
            if (event.getKeyCode() == KEYCODE_BACK) {
                setCarModeOn(true);
            }
            return false;
        });
        builder.show();
    }

    private void userUnBindCar() {
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        userInfoTool.userUnBindCar(this, new UserCallBack(){
            @Override
            public void onUserUnBindCar(boolean isSuccess, int errorCode, String errMsg) {
                super.onUserUnBindCar(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess){
                }else {
                    setCarModeOn(true);
                }
            }

            @Override
            public void onGetUserInfo(boolean isSuccess, int errorCode, String errMsg, UserBean user, DeviceBean device) {
                super.onGetUserInfo(isSuccess, errorCode, errMsg, user, device);
                if (isSuccess){
                    initUserInfo();
                }
            }
        });
    }

    private void setCarModeOn(boolean on) {
        bShouldDialogReact = false;
        switchCarMode.setChecked(on);
        bShouldDialogReact = true;
    }

    @OnClick({R.id.relativelayout_daily_attend, R.id.relativelayout_log_upload, R.id.relativelayout_data_export,
            R.id.relativelayout_data_kml, R.id.relativelayout_data_update, R.id.relativelayout_system_info,
            R.id.relativelayout_about_system, R.id.relativelayout_system_logout, R.id.layout_user_info_more,
            R.id.layout_main_root})
    public void onClick(View view) {
        clearEditFocus();
        switch (view.getId()) {
            case R.id.relativelayout_daily_attend: {
                overlay_to(UiDailyPlan.class);
            }
            break;
            case R.id.relativelayout_log_upload: {
                overlay_to(UiLogUpload.class);
            }
            break;
            case R.id.relativelayout_data_export: {
                overlay_to(UiDatabaseExport.class);
            }
            break;
            case R.id.relativelayout_data_kml: {
                overlay_to(UiDasData.class);
            }
            break;
            case R.id.relativelayout_data_update: {
                overlay_to(UiDataUpdate.class);
            }
            break;
            case R.id.relativelayout_system_info: {
                overlay_to(UiSystemInfo.class);
            }
            break;
            case R.id.relativelayout_about_system: {
                overlay_to(UiAbout.class);
            }
            break;
            case R.id.relativelayout_system_logout: {
                checkLogout();
            }
            break;
            case R.id.layout_user_info_more: {
                overlay_to(UiUserInfo.class);
            }
            break;
            case R.id.layout_main_root: {

            }
            break;
        }
    }

    private void checkLogout() {
        if (BaseApp.getSignState() == UiSign.SIGN_CHECKED_ON_TYPE){
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.dialog_logout_title);
            builder.setMessage(R.string.dialog_logout_need_resign);
            builder.setPositiveButton(android.R.string.ok, null);
            builder.show();
        }else {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.dialog_logout_title);
            builder.setMessage(R.string.dialog_logout_message);
            builder.setPositiveButton(android.R.string.ok, (dialog, which) -> logout());
            builder.setNegativeButton(android.R.string.cancel, null);
            builder.show();
        }
    }

    private void logout() {
        BaseApp.getInstance().stopAllBackgroundService(this);

        SharePreUtil.setIsNeedReLogin(this, true);
        overlay_to(UiLogin.class);
        finish();
    }

    private void clearEditFocus() {
        editVibrateTime.clearFocus();
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBusUtil.unregister(this);
    }
}
