package chaoran.business.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import androidx.core.content.FileProvider;

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

/**
 * 相机辅助类 - 通过JavaScript接口直接调用相机
 */
public class CameraHelper {
    
    private static final int REQUEST_CODE_CAMERA_DIRECT = 1003;
    private Activity activity;
    private WebView webView;
    private Uri cameraPhotoUri;
    private String currentPhotoPath;

    public CameraHelper(Activity activity, WebView webView) {
        this.activity = activity;
        this.webView = webView;
    }

    /**
     * 直接打开相机拍照
     */
    @JavascriptInterface
    public void openCamera() {
        activity.runOnUiThread(() -> {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (cameraIntent.resolveActivity(activity.getPackageManager()) != null) {
                File photoFile = createImageFile();
                if (photoFile != null) {
                    currentPhotoPath = photoFile.getAbsolutePath();
                    cameraPhotoUri = FileProvider.getUriForFile(
                            activity,
                            activity.getPackageName() + ".fileprovider",
                            photoFile
                    );
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraPhotoUri);
                    cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    activity.startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA_DIRECT);
                }
            }
        });
    }

    /**
     * 创建图片文件
     */
    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) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 处理Activity结果
     */
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_CAMERA_DIRECT) {
            if (resultCode == Activity.RESULT_OK && cameraPhotoUri != null) {
                // 通知JavaScript照片已拍摄
                String jsCode = "javascript:onCameraResult('" + cameraPhotoUri.toString() + "', '" + currentPhotoPath + "')";
                webView.post(() -> webView.loadUrl(jsCode));
            } else {
                // 取消拍照
                String jsCode = "javascript:onCameraResult(null, null)";
                webView.post(() -> webView.loadUrl(jsCode));
            }
            cameraPhotoUri = null;
            currentPhotoPath = null;
            return true;
        }
        return false;
    }
}
