package com.example.tyre;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.example.tyre.databinding.ActivityMainBinding;
import com.example.tyre.entity.AjaxResult;
import com.example.tyre.util.CommonDialog;
import com.example.tyre.util.MyUrl;
import com.example.tyre.util.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONObject;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_CODE = 1001;
    private static final int REQUEST_PERMISSIONS = 100;
    EditText loginName;
    EditText loginPass;
    Button loginLog;
    CheckBox cbRemember;
    TextView version;
    private ActivityMainBinding binding;
    // 声明进度条变量
    private ProgressDialog progressDialog;
    private BroadcastReceiver downloadReceiver;
    private long downloadId;
    private DownloadManager downloadManager;
    private String newVersionName;
    private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

            if (downloadId == id) {
                SharedPreferencesUtils.putstring("local_app_version", newVersionName);
                runOnUiThread(() -> {
                    // 这里更新界面上的 TextView
                    version.setText("当前版本: " + newVersionName); // ⭐ 修改：直接显示新版本
                });
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(id);

                Cursor cursor = downloadManager.query(query);
                if (cursor.moveToFirst()) {
                    int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));

                    if (status == DownloadManager.STATUS_SUCCESSFUL) {
                        String localUri =
                                cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        installApk(Uri.parse(localUri).getPath());
                    } else {
                        int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
                        Toast.makeText(context, "下载失败，错误码: " + reason, Toast.LENGTH_SHORT).show();
                    }
                }
                cursor.close();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        bindViews();
        setupClickListeners();
        initRememberInfo();
        checkPermissionsAndUpdate();
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    private void bindViews() {
        loginName = binding.loginName;
        loginPass = binding.loginPass;
        loginLog = binding.loginLog;
        cbRemember = binding.checkboxRemember;
        version = binding.version;
    }

    private void setupClickListeners() {
        binding.loginLog.setOnClickListener(v -> {
            String name = loginName.getText().toString().trim();
            String pass = loginPass.getText().toString().trim();
            boolean isRemember = cbRemember.isChecked();

            if (name.isEmpty() || pass.isEmpty()) {
                Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            showLoadingDialog();
            login(name, pass, isRemember);
        });
    }

    /**
     * 检查权限并开始版本更新检查
     */
    private void checkPermissionsAndUpdate() {
        // Android 6.0+ 动态申请存储权限（用于下载APK）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        PERMISSION_REQUEST_CODE);
            } else {
                // 权限已获取，开始检查更新
                checkAppUpdate();
            }
        } else {
            // 版本低于 6.0，直接检查更新
            checkAppUpdate();
        }
    }

    /**
     * 初始化“记住密码”的数据回显
     */
    private void initRememberInfo() {
        // 假设你在 SharedPreferencesUtils 中保存的 key 是 "user" 和 "password"
        String savedUser = SharedPreferencesUtils.getstring("user", "");
        String savedPass = SharedPreferencesUtils.getstring("password", "");

        // 如果用户名不为空，说明之前勾选过，则填充数据并勾选CheckBox
        if (savedUser != null && !savedUser.isEmpty()) {
            loginName.setText(savedUser);
            loginPass.setText(savedPass);
            cbRemember.setChecked(true);
        } else {
            cbRemember.setChecked(false);
        }
    }

    /**
     * 核心逻辑：检查更新
     */
    private void checkAppUpdate() {
        // 1. 获取本地版本号 (从 AndroidManifest.xml 读取)
        String localVersionName = getVersionName();
        Log.d("Version", "本地版本: " + localVersionName);
        // 2. 请求服务器接口获取最新版本
        // 假设接口返回格式: { "code": "0", "data": { "versionCode": 2, "apkUrl": "..." } }
        OkGo.<String>post(MyUrl.url + "/system/package/checkUpdate") // 替换为你实际的检查更新接口地址
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        hideLoadingDialog();
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            String code = jsonObject.getString("code");
                            if ("0".equals(code)) {
                                JSONObject data = jsonObject.getJSONObject("data");
//                                // 获取服务器版本号 (String)
                                String serverVersionName = data.getString("version");
                                String apkUrl = data.getString("fileName");
                                int compareResult = compareVersion(serverVersionName, localVersionName);
                                runOnUiThread(() -> {
                                    version.setText("当前版本: " + localVersionName + " | 最新版本: " + serverVersionName);
                                });
//                                // 3. 对比版本号
//                                // 如果服务器版本 > 本地版本
                                if (compareResult > 0) {
                                    showUpdateDialog(apkUrl, serverVersionName);
                                }
//                                if (compareVersion(serverVersionName, localVersionName) > 0) {
//                                    showUpdateDialog(apkUrl);
//                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 显示更新对话框
     */
    private void showUpdateDialog(String downloadUrl, String serverVersion) {
        this.newVersionName = serverVersion;
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("发现新版本 " + serverVersion)
                .setMessage("检测到最新版本，是否立即下载并安装？")
                .setPositiveButton("立即下载", (dialog, which) -> startDownload(downloadUrl))
                .setNegativeButton("取消", null).create();
        alertDialog.setOnShowListener(dialogInterface -> {
            // 修改确定按钮颜色
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                    .setTextColor(getResources().getColor(android.R.color.black));
            // 修改取消按钮颜色
            alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
                    .setTextColor(getResources().getColor(android.R.color.darker_gray));
        });
        alertDialog
                .show();
    }

    private String getVersionName() {
        // 1. 先尝试从 SP 读取（这个值是上次下载更新时存进去的最新版本）

        // 3. 如果 SP 里没有（说明是第一次安装或没更新过），读取 build.gradle 里的 versionName
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "1.0";
    }

    private int compareVersion(String v1, String v2) {
        // 如果两个版本号完全相同，直接返回0
        if (v1.equals(v2)) {
            return 0;
        }

        // 将版本号按 "." 分割成数组
        String[] v1Array = v1.split("\\.");
        String[] v2Array = v2.split("\\.");

        // 获取最大长度，确保能遍历完所有部分
        int maxLength = Math.max(v1Array.length, v2Array.length);

        for (int i = 0; i < maxLength; i++) {
            // 获取当前位的数值，如果该位置不存在（比如 1.0 对比 1.0.1），则默认为 0
            int v1Part = i < v1Array.length ? Integer.parseInt(v1Array[i]) : 0;
            int v2Part = i < v2Array.length ? Integer.parseInt(v2Array[i]) : 0;

            // 逐位比较
            if (v1Part > v2Part) {
                return 1; // v1 大
            } else if (v1Part < v2Part) {
                return -1; // v2 大
            }
        }
        return 0; // 相等
    }

    /**
     * 登录请求
     *
     * @param isRemember 是否勾选了记住密码
     */
    private void login(String name, String pass, boolean isRemember) {
        OkGo.<String>post(MyUrl.url + "/PdaLogin")
                .tag(this)
                .params("username", name)
                .params("password", pass)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        hideLoadingDialog();
                        String body = response.body();
                        Gson gson = new Gson();
                        AjaxResult ajaxResult = gson.fromJson(body, AjaxResult.class);

                        // 处理登录结果
                        handleLoginResponse(ajaxResult);

                        // --- 修改：在这里处理保存逻辑 ---
                        // 如果登录成功（假设 code 为 "0" 代表成功），且用户勾选了记住密码，则保存
                        // 如果用户没勾选，则清空保存的数据
                        if ("0".equals(ajaxResult.getCode())) {
                            if (isRemember) {
                                SharedPreferencesUtils.putstring("user", name);
                                SharedPreferencesUtils.putstring("password", pass);
                            } else {
                                // 如果没勾选，清除本地存储的密码（可选）
                                SharedPreferencesUtils.putstring("user", "");
                                SharedPreferencesUtils.putstring("password", "");
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        hideLoadingDialog();
                        Toast.makeText(MainActivity.this, "登录失败，请检查网络或重试", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void showLoadingDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("数据加载中...");
            progressDialog.setCancelable(false);
        }
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }

    private void hideLoadingDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private void handleLoginResponse(AjaxResult result) {
        switch (result.getCode()) {
            case "0":
                // 登录成功
                Toast.makeText(this, result.getMsg(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(this, HomePageActivity.class);
                startActivity(intent);
                finish();
                break;
            case "500":
                new CommonDialog(this).setMessage(result.getMsg()).show();
                break;
            default:
                new CommonDialog(this).setMessage("登录失败，请重试").show();
                break;
        }
    }

    /**
     * 开始下载 APK
     *
     * @param fileName 服务器上的文件名 (例如: "app-release.apk" 或若依数据库里的 "resourceName")
     */
    private void startDownload(String fileName) {
        // 1. 构建完整的下载 URL
        String downloadUrl = MyUrl.url + "/common/downloadApk?fileName=tyre_update.apk";

        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
        request.setTitle("APK下载");
        request.setDescription("正在下载更新...");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            request.setRequiresDeviceIdle(false);
            request.setAllowedOverMetered(true);
            request.setAllowedOverRoaming(true);
        }

        downloadId = downloadManager.enqueue(request);
        Toast.makeText(this, "开始下载...", Toast.LENGTH_SHORT).show();
    }

    private void installApk(String apkPath) {
        File file = new File(apkPath);
        if (!file.exists()) {
            Toast.makeText(this, "APK文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(file);
        }

        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        try {
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "无法安装应用: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "已获得安装未知应用权限", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "未获得安装未知应用权限，无法自动安装", Toast.LENGTH_LONG).show();
            }
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            boolean isKeyboardShown = v != null && (v instanceof EditText) && isKeyboardShowing(getCurrentFocus(), this);
            if (isKeyboardShown) {
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int)ev.getRawX(), (int)ev.getRawY())) {
                    hideSoftKeyboard(this);
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private void hideSoftKeyboard(Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
    }

    private boolean isKeyboardShowing(View v, Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        return imm.isAcceptingText();
    }
}