package com.stm.asset.page;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.stm.asset.R;
import com.stm.asset.base.BaseActivity;
import com.stm.asset.base.StmApplication;
import com.stm.asset.http.HttpException;
import com.stm.asset.http.HttpService;
import com.stm.asset.http.RequestCallback;
import com.stm.asset.json.CommonMapJson;
import com.stm.asset.model.UserInfo;
import com.stm.asset.utils.NetworkUtil;
import com.stm.asset.utils.VersionUtil;
import com.stm.asset.utils.ViewUtil;
import com.stm.asset.view.CommonAlertDialog;
import com.stm.asset.view.LoadingDialog;

import java.util.Map;

/**
 * 类名称：MainActivity
 * 类描述：主页面
 * 创建人：story
 * 创建时间：2021-12-08 16:39
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout logoutLayout;
    private View logoutLine;
    private TextView userTxt;

    private UserInfo userInfo;
    private LoadingDialog loadingDialog;
    private Map<String, String> versionMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        loadingDialog = new LoadingDialog(this);
    }

    private void initView() {
        userTxt = findViewById(R.id.main_user_txt);
        logoutLayout = findViewById(R.id.main_logout_layout);
        logoutLine = findViewById(R.id.main_logout_line);
        userTxt.setOnClickListener(this);
        findViewById(R.id.main_inventory_data_layout).setOnClickListener(this);
        findViewById(R.id.main_begin_inventory_layout).setOnClickListener(this);
        findViewById(R.id.main_settings_layout).setOnClickListener(this);
        logoutLayout.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        userInfo = StmApplication.getInstance().getUserInfo();
        if (userInfo != null) {
            String str = "用户：" + userInfo.getName();
            userTxt.setText(str);
            logoutLayout.setVisibility(View.VISIBLE);
            logoutLine.setVisibility(View.VISIBLE);
        } else {
            userTxt.setText("登录");
            logoutLayout.setVisibility(View.GONE);
            logoutLine.setVisibility(View.GONE);
        }
        // 不需要登录
        userTxt.setVisibility(View.GONE);
    }

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

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

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_user_txt:
                if (userInfo == null) {
                    Intent loginIntent = new Intent();
                    loginIntent.setClass(MainActivity.this, LoginActivity.class);
                    startActivity(loginIntent);
                }
                break;
            case R.id.main_inventory_data_layout:
                Intent gotoTaskIntent = new Intent();
                gotoTaskIntent.setClass(MainActivity.this, AdvantageListActivity.class);
                startActivity(gotoTaskIntent);
                break;
            case R.id.main_begin_inventory_layout:
                Intent inventoryIntent = new Intent();
                inventoryIntent.setClass(MainActivity.this, TaskListActivity.class);
                startActivity(inventoryIntent);
                break;
            case R.id.main_settings_layout:
                Intent deviceSetIntent = new Intent();
                deviceSetIntent.setClass(MainActivity.this, DeviceSetActivity.class);
                startActivity(deviceSetIntent);
                break;
            case R.id.main_logout_layout:
                userInfo = null;
                StmApplication.getInstance().setUserInfo(null);
                userTxt.setText("登录");
                logoutLayout.setVisibility(View.GONE);
                logoutLine.setVisibility(View.GONE);
                StmApplication.getInstance().showToastShort("退出成功");
                break;
        }
    }

    private void showExitDialog() {
        int dialog_width = (int) (ViewUtil.getScreenWidth(this) * 4 / 5.0);
        final CommonAlertDialog dialog = new CommonAlertDialog(MainActivity.this);
        dialog.setViewParams(new LinearLayout.LayoutParams(dialog_width, -2));
        dialog.show();
        dialog.setText("提示", "确定退出" + getResources().getString(R.string.app_name) + "吗？", "确定");
        dialog.setSureListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                sApp.setShowBackground(false);
                MainActivity.this.finish();
            }
        });
    }

    private void getVersionIno() {
        if (NetworkUtil.isNetworkAvailable(MainActivity.this)) {
            loadingDialog.show();
            HttpService.getInstance().queryAppVersionApp(version_cb);
        } else {
            StmApplication.getInstance().showToastShort(getString(R.string.net_settings));
        }
    }

    private void showVersionDialog() {
        String appName = getResources().getString(R.string.app_name);
        String content = "检测到"+ appName + "新版本v" + versionMap.get("vesion");
        int dialog_width = (int) (ViewUtil.getScreenWidth(this) * 4 / 5.0);
        final CommonAlertDialog dialog = new CommonAlertDialog(MainActivity.this);
        dialog.setViewParams(new LinearLayout.LayoutParams(dialog_width, -2));
        dialog.show();
        final String forceStr = versionMap.get("forceflag");
        if ("0".equals(forceStr)) { // 强制升级
            dialog.setText("提示", content, "现在升级", "退出程序");
        } else {
            dialog.setText("提示", content, "现在升级", "暂不升级");
        }
        dialog.setSureListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                // 权限检查
                int perRes = ActivityCompat.checkSelfPermission(MainActivity.this, "android.permission.READ_EXTERNAL_STORAGE");
                int perRes2 = ActivityCompat.checkSelfPermission(MainActivity.this, "android.permission.WRITE_EXTERNAL_STORAGE");
                if (perRes == PackageManager.PERMISSION_DENIED || perRes2 == PackageManager.PERMISSION_DENIED) {
                    sApp.setShowBackground(false);
//                    ActivityCompat.requestPermissions(MainActivity.this, new String[] {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"}, IConstant.PERMISSION_REQUEST_SELECT_PHOTO);
                } else {
                    //
                }
            }
        });
        dialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                if ("0".equals(forceStr)) {
                    sApp.setShowBackground(false);
                    MainActivity.this.finish();
                }
            }
        });
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            showExitDialog();
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    private final RequestCallback<CommonMapJson> version_cb = new RequestCallback<CommonMapJson>(CommonMapJson.class) {
        @Override
        public void onSuccess(CommonMapJson responseInfo) {
            if (responseInfo.isSucess()) {
                versionMap = responseInfo.getRspData();
                if (versionMap!= null && versionMap.containsKey("versionMap") && VersionUtil.needUpdate(versionMap.get("vesion"))) {
                    showVersionDialog();
                }
            }
        }

        @Override
        public void onFailure(HttpException error, String msg) {
        }
    };

}
