package chaoran.business.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Base64;
import android.util.Log;
import android.webkit.ValueCallback;
import android.widget.Toast;

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

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 文件选择和相机拍照辅助类
 */
public class FileChooserHelper {

    private static final String TAG = "FileChooserHelper";
    private static final int REQUEST_CODE_CAMERA = 1001;
    private static final int REQUEST_CODE_FILE_CHOOSER = 1002;
    private static final int REQUEST_CODE_PERMISSION_CAMERA = 2001;
    private static final int REQUEST_CODE_PERMISSION_STORAGE = 2002;

    private Activity activity;
    private ValueCallback<Uri[]> filePathCallback;
    private Uri cameraPhotoUri;
    private boolean pendingAcceptImage = false;
    private boolean pendingAcceptCamera = false;
    private boolean pendingCameraOnly = false;

    public FileChooserHelper(Activity activity) {
        this.activity = activity;
    }

    /**
     * 打开文件选择器（支持相机和图片选择）
     */
    public void openFileChooser(ValueCallback<Uri[]> callback, boolean acceptImage, boolean acceptCamera) {
        openFileChooser(callback, acceptImage, acceptCamera, false);
    }

    /**
     * 打开文件选择器（支持相机和图片选择）
     * @param callback 文件选择回调
     * @param acceptImage 是否只接受图片
     * @param acceptCamera 是否支持相机
     * @param cameraOnly 是否仅使用相机（不显示文件选择器）
     */
    public void openFileChooser(ValueCallback<Uri[]> callback, boolean acceptImage, boolean acceptCamera, boolean cameraOnly) {
        this.filePathCallback = callback;
        this.pendingAcceptImage = acceptImage;
        this.pendingAcceptCamera = acceptCamera;
        this.pendingCameraOnly = cameraOnly;

        // 检查权限
        if (acceptCamera && !checkCameraPermission()) {
            requestCameraPermission();
            return;
        }

        if (!cameraOnly && !checkStoragePermission()) {
            requestStoragePermission();
            return;
        }

        // 创建选择器
        showFileChooser();
    }

    /**
     * 显示文件选择器
     */
    private void showFileChooser() {
        Intent chooserIntent = createChooserIntent(pendingAcceptImage, pendingAcceptCamera);
        if (chooserIntent != null) {
            try {
                activity.startActivityForResult(chooserIntent, REQUEST_CODE_FILE_CHOOSER);
            } catch (Exception e) {
                Log.e(TAG, "打开文件选择器失败", e);
                Toast.makeText(activity, "打开文件选择器失败", Toast.LENGTH_SHORT).show();
                if (filePathCallback != null) {
                    filePathCallback.onReceiveValue(null);
                    filePathCallback = null;
                }
            }
        }
    }

    /**
     * 创建选择器Intent
     */
    private Intent createChooserIntent(boolean acceptImage, boolean acceptCamera) {
        // 如果只需要相机，直接返回相机Intent
        if (acceptCamera && pendingCameraOnly) {
            return createCameraIntent();
        }

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        
        if (acceptImage) {
            contentSelectionIntent.setType("image/*");
        } else {
            contentSelectionIntent.setType("*/*");
        }

        Intent[] intentArray;
        if (acceptCamera) {
            Intent cameraIntent = createCameraIntent();
            if (cameraIntent != null) {
                intentArray = new Intent[]{cameraIntent};
            } else {
                intentArray = new Intent[0];
            }
        } else {
            intentArray = new Intent[0];
        }

        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "选择文件");

