package cc.winboll.studio.powerbell.activities;

/**
 * @Author ZhanGSKen<zhangsken@qq.com>
 * @Date 2025/06/22 14:15
 */
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cc.winboll.studio.libaes.interfaces.IWinBoLLActivity;
import cc.winboll.studio.libaes.views.AToolbar;
import cc.winboll.studio.libappbase.GlobalApplication;
import cc.winboll.studio.powerbell.R;
import cc.winboll.studio.powerbell.activities.BackgroundPictureActivity;
import cc.winboll.studio.powerbell.activities.PixelPickerActivity;
import cc.winboll.studio.powerbell.beans.BackgroundPictureBean;
import cc.winboll.studio.powerbell.utils.BackgroundPictureUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class PixelPickerActivity extends WinBoLLActivity implements IWinBoLLActivity {

	public static final String TAG = "PixelPickerActivity";

	@Override
	public Activity getActivity() {
		return this;
	}

	@Override
	public String getTag() {
		return TAG;
	}

	private AToolbar mAToolbar;
	private ImageView imageView;
	private Bitmap originalBitmap;
	private TextView infoText;
	private ViewGroup imageContainer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pixelpicker);


        // 初始化工具栏
        mAToolbar = (AToolbar) findViewById(R.id.toolbar);
        setActionBar(mAToolbar);
        mAToolbar.setSubtitle(R.string.subtitle_activity_pixelpicker);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        mAToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });

		imageView = findViewById(R.id.imageView);
		infoText = findViewById(R.id.infoText);
		imageContainer = findViewById(R.id.imageContainer);

		// 从Intent获取图片路径并加载
		String imagePath = getIntent().getStringExtra("imagePath");
		if (imagePath != null) {
			loadImage(imagePath);
		} else {
			infoText.setText("未找到图片路径");
		}

		// 设置图片点击事件
		imageContainer.setOnTouchListener(new View.OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if (event.getAction() == MotionEvent.ACTION_DOWN && originalBitmap != null) {
						// 计算点击位置在图片上的实际坐标
						float touchX = event.getX();
						float touchY = event.getY();

						int pixelX = -1, pixelY = -1;
						try {
							// 获取图片在容器中的实际位置和尺寸
							int[] imageLocation = new int[2];
							imageView.getLocationInWindow(imageLocation);
							int imageWidth = imageView.getWidth();
							int imageHeight = imageView.getHeight();

							// 计算缩放比例
							float scaleX = (float) originalBitmap.getWidth() / imageWidth;
							float scaleY = (float) originalBitmap.getHeight() / imageHeight;

							// 调整触摸坐标到图片坐标系
							float adjustedX = touchX - imageLocation[0];
							float adjustedY = touchY - imageLocation[1];

							// 检查是否在图片范围内
							if (adjustedX >= 0 && adjustedX <= imageWidth && adjustedY >= 0 && adjustedY <= imageHeight) {
								// 计算实际像素坐标
								pixelX = (int) (adjustedX * scaleX);
								pixelY = (int) (adjustedY * scaleY);

								// 再次检查像素坐标是否在有效范围内
								if (pixelX >= 0 && pixelX < originalBitmap.getWidth() && 
									pixelY >= 0 && pixelY < originalBitmap.getHeight()) {
									int pixelColor = originalBitmap.getPixel(pixelX, pixelY);
									showPixelDialog(pixelColor, pixelX, pixelY);
								} else {
									Toast.makeText(PixelPickerActivity.this, "像素坐标超出范围", Toast.LENGTH_SHORT).show();
								}
							} else {
								Toast.makeText(PixelPickerActivity.this, "点击位置超出图片显示范围", Toast.LENGTH_SHORT).show();
							}
						} catch (Exception e) {
							e.printStackTrace();
							Toast.makeText(PixelPickerActivity.this, "计算像素位置失败", Toast.LENGTH_SHORT).show();
						}
					}
					return true;
				}
			});
	}

	/**
	 * 加载图片
	 */
	private void loadImage(String imagePath) {
		try {
			File file = new File(imagePath);
			if (file.exists()) {
				// 解码图片
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 1; // 加载原图
				originalBitmap = BitmapFactory.decodeStream(new FileInputStream(file), null, options);

				if (originalBitmap != null) {
					imageView.setImageBitmap(originalBitmap);
					infoText.setText("图片已加载，点击获取像素值");
				} else {
					infoText.setText("图片加载失败");
				}
			} else {
				infoText.setText("图片文件不存在");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			infoText.setText("图片文件未找到");
		}
	}

	/**
	 * 显示像素对话框
	 */
	private void showPixelDialog(final int pixelColor, int x, int y) {
		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.dialog_pixel);
		dialog.setCancelable(true);

		// 设置像素颜色视图背景
		TextView colorView = dialog.findViewById(R.id.pixelColorView);
		colorView.setBackgroundColor(pixelColor);

		// 显示颜色信息
		TextView infoText = dialog.findViewById(R.id.colorInfoText);
		String colorInfo = String.format(
			"RGB: (%d, %d, %d)\n" +
			"ARGB: #%08X\n" +
			"实际像素位置: (%d, %d)",
			Color.red(pixelColor),
			Color.green(pixelColor),
			Color.blue(pixelColor),
			pixelColor,
			x, y);
		infoText.setText(colorInfo);

		// 设置确定按钮点击事件
		Button confirmButton = dialog.findViewById(R.id.confirmButton);
		confirmButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
					// 可以在这里添加确定后的回调逻辑
					BackgroundPictureUtils utils = BackgroundPictureUtils.getInstance(PixelPickerActivity.this);
					BackgroundPictureBean bean = utils.getBackgroundPictureBean();
					bean.setPixelColor(pixelColor);
					utils.saveData();
					Toast.makeText(PixelPickerActivity.this, "已记录像素值", Toast.LENGTH_SHORT).show();
					setBackgroundColor();
				}
			});

		dialog.show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 回收Bitmap资源
		if (originalBitmap != null && !originalBitmap.isRecycled()) {
			originalBitmap.recycle();
			originalBitmap = null;
		}
	}


	void setBackgroundColor() {
		BackgroundPictureUtils utils = BackgroundPictureUtils.getInstance(PixelPickerActivity.this);
		BackgroundPictureBean bean = utils.getBackgroundPictureBean();
		int nPixelColor = bean.getPixelColor();
		RelativeLayout mainLayout = findViewById(R.id.activitypixelpickerRelativeLayout1);
		mainLayout.setBackgroundColor(nPixelColor);
	}

	@Override
	protected void onResume() {
		super.onResume();
		setBackgroundColor();
	}
	

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
			Intent intent = new Intent();
            intent.setClass(this, BackgroundPictureActivity.class);
            startActivity(intent);
            //GlobalApplication.getWinBoLLActivityManager().startWinBoLLActivity(getApplicationContext(), );
            return true;
        }
        // 在switch语句中处理每个ID，并在处理完后返回true，未处理的情况返回false。
        return super.onOptionsItemSelected(item);
    }

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		Intent intent = new Intent();
		intent.setClass(this, BackgroundPictureActivity.class);
		startActivity(intent);
		//GlobalApplication.getWinBoLLActivityManager().startWinBoLLActivity(getApplicationContext(), BackgroundPictureActivity.class);
	}
}


	
