package com.lh.wallpaper2.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lh.wallpaper2.R;
import com.lh.wallpaper2.adapter.ImageRecyclerViewAdapter;
import com.lh.wallpaper2.file.MyItemSpace;
import com.lh.wallpaper2.room.AppDatabase;
import com.lh.wallpaper2.room.ImageEntry;
import com.lh.wallpaper2.room.ImageEntryDao;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ImportFragment extends Fragment {

    private static final int PICK_IMAGE_REQUEST_CODE = 202; // 请求码，用于标识图片选择
    private ImageView btnSelectImage; // 选择图片按钮
    private RecyclerView recyclerView; // 显示图片的 RecyclerView
    private ImageRecyclerViewAdapter adapter; // 图片适配器
    private List<String> imagePaths = new ArrayList<>(); // 图片路径列表
    private AppDatabase appDatabase; // 数据库实例
    private ImageEntryDao imageEntryDao; // 图片条目 DAO
    private LinearLayout linearLayout; // 空视图

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 加载 Fragment 的布局
        View view = inflater.inflate(R.layout.fragment_import, container, false);

        // 初始化控件
        btnSelectImage = view.findViewById(R.id.btn_select_image);
        recyclerView = view.findViewById(R.id.recycler_view);
        linearLayout = view.findViewById(R.id.empty);

        // 设置 RecyclerView 的布局管理器和适配器
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2)); // 网格布局，每行显示两个图片
        MyItemSpace itemDecoration = new MyItemSpace(30, 50, 40);
        recyclerView.addItemDecoration(itemDecoration);

        adapter = new ImageRecyclerViewAdapter(imagePaths, requireActivity());
        recyclerView.setAdapter(adapter);

        // 设置选择图片按钮的点击事件
        btnSelectImage.setOnClickListener(v -> openImagePicker());

        // 初始化数据库和 DAO
        appDatabase = AppDatabase.getInstance(requireContext());
        imageEntryDao = appDatabase.imageEntryDao();

        // 加载图片路径
        loadImagePaths();

        // 设置图片删除监听器
        adapter.setOnImageDeleteListener(imagePath -> {
            // 从数据库中删除图片记录
            new Thread(() -> {
                // 删除本地存储中的图片文件
                File imageFile = new File(imagePath);
                if (imageFile.exists() && imageFile.delete()) {  // 删除文件，成功返回 true
                    // 文件删除成功后，再删除数据库中的图片记录和更新列表
                    imageEntryDao.deleteByPath(imagePath); // 删除数据库中的图片记录
                    imagePaths.remove(imagePath); // 从列表中删除图片路径

                    requireActivity().runOnUiThread(() -> {
                        adapter.updateImagePaths(imagePaths); // 更新 RecyclerView
                        setView(!imagePaths.isEmpty()); // 更新视图
                        Toast.makeText(getContext(), "Image deleted", Toast.LENGTH_SHORT).show();
                    });
                } else {
                    // 文件删除失败时的处理
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "Failed to delete image file", Toast.LENGTH_SHORT).show();
                    });
                }
            }).start();
        });


        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        adapter.notifyDataSetChanged(); // 重新加载适配器内容
    }

    // 打开图片选择器
    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE); // 启动选择图片的活动
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST_CODE && resultCode == getActivity().RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData(); // 获取选中的图片 URI
            if (selectedImageUri != null) {
                try {
                    if (isImageSizeAcceptable(selectedImageUri)) {
                        saveImageToInternalStorage(selectedImageUri); // 保存图片到内部存储
                    } else {
                        Toast.makeText(getContext(), "图片大小超过限制", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), "无法获取图片大小: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    // 检查图片大小是否在允许范围内
    private boolean isImageSizeAcceptable(Uri uri) throws IOException {
        InputStream inputStream = requireContext().getContentResolver().openInputStream(uri);
        if (inputStream == null) {
            return false;
        }
        long fileSize = inputStream.available();
        inputStream.close();
        long maxFileSize = 10 * 1024 * 1024; // 最大 10MB
        return fileSize <= maxFileSize;
    }

    // 将选中的图片保存到内部存储
    private void saveImageToInternalStorage(Uri uri) {
        try {
            InputStream inputStream = requireContext().getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            if (bitmap == null) {
                Toast.makeText(getContext(), "无法加载图片", Toast.LENGTH_SHORT).show();
                return;
            }
            File internalStorageDir = requireContext().getFilesDir();
            File imageFile = new File(internalStorageDir, System.currentTimeMillis() + ".jpg");
            FileOutputStream outputStream = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.close();
            inputStream.close();

            String imagePath = imageFile.getAbsolutePath();
            new Thread(() -> {
                if (isImageAlreadyExists(imagePath)) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(getContext(), "该图片已经存在", Toast.LENGTH_SHORT).show());
                    imageFile.delete();
                    return;
                }
                imagePaths.add(imagePath);
                requireActivity().runOnUiThread(() -> {
                    adapter.updateImagePaths(imagePaths);
                    setView(!imagePaths.isEmpty());
                });
                imageEntryDao.insert(new ImageEntry(imagePath));
            }).start();

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "保存图片失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    // 检查图片是否已经存在
    private boolean isImageAlreadyExists(String imagePath) {
        File newImageFile = new File(imagePath);
        for (String path : imagePaths) {
            File existingFile = new File(path);
            if (filesAreIdentical(existingFile, newImageFile)) {
                return true;
            }
        }
        List<ImageEntry> imageEntries = imageEntryDao.getAllImages();
        for (ImageEntry imageEntry : imageEntries) {
            File existingFile = new File(imageEntry.getImagePath());
            if (filesAreIdentical(existingFile, newImageFile)) {
                return true;
            }
        }
        return false;
    }

    // 比较两个文件是否相同
    private boolean filesAreIdentical(File file1, File file2) {
        return file1.length() == file2.length(); // 比较文件长度
    }

    // 加载图片路径列表
    private void loadImagePaths() {
        new Thread(() -> {
            imagePaths.clear();  // 清空列表，防止重复添加
            List<ImageEntry> imageEntries = imageEntryDao.getAllImages();
            for (ImageEntry imageEntry : imageEntries) {
                imagePaths.add(imageEntry.getImagePath()); // 添加路径到列表
            }
            requireActivity().runOnUiThread(() -> {
                adapter.updateImagePaths(imagePaths);
                setView(!imagePaths.isEmpty());
            });
        }).start();
    }

    // 更新视图，切换空视图与图片视图
    private void setView(Boolean hasData) {
        if (hasData) {
            recyclerView.setVisibility(View.VISIBLE);
            linearLayout.setVisibility(View.GONE);
        } else {
            recyclerView.setVisibility(View.GONE);
            linearLayout.setVisibility(View.VISIBLE);
        }
    }
}