        return chooserIntent;
    }

    /**
     * 创建相机Intent
     */
    private Intent createCameraIntent() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(activity.getPackageManager()) != null) {
            File photoFile = createImageFile();
            if (photoFile != null) {
                cameraPhotoUri = FileProvider.getUriForFile(
                        activity,
                        activity.getPackageName() + ".fileprovider",
                        photoFile
                );
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraPhotoUri);
                cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                return cameraIntent;
            }
        }
        return null;
    }

    /**
     * 创建图片文件
     */
    private File createImageFile() {
        try {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";
            File storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            if (storageDir != null && !storageDir.exists()) {
                storageDir.mkdirs();
            }
            return File.createTempFile(imageFileName, ".jpg", storageDir);
        } catch (IOException e) {
            Log.e(TAG, "创建图片文件失败", e);
            return null;
        }
    }

    /**
     * 处理Activity结果
     */
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_FILE_CHOOSER) {
            if (filePathCallback == null) {
                return true;
            }

            Uri[] results = null;
            if (resultCode == Activity.RESULT_OK) {
                if (data != null && data.getData() != null) {
                    // 从文件选择器选择的文件
                    results = new Uri[]{data.getData()};
                } else if (cameraPhotoUri != null) {
                    // 从相机拍摄的照片
                    results = new Uri[]{cameraPhotoUri};
                }
            }

            filePathCallback.onReceiveValue(results);
            filePathCallback = null;
            cameraPhotoUri = null;
            return true;
        }
        return false;
    }

    /**
     * 处理权限请求结果
     */
    public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_CODE_PERMISSION_CAMERA) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(activity, "相机权限已授予", Toast.LENGTH_SHORT).show();
                // 权限授予后，检查存储权限
                if (!checkStoragePermission()) {
                    requestStoragePermission();
                } else {
                    // 权限都已授予，重新打开文件选择器
                    showFileChooser();
                }
            } else {
                Toast.makeText(activity, "相机权限被拒绝", Toast.LENGTH_SHORT).show();
                if (filePathCallback != null) {
                    filePathCallback.onReceiveValue(null);
                    filePathCallback = null;
                }
            }
            return true;
        } else if (requestCode == REQUEST_CODE_PERMISSION_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(activity, "存储权限已授予", Toast.LENGTH_SHORT).show();
                // 权限授予后，重新打开文件选择器
                showFileChooser();
            } else {
                Toast.makeText(activity, "存储权限被拒绝", Toast.LENGTH_SHORT).show();
                if (filePathCallback != null) {
                    filePathCallback.onReceiveValue(null);
                    filePathCallback = null;
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 检查相机权限
     */
    private boolean checkCameraPermission() {
        return ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 请求相机权限
     */
    private void requestCameraPermission() {
        ActivityCompat.requestPermissions(activity,
                new String[]{Manifest.permission.CAMERA},
                REQUEST_CODE_PERMISSION_CAMERA);
    }

    /**
     * 检查存储权限
     * Android 10+ 使用分区存储，不需要READ_EXTERNAL_STORAGE权限来访问通过文件选择器选择的文件
     */
    private boolean checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= 33) { // Android 13 (TIRAMISU)
            // Android 13+ 使用新的媒体权限
            return ContextCompat.checkSelfPermission(activity, "android.permission.READ_MEDIA_IMAGES")
                    == PackageManager.PERMISSION_GRANTED;
        } else if (Build.VERSION.SDK_INT >= 29) { // Android 10 (Q)
            // Android 10-12 使用分区存储，通过文件选择器不需要权限
            return true;
        } else {
            // Android 9 需要存储权限
            return ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED;
        }
    }

    /**
     * 请求存储权限
     */
    private void requestStoragePermission() {
        if (Build.VERSION.SDK_INT >= 33) { // Android 13 (TIRAMISU)
            // Android 13+ 请求新的媒体权限
            ActivityCompat.requestPermissions(activity,
                    new String[]{"android.permission.READ_MEDIA_IMAGES"},
                    REQUEST_CODE_PERMISSION_STORAGE);
        } else if (Build.VERSION.SDK_INT >= 29) { // Android 10 (Q)
            // Android 10-12 不需要请求权限
            Toast.makeText(activity, "存储权限已授予", Toast.LENGTH_SHORT).show();
        } else {
            // Android 9 请求存储权限
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_CODE_PERMISSION_STORAGE);
        }
    }

    /**
     * 获取文件名
     */
    public static String getFileName(Context context, Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (nameIndex >= 0) {
                        result = cursor.getString(nameIndex);
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "获取文件名失败", e);
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf('/');
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }

    /**
     * 将文件转换为Base64字符串
     */
    public static String fileToBase64(Context context, Uri uri) {
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            if (inputStream == null) {
                return null;
            }

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();

            byte[] fileBytes = byteArrayOutputStream.toByteArray();
            return Base64.encodeToString(fileBytes, Base64.NO_WRAP);
        } catch (Exception e) {
            Log.e(TAG, "文件转Base64失败", e);
            return null;
        }
    }

    /**
     * 获取文件大小
     */
    public static long getFileSize(Context context, Uri uri) {
        try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
                if (sizeIndex >= 0) {
                    return cursor.getLong(sizeIndex);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取文件大小失败", e);
        }
        return 0;
    }
}
