package com.example.sleep;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.sleep.database.dao.DatabaseManager;

import java.io.File;
import java.util.List;

public class Share extends Fragment {
    private static final int RESULT_LOAD_IMAGE = 111;
    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 222;

    private ImageView eventPostImage;

    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 3;

    private static final int REQUEST_IMAGE_CAPTURE = 1;

    private Bitmap imageBitmap;
    private RecyclerView eventRl;
    private MyAdapter adapter;
    private List<ItemModel> dataList;

    // 在Fragment的onCreateView方法中初始化RecyclerView并设置适配器
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.i("11111", "onCreateView");
        View view = inflater.inflate(R.layout.event_content, container, false);
        eventRl = view.findViewById(R.id.rl);
        eventPostImage = view.findViewById(R.id.event_image);

        eventPostImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 当点击事件被触发时，显示底部对话框
                if (true) {  // 在这里应该有条件检查
                    showDialog();
                }
            }
        });

        initData();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i("11111", "onResume");
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
        String retrievedUserName = sharedPreferences.getString("UserNameKey", "DefaultUserName");
        loadData(retrievedUserName);
        adapter.setDataList(dataList);
        adapter.notifyDataSetChanged();
    }

    private void initData() {
        eventRl.setLayoutManager(new LinearLayoutManager(getActivity()));
        /*SharedPreferences sharedPreferences = getActivity().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
        String retrievedUserName = sharedPreferences.getString("UserNameKey", "DefaultUserName");
        loadData(retrievedUserName);  // 初始化数据*/

        adapter = new MyAdapter(getActivity(), dataList);
        eventRl.setAdapter(adapter);
    }

    private void loadData(String username) {
        DatabaseManager manager = new DatabaseManager(getActivity());
        manager.open();
        dataList = manager.getUserNameEvent(username);
    }

    private void showDialog() {
        // 显示底部对话框
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(getActivity());
        View bottomSheetView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_bottom_sheet_dialog, null);
        bottomSheetDialog.setContentView(bottomSheetView);

        bottomSheetView.findViewById(R.id.btn_take_photo).setOnClickListener(v -> {
            // 处理拍摄按钮点击事件
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                // 请求相机权限
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA);
            } else {
                openCamera();
            }

            bottomSheetDialog.dismiss();
        });

        bottomSheetView.findViewById(R.id.btn_choose_from_gallery).setOnClickListener(v -> {
            // 处理从相册中选择按钮点击事件
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                // 请求读取外部存储权限
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            } else {
                // 权限已经授予，进入图片选择流程
                dispatchChoosePictureIntent();
            }

            bottomSheetDialog.dismiss();
        });

        bottomSheetView.findViewById(R.id.btn_cancel).setOnClickListener(v -> {
            bottomSheetDialog.dismiss();  // 关闭对话框
        });

        bottomSheetDialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CAMERA: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 用户授予了相机权限，可以拍照
                    openCamera();
                } else {
                    // 用户拒绝了相机权限
                }
            }
            case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 用户授予了读取外部存储权限
                    dispatchChoosePictureIntent();
                } else {
                    // 用户拒绝了读取外部存储权限
                }
            }
        }
    }

    private void dispatchChoosePictureIntent() {
        if (true) {
            // 从相册中选择图片
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, RESULT_LOAD_IMAGE);
            return;
        }

        // 创建拍照和选择图片的Intent
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Intent pickPictureIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, pickPictureIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "选择图片");

        if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
            // 创建拍照所需的文件
            File photoFile = null;
            if (photoFile != null) {
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{takePictureIntent});
            }
        }
    }

    private void openCamera() {
        // 打开相机应用拍照
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_IMAGE_CAPTURE) {
                // 处理相机返回的数据
                Bundle extras = data.getExtras();
                imageBitmap = (Bitmap) extras.get("data");

                // 启动新Activity并传递拍摄的图片
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putParcelable("bitmapImage", imageBitmap);
                intent.putExtra("isPhoto", false);
                intent.putExtras(bundle);
                intent.setClass(getActivity(), EditScreen.class);
                startActivity(intent);
            } else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
                Uri selectedImageUri = data.getData();

                // 处理URI获取图片路径或者直接存储URI
                // ...

                // 如果你想获取图片的实际文件路径，可以如此操作
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getActivity().getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();

                    // 将图片路径保存到数据库
                    // saveImagePathToDatabase(picturePath);
                    // 使用 imageBitmap ...
                    Intent intent = new Intent();
                    intent.putExtra("bitmapImageString", picturePath);
                    intent.putExtra("isPhoto", true);
                    intent.setClass(getActivity(), EditScreen.class);
                    startActivity(intent);
                }

                // 或者，可以保存URI.toString()到数据库
                // saveImageUriToDatabase(selectedImageUri.toString());
            }
        }
    }
}