package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.DataBase.DatabaseHelper;
import com.example.myapplication.Tool.RetrofitClient;
import com.example.myapplication.Tool.ShowError;
import com.example.myapplication.api.AuthApi;
import com.example.myapplication.api.UserApi;
import com.example.myapplication.model.ApiResponse;
import com.example.myapplication.model.ChangePasswordRequest;
import com.example.myapplication.model.LoginEntity;
import com.example.myapplication.model.LoginRequest;
import com.example.myapplication.model.PageResult;
import com.example.myapplication.model.UserInfo;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;


public class LoginActivity extends AppCompatActivity {
    private EditText etUsername, etPassword;
    private CheckBox cbRemember;
    private final Handler mainHandler = new Handler(Looper.getMainLooper());
    private final ExecutorService executor = Executors.newFixedThreadPool(7);

    private Button btnLogin;

    private DatabaseHelper dbHelper;
    private SharedPreferences sharedPreferences;
    private final String AUTH_TOKEN_KEY = "auth_token";
    private static final String  Name = "name";
    private static final String  Userid = "userid";
    private static final String BASE_URL = "http://pms.dtyx.net:9158/";
    private String authToken = "";
    private static final String PREFS_NAME = "LoginPrefs";
    private static final String PREF_USERNAME = "username";
    private static final String PREF_PASSWORD = "password";
    private static final String PREF_REMEMBER = "remember";
    ShowError errorShower = new ShowError(this);



    @SuppressLint("SuspiciousIndentation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        dbHelper = new DatabaseHelper(this);
        // 使用 Context.MODE_PRIVATE 替代 MODE_PRIVATE 常量
        sharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

        initViews();
        setupListeners();
        loadSavedPreferences();
    }

    private void initViews() {
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        cbRemember = findViewById(R.id.cbRemember);
        btnLogin = findViewById(R.id.btnLogin);
    }

