package com.bonait.bnframework.modules.home.fragment.from;

import static com.bonait.bnframework.MainApplication.getContext;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.R;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.base.BaseFragment;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.Constants;
import com.bonait.bnframework.common.filepicker.PickerManager;
import com.bonait.bnframework.common.filepicker.adapter.FilePickerShowAdapter;
import com.bonait.bnframework.common.filepicker.adapter.OnFileItemClickListener;
import com.bonait.bnframework.common.filepicker.model.FileEntity;
import com.bonait.bnframework.common.filepicker.model.FileType;
import com.bonait.bnframework.common.image.utils.LocalCacheUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.fragment.SheZhifragment;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ImageSourceActivity extends BaseActivity {

    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;
    private Context context;

    @BindView(R.id.rl_file)
    RecyclerView mRecyclerView;
    @BindView(R.id.rl_yx_file)
    RecyclerView rl_yx_file;
    @BindView(R.id.baocunbendi)
    Button baocunbendi;
    @BindView(R.id.delete_all)
    Button delete_all;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imagesource);
        ButterKnife.bind(this);
        context=getContext();
        initTopBar();
        initFragment();
        FlushedImage();
    }

    private void initTopBar() {
        mTopBar.setTitle("图片资源管理");
        mTopBar.addLeftImageButton(R.mipmap.fanhui,R.id.topbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        String cacheSize = getCacheSize();
        if(!cacheSize.isEmpty()){
            delete_all.setText("已缓存:"+cacheSize+"\n删除所有缓存图片");
        }
    }
    /**
     * viewPager里添加fragment
     */
    private void initFragment() {

    }

    @OnClick({R.id.xuanzhewenjian, R.id.baocunbendi,R.id.delete_all})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.xuanzhewenjian://保存按钮
                Intent intent = new Intent(context, FileActivity.class);
                startActivityForResult(intent, Constants.REQ_CODE);
                break;
            case R.id.delete_all:
                LogUtils.d(" yx_files="+yx_files.toString());
                if(!yx_files.isEmpty()){
                    for (int i =0;i<yx_files.size();i++){
                        File file= yx_files.get(i).getFile();
                        if (file.exists() && file.isFile())
                        {
                            file.delete();
                        }
                    }
                    yx_files.clear();
                    if(rl_yx_file!=null&& rl_yx_file.getAdapter()!=null){
                        rl_yx_file.getAdapter().notifyDataSetChanged();
                    }
                }
                delete_all.setText("删除所有缓存图片");
                break;
            case R.id.baocunbendi://保存按钮
                for (FileEntity item : PickerManager.getInstance().files) {
                    File file = item.getFile();
                    try {
                        Bitmap bitmap1 = BitmapFactory.decodeStream(new FileInputStream(file));
                        LocalCacheUtils.Get().setBitmapToLocal(file.getName(), bitmap1);
                    } catch (Exception e) {
                    }
                }
                ToastUtils.info("添加成功！");
                FlushedImage();
                break;
        }
    }

    ArrayList<FileEntity> yx_files = new ArrayList<>();
    public static final String CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hblchayingdb/WebImage";

    public void FlushedImage() {
        File path = new File(CACHE_PATH);// 获得路径
        File[] files = path.listFiles();// 读取文件
        yx_files.clear();
        for (File f : files) {
            String absolutePath = f.getAbsolutePath();
            FileEntity e;
            if (checkExits(absolutePath)) {
                e = new FileEntity(absolutePath, f, true);
            } else {
                e = new FileEntity(absolutePath, f, false);
            }
            if (f.isFile()) {
                String[] imgs = {"png", "jpg", "jpeg", "gif"};
                e.setFileType(new FileType("IMG", imgs, 0));
                yx_files.add(e);
            }
        }
        rl_yx_file.setLayoutManager(new LinearLayoutManager(context));
        FilePickerShowAdapter adapter = new FilePickerShowAdapter(context, yx_files);
        adapter.setCallBack(callBack);
        rl_yx_file.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnFileItemClickListener() {
            @Override
            public void click(int position) {

//                String path=yx_files.get(position).getPath();
//                Bitmap bitmap =BitmapFactory.decodeFile("file://" + path);
//                MyImageDialog myImageDialog = new MyImageDialog(getActivity(),R.style.dialogWindowAnim,0,0,bitmap);
//                myImageDialog.show();

                //打开系统相册浏览照片
//                Intent intent = new Intent();
//                intent.setAction(Intent.ACTION_VIEW);
//                intent.setDataAndType(Uri.parse("file://" + path), "image/*");
//                startActivity(intent);
            }
        });
        delete_all.setText("已缓存:"+getCacheSize()+"\n删除所有缓存图片");
    }

    private FilePickerShowAdapter.CallBack callBack = new FilePickerShowAdapter.CallBack() {
        @Override
        public void delete() {
            delete_all.setText("已缓存:"+getCacheSize()+"\n删除所有缓存图片");
        }
    };

    private static boolean checkExits(String path) {
        for (FileEntity entity : PickerManager.getInstance().files) {
            if (entity.getPath().equals(path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQ_CODE) {
            mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
            FilePickerShowAdapter adapter = new FilePickerShowAdapter(context, PickerManager.getInstance().files);
            mRecyclerView.setAdapter(adapter);

            String res = "(" + PickerManager.getInstance().files.size() + "/" + PickerManager.getInstance().maxCount + ")";
            baocunbendi.setText(getString(R.string.file_select_res1, res));
            adapter.setOnItemClickListener(new OnFileItemClickListener() {
                @Override
                public void click(int position) {

//                    String path=PickerManager.getInstance().files.get(position).getPath();
//                    Intent intent = new Intent();
//                    intent.setAction(Intent.ACTION_VIEW);
//                    intent.setDataAndType(Uri.parse("file://" + path), "image/*");
//                    startActivity(intent);
                }
            });
        }
    }

    //-------------------------配置viewPager与fragment关联----------------------------//

    private String getCacheSize(){
        String sizeString = "";
        try {
            File folder = new File(CACHE_PATH); // 替换为你的文件夹路径
            long folderSize = getFolderSize(folder);
            sizeString = formatSize(folderSize); // 将大小转换为可读的格式（可选）
        }catch (Exception e){
            e.printStackTrace();
        }
        return sizeString;
    }

    private long getFolderSize(File dir) {
        long size = 0;
        if (dir != null && dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                if (file.isFile()) {
                    size += file.length();
                } else if (file.isDirectory()) {
                    size += getFolderSize(file); // 递归调用以获取子文件夹的大小
                }
            }
        }
        return size;
    }

    private String formatSize(long size) {
        if (size <= 0) return "0 Bytes";
        final String[] units = {"Bytes", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        yx_files.clear();
        yx_files = null;
        mRecyclerView.setAdapter(null);
        rl_yx_file.setAdapter(null);
    }

    @Override
    protected boolean canDragBack() {
        return false;
    }
}