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

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
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.base.url.NetRequestURL;
import com.tofly.ghrq_route.module.service.NetStateService;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.systemConfig.controller.ServerSysConfigCallBack;
import com.tofly.ghrq_route.module.systemConfig.controller.ServerSysConfigController;
import com.tofly.ghrq_route.module.systemConfig.domain.ServerParamConfigBean;
import com.tofly.ghrq_route.module.systemConfig.domain.SystemConfigBean;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.controller.UserController;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.sharedPreference.SharePreUtil;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Amu on 2017/6/23.
 */

public class UiSystemConfig extends BaseUi {
    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.text_sysconf_server)
    TextView textSysconfServer;
    @BindView(R.id.text_sysconf_uprate)
    TextView textSysconfUprate;
    @BindView(R.id.text_sysconf_radius)
    TextView textSysconfRadius;
    @BindView(R.id.text_sysconf_radius_device)
    TextView textSysconfRadiusDevice;
    @BindView(R.id.tv_rx_zkcksd)
    TextView tvRxZkcksd;
    @BindView(R.id.text_cx_zkcksd)
    TextView textCxZkcksd;
    @BindView(R.id.text_cx_zddwrc)
    TextView textCxZddwrc;
    @BindView(R.id.text_dw_yxjd)
    TextView textDwYxjd;
    @BindView(R.id.text_sysconf_photo_watermark)
    TextView textSysconfPhotoWatermark;

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

    private DBDaoHelper dbDaoHelper;

    private ServerSysConfigController sysConfigController;

    private UserController userController;

    private NetStateService netStateService;

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

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

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

    private void initView() {

    }

    private void initData() {
        dbDaoHelper = DBDaoHelper.getInstance();
        loadServerConfig();
    }

    private void initListener() {

    }

    private void loadServerConfig() {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (sysConfigController == null)
            sysConfigController = new ServerSysConfigController(this);
        String strUploading = getString(R.string.updating_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        sysConfigController.getSysSetting(this, new ServerSysConfigCallBack() {
            @Override
            public void onGetSysSetting(boolean isSuccess, int errorCode, String errMsg, JsonObject settings) {
                super.onGetSysSetting(isSuccess, errorCode, errMsg, settings);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    if (settings != null) {
                        String server_addr = "";
                        String server_port = "";
                        String server_uprate = "";
                        String server_refresh = "";
                        String server_radius = "";
                        String server_radius_device = "";
                        String server_uprate_car = "";
                        String server_radius_car = "";
                        String server_build_range = "";
                        String server_speed = "";
                        String server_speed_car = "";
                        String server_gps_precision = "";
                        String server_max_gps_speed = "";
                        String server_photo_watermark = "";

                        ServerParamConfigBean paramConfigBean = new ServerParamConfigBean();
                        String key = SystemConfigBean.SERVER_ADDR_KEY;
                        String desc = SystemConfigBean.SERVER_ADDR_DESC;
                        if (settings.has(key)) {
                            JsonElement jsonAddr = settings.get(key);
                            server_addr = jsonAddr.getAsString();
                            textSysconfServer.setText(server_addr);

                            updateDatabase(key, server_addr, desc);
                        }
//                        key = SystemConfigBean.SERVER_PORT_KEY;
//                        desc = SystemConfigBean.SERVER_PORT_DESC;
//                        if (settings.has(key)) {
//                            JsonElement jsonPort = settings.get(key);
//                            if (!jsonPort.isJsonNull()) {
//                                server_port = jsonPort.getAsString();
//                                textSysconfPort.setText(server_port);
//
//                                updateDatabase(key, server_port, desc);
//                            }
//                        }
                        key = SystemConfigBean.SERVER_UPRATE_KEY;
                        desc = SystemConfigBean.SERVER_UPRATE_DESC;
                        if (settings.has(key)) {
                            JsonElement jsonUprate = settings.get(key);
                            server_uprate = jsonUprate.getAsString();
                            paramConfigBean.setUploadRate(server_uprate);
                            textSysconfUprate.setText(server_uprate + "秒");

                            updateDatabase(key, server_uprate, desc);
                        }
                        key = SystemConfigBean.SERVER_REFRESH_KEY;
                        desc = SystemConfigBean.SERVER_REFRESH_DESC;
                        if (settings.has(key) && settings.get(key) != null) {
                            JsonElement jsonRefresh = settings.get(key);
                            server_refresh = jsonRefresh.getAsString();
                            paramConfigBean.setRefreshInternal(server_refresh);

                            updateDatabase(key, server_refresh, desc);
                        }
                        key = SystemConfigBean.SERVER_RADIUS_KEY;
                        desc = SystemConfigBean.SERVER_RADIUS_DESC;
                        if (settings.has(key)) {
                            JsonElement jsonRadius = settings.get(key);
                            server_radius = jsonRadius.getAsString();
                            paramConfigBean.setMinDistanceInPlace(server_radius);
                            textSysconfRadius.setText(server_radius + "米");

                            updateDatabase(key, server_radius, desc);
                        }
                        key = SystemConfigBean.SERVER_RADIUS_DEVICE_KEY;
                        desc = SystemConfigBean.SERVER_RADIUS_DEVICE_DESC;
                        if (settings.has(key)) {
                            JsonElement jsonRadius = settings.get(key);
                            server_radius_device = jsonRadius.getAsString();
                            paramConfigBean.setMinDistanceInDevice(server_radius_device);
                            textSysconfRadiusDevice.setText(server_radius_device + "米");

                            updateDatabase(key, server_radius, desc);
                        }
/*                        key = SystemConfigBean.SERVER_UPRATE_CAR_KEY;
                        desc = SystemConfigBean.SERVER_UPRATE_CAR_DESC;
                        if (settings.has(key)) {
                            JsonElement jsonUprate = settings.get(key);
                            server_uprate_car = jsonUprate.getAsString();
                            paramConfigBean.setCarRefreshInternal(server_uprate_car);
                            textSysconfUprateCar.setText(server_uprate_car + "秒");

                            updateDatabase(key, server_uprate_car, desc);
                        }*/
                        key = SystemConfigBean.SERVER_RADIUS_CAR_KEY;
                        desc = SystemConfigBean.SERVER_RADIUS_CAR_DESC;
                        if (settings.has(key)) {
                            JsonElement jsonRadius = settings.get(key);
                            server_radius_car = jsonRadius.getAsString();
                            paramConfigBean.setCarMinDistanceInPlace(server_radius_car);
                            textCxZddwrc.setText(server_radius_car + "米");

                            updateDatabase(key, server_radius_car, desc);
                        }
/*                        key = SystemConfigBean.SERVER_BUILD_RANGE_KEY;
                        desc = SystemConfigBean.SERVER_BUILD_RANGE_DESC;
                        if (settings.has(key)) {
                            JsonElement jsonRadius = settings.get(key);
                            server_build_range = jsonRadius.getAsString();
                            paramConfigBean.setBuildRange(server_build_range);
                            textSysconfBuildRange.setText(server_build_range + "米");

                            updateDatabase(key, server_build_range, desc);
                        }*/
                        key = SystemConfigBean.SERVER_MAX_SPEED_KEY;
                        desc = SystemConfigBean.SERVER_MAX_SPPED_DESC;
                        if (settings.has(key)) {
                            JsonElement jsonSpeed = settings.get(key);
                            server_speed = jsonSpeed.getAsString();
                            paramConfigBean.setMaxSpeed(server_speed);
                            tvRxZkcksd.setText(server_speed + "千米/小时");

                            updateDatabase(key, server_speed, desc);
                        }
                        key = SystemConfigBean.SERVER_MAX_SPEED_CAR_KEY;
                        desc = SystemConfigBean.SERVER_MAX_SPPED_CAR_DESC;
                        if (settings.has(key)) {
                            JsonElement jsonSpeedCar = settings.get(key);
                            server_speed_car = jsonSpeedCar.getAsString();
                            paramConfigBean.setCarMaxSpeed(server_speed_car);
                            textCxZkcksd.setText(server_speed_car + "千米/小时");

                            updateDatabase(key, server_speed_car, desc);
                        }
                        key = SystemConfigBean.SERVER_MAX_GPS_PRECISION_KEY;
                        desc = SystemConfigBean.SERVER_MAX_GPS_PRECISION_DESC;
                        if (settings.has(key)) {
                            JsonElement jsonGpsPrecision = settings.get(key);
                            server_gps_precision = jsonGpsPrecision.getAsString();
                            paramConfigBean.setTrackMaxAccuracy(server_gps_precision);
                            textDwYxjd.setText(server_gps_precision + "米");

                            updateDatabase(key, server_gps_precision, desc);
                        }
                        key = SystemConfigBean.SERVER_MAX_GPS_SPEED_KEY;
                        desc = SystemConfigBean.SERVER_MAX_GPS_SPEED_DESC;
                        if (settings.has(key)) {
                            JsonElement jsonMaxGpsSpeed = settings.get(key);
                            server_max_gps_speed = jsonMaxGpsSpeed.getAsString();
                            paramConfigBean.setTrackMaxSpeed(server_max_gps_speed);

                            updateDatabase(key, server_max_gps_speed, desc);
                        }
                        key = SystemConfigBean.SERVER_PHOTO_WATERMARK_KEY;
                        desc = SystemConfigBean.SERVER_PHOTO_WATERMARK_DESC;
                        if (settings.has(key)) {
                            JsonElement jsonPhotoWatermark = settings.get(key);
                            server_photo_watermark = jsonPhotoWatermark.getAsString();
                            paramConfigBean.setImageWatermark(server_photo_watermark);
                            textSysconfPhotoWatermark.setText(server_photo_watermark.equals("0") ? R.string.yes : R.string.no);

                            updateDatabase(key, server_photo_watermark, desc);
                        }
                        setLocalUprateRadius(paramConfigBean);
                        //checkServerAddr(server_addr, server_port);
                    }
                    String content = getString(R.string.update_success);
                    showUpdateResultDialog(content, null);
                } else {
                    toast(errMsg);
                    showUpdateResultDialog(getString(R.string.update_failed), errMsg);
                }
            }
        });
    }

    private void showUpdateResultDialog(String title, String content) {
//        String title = getString(R.string.update_prompt);
        AlertDialog.Builder builder = new AlertDialog.Builder(UiSystemConfig.this);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setCancelable(false);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    private void updateDatabase(String key, String value, String desc) {
        if (key != null && !key.isEmpty() && value != null && !value.isEmpty()) {
            SystemConfigBean systemConfigBean = new SystemConfigBean();
            systemConfigBean.setCode(key);
            systemConfigBean.setValue(value);
            if (desc != null && !desc.isEmpty()) {
                systemConfigBean.setDesc(desc);
            }
            dbDaoHelper.insertOrUpdateSysConfig(systemConfigBean);
        }
    }

    private void setLocalUprateRadius(ServerParamConfigBean paramConfigBean) {
        BaseApp.getInstance().setUprateRaidusToConfig(paramConfigBean);
    }

    private void checkServerAddr(String addr, String port) {
        String oldAddr = NetRequestURL.HTTPHEAD;
        /*String oldPort = NetRequestURL.HTTPPORT;*/

        boolean bNeedLogOut = false;
        if (addr != null && !addr.isEmpty() /*&& port != null && !port.isEmpty()*/) {
            if (!oldAddr.equals(addr) /*|| !oldPort.equals(port)*/)
                bNeedLogOut = true;
        }

        if (bNeedLogOut) {
            showLogoutAlert();
        }
    }

    private void showLogoutAlert() {
        String title = "重新登陆";
        String content = "当前服务器地址已经改变，需要重新登陆!";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setCancelable(false);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                logout();
            }
        });
        builder.show();
    }

    private void logout() {
        if (userController == null)
            userController = new UserController(this);
        UserBean user = BaseApp.getInstance().getLoginUser();
        userController.logout(user.getToken(), new UserCallBack() {
            @Override
            public void onLogout(boolean isSuccess, int errorCode, String errMsg) {
                super.onLogout(isSuccess, errorCode, errMsg);
                if (isSuccess) {
                    BaseApp.getInstance().stopAllBackgroundService(UiSystemConfig.this);

                    SharePreUtil.setIsNeedReLogin(UiSystemConfig.this, true);
                    Intent intent = new Intent();
                    intent.setClass(UiSystemConfig.this, UiLogin.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish();

                    BaseApp.getInstance().initDataBase();
                } else {
                    toast(errMsg);
                }
            }
        });
    }

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