    private void setupListeners() {
        btnLogin.setOnClickListener(v -> attemptLogin());
    }
    private boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) return false;

        NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
        return capabilities != null &&
                (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                        capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
                        capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET));
    }
    private void loadSavedPreferences() {
        boolean remember = sharedPreferences.getBoolean(PREF_REMEMBER, false);
        if (remember) {
            String savedUsername = sharedPreferences.getString(PREF_USERNAME, "");
            String savedPassword = sharedPreferences.getString(PREF_PASSWORD, "");

            etUsername.setText(savedUsername);
            etPassword.setText(savedPassword);
            cbRemember.setChecked(true);
        }
    }

    private void attemptLogin() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(LoginActivity.this, "请填写所有字段", Toast.LENGTH_SHORT).show();
            return;
        }

        // 在后台线程执行数据库操作
        // 先进行认证
        if(isNetworkAvailable())
        authenticateUser(username, password);
        else continueLoginProcess(username,password);
    }
    private void authenticateUser(String username, String password) {

        executor.execute(() -> {
            try {
                // 加密密码
                String encryptedPassword2 = encryptPassword(username, password);


                // 创建认证请求体
                LoginRequest loginRequest = new LoginRequest(username, encryptedPassword2);
                String token = sharedPreferences.getString(AUTH_TOKEN_KEY, "");
                // 初始化Retrofit
                Retrofit retrofit = RetrofitClient.getClient(token);

                // 创建认证API服务
                AuthApi authApi = retrofit.create(AuthApi.class);

                // 执行认证请求
                Call<ApiResponse<LoginEntity>> call = authApi.login(loginRequest);
                Response<ApiResponse<LoginEntity>> response = call.execute();

                if (response.isSuccessful() && response.body() != null) {

                    if (response.body().getCode() == 500200) {
                        //修改密码操作
                        runOnUiThread(() -> showChangePasswordDialog(username));
                    } else if (response.body().getCode() == 200) {

                        authToken = response.body().getData().getTokenValue();
                        Log.e("令牌:",authToken);
                        sharedPreferences.edit().putString(AUTH_TOKEN_KEY, authToken).apply();
                        Retrofit retrofit2 = RetrofitClient.getClient(authToken);
                        // 创建UserApi服务
                        UserApi userApi = retrofit2.create(UserApi.class);

                        // 执行查询请求，只根据account查询
                        Call<PageResult<UserInfo>> userCall = userApi.getUserList(
                                authToken,  // 注意token前缀，根据你的API要求调整
                                username,  // account参数
                                null,      // deptId
                                null,      // mobile
                                null,      // name
                                null,      // userCode
                                null,      // userStatus
                                null       // userType
                        );

                        try {

                            Response<PageResult<UserInfo>> userResponse = userCall.execute();
                            if (userResponse.isSuccessful() && userResponse.body() != null
                                    && userResponse.body().getCode() == 200
                                    && !userResponse.body().getRows().isEmpty()) {
                                // 获取第一个匹配用户的name
                                String name = userResponse.body().getRows().get(0).getName();
                                String userid=userResponse.body().getRows().get(0).getUserId();
                                sharedPreferences.edit().putString(Name, name).apply();
                                sharedPreferences.edit().putString(Userid, userid).apply();
                                executor.execute(()-> {

                                    continueLoginProcess(username, password);
                                });

                            } else {
                                // 查询失败或没有结果，使用username作为name
                                errorShower.showErrorDialog("查询姓名失败" , userResponse.body().getMsg());

                                sharedPreferences.edit().putString(Name, "").apply();
                                executor.execute(()-> {

                                    continueLoginProcess(username, password);
                                });
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            // 发生异常，使用username作为name
                            errorShower.showErrorDialog("出现异常:", e.getMessage());
                            executor.execute(()-> {

                                continueLoginProcess(username, password);
                            });
                        }


                    }
                    else {
                       showToast(password+"密码出错"+response.body().toString());
                    }
                } else {
                    runOnUiThread(() -> {
                        String errorMsg = "认证失败: ";
                        if (response.errorBody() != null) {
                            try {
                                errorMsg += response.errorBody().string();
                            } catch (IOException e) {
                                errorMsg += "无法读取错误详情";
                            }
                        }
                        showToast(errorMsg);
                    });
                }
            } catch (Exception e) {
              showToast("认证出错:"+e.getMessage());
            }
        });
    }


    // 封装 Toast 显示
    private void showToast(String message) {
        mainHandler.post(() -> Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show());
    }

    private void showChangePasswordDialog(String username) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请修改密码");

        View view = getLayoutInflater().inflate(R.layout.dialog_change_password, null);
        EditText etOldPassword = view.findViewById(R.id.etOldPassword);
        EditText etNewPassword = view.findViewById(R.id.etNewPassword);
        EditText etConfirmPassword = view.findViewById(R.id.etConfirmPassword);

        builder.setView(view);
        builder.setPositiveButton("确认", (dialog, which) -> {
            String oldPassword = etOldPassword.getText().toString().trim();
            String newPassword = etNewPassword.getText().toString().trim();
            String confirmPassword = etConfirmPassword.getText().toString().trim();

            if (newPassword.equals(confirmPassword)) {
                changePassword(username, oldPassword, newPassword);
            } else {
                Toast.makeText(this, "新密码与确认密码不匹配", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.setCancelable(false);
        builder.show();
    }

    private void changePassword(String username, String oldPassword, String newPassword) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(() -> {
            try {
                // 加密旧密码和新密码
                String encryptedOldPassword = encryptPassword(username, oldPassword);
                String encryptedNewPassword = encryptPassword(username, newPassword);

                // 创建修改密码请求体
                ChangePasswordRequest request = new ChangePasswordRequest(
                        username,
                        encryptedNewPassword,
                        encryptedOldPassword
                );

                // 获取token
                String token = sharedPreferences.getString(AUTH_TOKEN_KEY, "");

                // 初始化Retrofit
               Retrofit retrofit = RetrofitClient.getClient(token);
                // 创建API服务
                AuthApi authApi = retrofit.create(AuthApi.class);
                // 执行修改密码请求
                Call<ApiResponse<Void>> call = authApi.modifyPassword(request);
                Response<ApiResponse<Void>> response = call.execute();
                runOnUiThread(() -> {
                    if (response.isSuccessful() && response.body() != null) {
                        if (response.body().isSuccess()) {
                            Toast.makeText(LoginActivity.this, "密码修改成功，请重新登录", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(LoginActivity.this, "密码修改失败: " + response.body().toString(), Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        String errorMsg = "修改密码失败: ";
                        if (response.errorBody() != null) {
                            try {
                                errorMsg += response.errorBody().string();
                            } catch (IOException e) {
                                errorMsg += "无法读取错误详情";
                            }
                        }
                        Toast.makeText(LoginActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (Exception e) {
                runOnUiThread(() ->
                        Toast.makeText(LoginActivity.this, "修改密码出错: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }
        });
    }

    // 新增修改密码请求体

    private void continueLoginProcess(String username, String password) {
        // 在后台线程执行数据库操作
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(() -> {
            try {

                // 保存登录信息
                saveLoginPreferences(username, password);

                // 检查用户是否存在
                boolean userExists = dbHelper.userExists(username);

                runOnUiThread(() -> {
                    if (userExists) {
                        // 用户存在，验证密码
                        if (dbHelper.checkUser(username, password)) {
                            handleLoginSuccess(username,password);
                        } else {
                            Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        // 用户不存在，自动注册
                        if (dbHelper.addUser(username, password)) {
                            handleLoginSuccess(username,password);
                        } else {
                            Toast.makeText(LoginActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            } catch (Exception e) {
                runOnUiThread(() ->
                        Toast.makeText(LoginActivity.this, "登录出错: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }
        });
    }

    private String encryptPassword(String username, String password) {
        try {
            // 1. 对账号做MD5计算
            String md5Hash = md5(username);

            // 2. 取8-24位作为密钥
            String key = md5Hash.substring(8, 24); // 8-24位（索引从0开始）
            Log.e("key:",key);
            // 3. AES加密
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // PKCS5Padding等同于PKCS7Padding在Java中
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);

            byte[] encryptedBytes = cipher.doFinal(password.getBytes());
            return Base64.encodeToString(encryptedBytes, Base64.DEFAULT).trim();
        } catch (Exception e) {
            e.printStackTrace();
            showToast("加密密码错误:"+e.getMessage());
            return "";
        }
    }

    private String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());

            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }



    private void saveLoginPreferences(String username, String password) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (cbRemember.isChecked()) {
            editor.putString(PREF_USERNAME, username);
            editor.putString(PREF_PASSWORD, password);
            editor.putBoolean(PREF_REMEMBER, true);
        } else {
            editor.clear();
        }
        editor.apply();
    }

    private void handleLoginSuccess(String username, String password) {
//        todo 切换时保存个人项目信息
//        dbHelper.updateUserProject(username, projectId, projectName);
        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.putExtra("username", username);
        intent.putExtra("password",password);
        startActivity(intent);
        finish();
    }

}