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

import android.content.Context;

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.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.bonait.bnframework.R;
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.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_SYSTEMSET;
import com.bonait.bnframework.common.filepicker.PickerManager;
import com.bonait.bnframework.common.filepicker.adapter.FilePickerShowAdapter;
import com.bonait.bnframework.common.filepicker.adapter.OnDeleteListener;
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.filepicker.util.OpenFile;
import com.bonait.bnframework.common.image.utils.LocalCacheUtils;
import com.bonait.bnframework.common.image.utils.MD5Encoder;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.MyImageDialog;
import com.bonait.bnframework.common.view.MyLayoutManager;
import com.bonait.bnframework.modules.home.fragment.from.FileActivity;
import com.bonait.bnframework.modules.home.fragment.mode.image_sp;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.arch.QMUIFragment;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 资源管理
 */
public class systeminternetfragment extends BaseFragment {
    @BindView(R.id.rl_file)
    RecyclerView mRecyclerView;
    @BindView(R.id.rl_yx_file)
    RecyclerView rl_yx_file;
    @BindView(R.id.baocunbendi)
    Button baocunbendi;
    private Context context;

    @Override
    protected View onCreateView() {
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_system_internet, null);
        ButterKnife.bind(this, root);
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Logger.d("我的fragment创建");
        context = getContext();
        FlushedImage();
    }

    @OnClick({R.id.xuanzhewenjian, R.id.baocunbendi})
    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.baocunbendi://保存按钮
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;//宽高压缩为原来的1/2
                for (FileEntity item : PickerManager.getInstance().files) {
                    File file = item.getFile();
                    try {
                        Bitmap bitmap1 = BitmapFactory.decodeStream(new FileInputStream(file));
                        new LocalCacheUtils().setBitmapToLocal(file.getName(), bitmap1);
                    } catch (Exception e) {
                    }
                }
                ToastUtils.info("添加成功！");
                break;
        }
    }

    ArrayList<FileEntity> yx_files = new ArrayList<>();
    private static final String CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hblxiaochaodb/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);
        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);
            }
        });
    }

    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);
                }
            });
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.d("我的fragment销毁");
    }

    /**
     * 当在activity设置viewPager + BottomNavigation + fragment时，
     * 为防止viewPager左滑动切换界面，与fragment左滑返回上一界面冲突引起闪退问题，
     * 必须加上此方法，禁止fragment左滑返回上一界面。
     * <p>
     * 切记！切记！切记！否则会闪退！
     * <p>
     * 当在fragment设置viewPager + BottomNavigation + fragment时，则不会出现这个问题。
     */
    @Override
    protected boolean canDragBack() {
        return false;
    }
}