package com.efounder.pansoft.chat.photo;

import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.manager.PictureAndCropManager;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.EasyPermissionUtils;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.FileUtils;
import com.utilcode.util.ImageUtils;
import com.utilcode.util.TimeUtils;
import com.utilcode.util.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;

import pub.devrel.easypermissions.AfterPermissionGranted;

/**
 * Created by will on 18-4-12.
 */

public class JFPicturePickPhotoWallActivity extends BaseActivity implements View.OnClickListener {

    private TextView titleTV;
    private TextView tvPreview, tvRawPic, tvSend;
    private CheckBox cbRawPic;
    private ArrayList<SelectModel> list = new ArrayList<>();
    private GridView mPhotoWall;
    public static int maxNum = 0;//可选择的最大图片数,intent有MAX_NUM
    public static boolean showRawPic = true;//默认显示原图选项，intent有SHOW_RAW_PIC
    private JFPicturePickPhotoWallAdapter adapter;
    private PictureAndCropManager pictureAndCropManager;//拍照裁剪

    public static final String MAX_NUM = "maxNum";//最大可选图片数量
    public static final String SHOW_RAW_PIC = "showRawPic";//是否显示原图
    public static final String SELECT_MODE = "select_mode";//选择模式：图片，视频，还是图片视频混合
    /** 注意，若要带有拍照功能，则不可以传过来图片数组"mPictureList"，不和相册里的图片联动 **/
    public static final String WITH_TAKE_PIC = "take_pic";//带有拍照选项，默认没有
    private boolean isWithTakePic = false;

    public static final String SELECTED_VIDEO = "selectedVideo";//返回的result
    public static final String MAX_VIDEO_SIZE = "maxVideoSize";//视频最大大小
    public static final String MAX_VIDEO_DURATION = "maxVideoDuration";//视频最长时间

    public static final int MODE_PIC_VIDEO = 101;//图片视频显示模式
    public static final int MODE_PIC_ONLY = 102;//图片显示模式
    public static final int MODE_VIDEO_ONLY = 103;//视频显示模式
    public static int videoSize = 20;//最大可选择视频大小20M
    public static int videoDuration = 120;//最大可选择视频时间20s
    public static int mode = 102;// 默认只有图片
    public static LinkedList<SelectModel> selectedPics = new LinkedList<>();//静态数组，选中的item
    private String sendBtnName = "";//如果intent传来这个参数，那么底部发送按钮改为这个值，默认为“发送”

    /**
     * 当前文件夹路径
     */
    private String currentFolder = null;
    /**
     * 当前展示的是否为最近照片
     */
    private boolean isLatest = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qq_style_activity_picture_pick_photo_wall);
        //禁止滑动返回
        setSwipeBackEnable(false);
        //根据传来的数据初始化参数
        initIntent();
        //初始化view
        initView();
        //处理图片选中状态
        dealWithPicSelectChange();
        //处理原图选中状态
        dealWithRawPicSelected();
        //设置适配器
        setUpAdapter();
        //加载相册数据
        loadPhotoData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter.notifyDataSetChanged();
        dealWithPicSelectChange();
        cbRawPic.setChecked(EnvironmentVariable.getProperty("picture_pick_is_raw_pic", "false").equals("true"));
    }

    /**
     * 根据传过来的intent参数初始化参数
     */
    private void initIntent() {
        if (getIntent().getExtras() != null && getIntent().getExtras().get("mPictureList") != null) {
            ArrayList<String> tempList = (ArrayList<String>) getIntent().getExtras().get("mPictureList");
            if (tempList.size() > 0) {
                for (String path : tempList) {
                    SelectModel selectModel = new SelectModel(path, MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE);
                    selectedPics.add(selectModel);
                }
            }
        }

        if (getIntent().getExtras().containsKey(MAX_NUM)) {
            maxNum = getIntent().getIntExtra(MAX_NUM, 0);
        }

        if (getIntent().getExtras().containsKey(SHOW_RAW_PIC)) {
            showRawPic = getIntent().getExtras().getBoolean(SHOW_RAW_PIC);
        }

        if (getIntent().getExtras().containsKey("sendBtnName")) {
            sendBtnName = getIntent().getStringExtra("sendBtnName");
        }

        //默认图片模式
        if (getIntent().getExtras().containsKey(SELECT_MODE)) {
            mode = getIntent().getIntExtra(SELECT_MODE, MODE_PIC_ONLY);
        } else {
            mode = MODE_PIC_ONLY;
        }

        if (getIntent().getExtras().containsKey(MAX_VIDEO_SIZE)) {
            videoSize = getIntent().getIntExtra(MAX_VIDEO_SIZE, 20);
        }

        if (getIntent().getExtras().containsKey(MAX_VIDEO_DURATION)) {
            videoDuration = getIntent().getIntExtra(MAX_VIDEO_DURATION, 20);
        }

        //带有拍照
        //注意，若要带有拍照功能，则不可以传过来图片数组"mPictureList"，不和相册里的图片联动 **/
        if (getIntent().getExtras().containsKey(WITH_TAKE_PIC)) {
            isWithTakePic = true;
            pictureAndCropManager = new PictureAndCropManager(this);
        }
    }

    /**
     * 初始化view
     */
    private void initView() {
        ConstraintLayout clBottom = (ConstraintLayout) findViewById(R.id.cl_bottom);
        clBottom.setOnClickListener(this);
        titleTV = (TextView) findViewById(R.id.tv_title);
        titleTV.setText(ResStringUtil.getString(R.string.wrchatview_recent_photos));
        tvPreview = (TextView) findViewById(R.id.tv_preview);
        tvRawPic = (TextView) findViewById(R.id.tv_raw_pic);
        tvSend = (TextView) findViewById(R.id.tv_send_pic);
        if (!sendBtnName.equals("")) {
            tvSend.setText(sendBtnName);
        }
        cbRawPic = (CheckBox) findViewById(R.id.cb_raw_pic);
        if (!showRawPic) {
            cbRawPic.setVisibility(View.INVISIBLE);
            tvRawPic.setVisibility(View.INVISIBLE);
        }
        tvPreview.setOnClickListener(this);
        tvRawPic.setOnClickListener(this);
        tvSend.setOnClickListener(this);
        tvSend.setClickable(false);
        cbRawPic.setOnClickListener(this);
        cbRawPic.setChecked(EnvironmentVariable.getProperty("picture_pick_is_raw_pic", "false").equals("true"));

        cbRawPic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                dealWithRawPicSelected();
                EnvironmentVariable.setProperty("picture_pick_is_raw_pic", String.valueOf(cbRawPic.isChecked()));
            }
        });
        TextView tvCancel = (TextView) findViewById(R.id.tv_save);
        tvCancel.setText(R.string.common_text_cancel);
        tvCancel.setVisibility(View.VISIBLE);
        tvCancel.setOnClickListener(this);

        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
    }

    /**
     * 设置适配器
     */
    private void setUpAdapter() {
        mPhotoWall = (GridView) findViewById(R.id.photo_wall_grid);
        adapter = new JFPicturePickPhotoWallAdapter(this, list, isWithTakePic);
        mPhotoWall.setAdapter(adapter);

        adapter.setOnPicSelectedChangedListener(new JFPicturePickPhotoWallAdapter.OnPicSelectedChangedListener() {
            @Override
            public void onPicSelectedChanged() {
                dealWithPicSelectChange();
                dealWithRawPicSelected();
            }
        });
        adapter.setOnVideoSelectedListener(new JFPicturePickPhotoWallAdapter.OnVideoSelectedListener() {
            @Override
            public void onVideoSelected(int position) {
                if (FileUtils.getFileLength(list.get(position).getPath()) > videoSize * 1024 * 1024) {
                    ToastUtils.showShort(ResStringUtil.getString(R.string.wrchatview_video_than) + videoSize + ResStringUtil.getString(R.string.wrchatview_m_select));
                    return;
                }
                int during = TimeUtils.getRingDuring(list.get(position).getPath());
                if (during > videoDuration * 1000) {
                    ToastUtils.showShort(ResStringUtil.getString(R.string.wrchatview_video_than) + videoDuration + ResStringUtil.getString(R.string.wrchatview_s_select));
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra(SELECTED_VIDEO, list.get(position).getPath());
                intent.putExtra("videoTime", during + "");
                setResult(RESULT_OK, intent);
                finish();
                EnvironmentVariable.setProperty("picture_pick_is_raw_pic", "false");
                overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);

            }
        });
        adapter.setOnTakePicSectedListener(new JFPicturePickPhotoWallAdapter.OnTakePicSectedListener() {
            @Override
            public void onTakePic() {
                startTakePhoto();
            }
        });
    }

    @AfterPermissionGranted(EasyPermissionUtils.PERMISSION_REQUEST_CODE_CAMERA)
    private void startTakePhoto() {
        if (EasyPermissionUtils.checkCameraPermission()) {
            pictureAndCropManager.takePicture();
        } else {
            EasyPermissionUtils.requestCameraPermission(this);
        }
    }

    /**
     * 加载相册数据
     * 在线程中加载
     */
    private void loadPhotoData() {
        //code,从相册选择界面传来，100表示某个相册，需要从相册路径取数据，200表示最近照片，需要调用其他方法
        int code = getIntent().getIntExtra("code", -1);
        LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.wrchatview_read_photos));
        if (code == 100) {
            //某个相册
            String folderPath = getIntent().getStringExtra("folderPath");
            if (isLatest || (folderPath != null && !folderPath.equals(currentFolder))) {
                currentFolder = folderPath;
                updateView(100, currentFolder);
                isLatest = false;
            }
        } else if (code == 200) {
            //“最近照片”
//            if (!isLatest) {
            updateView(200, null);
            isLatest = true;
//            }
        } else {
            CommonThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    final ArrayList<SelectModel> tempList = JFMessagePicturePickView
                            .getAllPicture(JFPicturePickPhotoWallActivity.this, -1);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (tempList != null)
                                list.addAll(tempList);
                            LoadingDataUtilBlack.dismiss();
                            adapter.notifyDataSetChanged();
                        }
                    });
                }
            });
        }
    }

    /**
     * 第一次跳转至相册页面时，传递最新照片信息
     */
    private boolean firstIn = true;

    /**
     * 点击返回时，跳转至相册页面
     */
    private void backAction() {
        //没有照片，直接退出
        if (list == null || (list != null && list.size() == 0)) {
            selectedPics.clear();
            Intent intent = new Intent();
            intent.putExtra("cancel", true);
            setResult(RESULT_CANCELED, intent);
            EnvironmentVariable.setProperty("picture_pick_is_raw_pic", "false");
            finish();
            overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
            return;
        }

        //进入相册界面
        Intent intent = new Intent(this, JFPicturePickerPhotoAlbumActivity.class);
        //传递“最近照片”分类信息
//        if (firstIn) {
        if (list != null && list.size() > 0) {
            intent.putExtra("latest_count", list.size());
            intent.putExtra("latest_first_img", list.get(0).getPath());
        }
//            firstIn = false;
//        }

        startActivityForResult(intent, JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE);
        //overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
        //动画
    }

    //重写返回键
    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backAction();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 根据图片所属文件夹路径，刷新页面
     */
    private void updateView(int code, final String folderPath) {
        list.clear();
        adapter.notifyDataSetChanged();

        if (code == 100) {   //某个相册
            int lastSeparator = folderPath.lastIndexOf(File.separator);
            String folderName = folderPath.substring(lastSeparator + 1);
            titleTV.setText(folderName);
            CommonThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    final ArrayList<SelectModel> tempList = getAllImagePathsByFolder(folderPath);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (tempList != null)
                                list.addAll(tempList);
                            LoadingDataUtilBlack.dismiss();
                            adapter.notifyDataSetChanged();
                        }
                    });
                }
            });
        } else if (code == 200) {  //最近照片
            titleTV.setText(ResStringUtil.getString(R.string.wrchatview_recent_photos));
            CommonThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    final ArrayList<SelectModel> tempList = JFMessagePicturePickView
                            .getAllPicture(JFPicturePickPhotoWallActivity.this, -1);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (tempList != null)
                                list.addAll(tempList);
                            LoadingDataUtilBlack.dismiss();
                            adapter.notifyDataSetChanged();
                        }
                    });
                }
            });
        }

        if (list.size() > 0) {
            //滚动至顶部
            mPhotoWall.smoothScrollToPosition(0);
        }
    }


    /**
     * 获取指定路径下的所有图片文件。
     */
    private ArrayList<SelectModel> getAllImagePathsByFolder(String folderPath) {
        File folder = new File(folderPath);
        ArrayList<SelectModel> list = new ArrayList<>();
        String[] allFileNames = folder.list();
        if (allFileNames == null || allFileNames.length == 0) {
            return list;
        }

        ArrayList<SelectModel> imageFilePaths = new ArrayList<>();
        for (int i = allFileNames.length - 1; i >= 0; i--) {
            if (mode == MODE_PIC_ONLY) {
                //图片模式
                if (ImageUtils.isImage(allFileNames[i])) {
                    imageFilePaths.add(new SelectModel(folderPath + File.separator + allFileNames[i],
                            MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE));
                }
            } else if (mode == MODE_PIC_VIDEO) {
                //图片视频模式
                if (ImageUtils.isImage(allFileNames[i])) {
                    imageFilePaths.add(new SelectModel(folderPath + File.separator + allFileNames[i],
                            MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE));
                } else if (allFileNames[i].endsWith(".mp4") || allFileNames[i].endsWith(".avi")
                        || allFileNames[i].endsWith(".3gp") || allFileNames[i].endsWith(".mkv")) {
                    SelectModel selectModel = new SelectModel(folderPath + File.separator + allFileNames[i],
                            MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO);
                    selectModel.setSize(JFMessagePicturePickView.getVideoDuration(folderPath + File.separator + allFileNames[i]));
                    imageFilePaths.add(selectModel);
                }
            } else {
                //视频模式
                if (allFileNames[i].endsWith(".mp4") || allFileNames[i].endsWith(".avi")
                        || allFileNames[i].endsWith(".3gp") || allFileNames[i].endsWith(".mkv")) {
                    SelectModel selectModel = new SelectModel(folderPath + File.separator + allFileNames[i],
                            MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO);
                    selectModel.setSize(JFMessagePicturePickView.getVideoDuration(folderPath + File.separator + allFileNames[i]));
                    imageFilePaths.add(selectModel);
                }
            }
        }

        return imageFilePaths;
    }


    //获取已选择的图片路径
    private ArrayList<String> getSelectImagePaths() {
        LinkedList map = adapter.getSelectionMap();
        if (map.size() == 0) {
            return null;
        }

        ArrayList<String> selectedImageList = new ArrayList<String>();

        for (int i = 0; i < list.size(); i++) {
            selectedImageList.add(list.get(i).getPath());
        }

        return selectedImageList;
    }

    private void dealWithPicSelectChange() {
        if (selectedPics.size() > 0) {
            tvPreview.setTextColor(getResources().getColor(R.color.chat_red));
            tvPreview.setClickable(true);
            if (!sendBtnName.equals("")) {
                tvSend.setText(sendBtnName + "(" + selectedPics.size() + ")");
            } else {
                tvSend.setText(ResStringUtil.getString(R.string.wrchatview_send) + "(" + selectedPics.size() + ")");
            }
            tvSend.setBackground(getResources().getDrawable(R.drawable.qq_style_rect_button_shape));
            tvSend.setTextColor(getResources().getColor(R.color.white));
            tvSend.setClickable(true);

        } else {
            tvPreview.setClickable(false);
            tvPreview.setTextColor(getResources().getColor(R.color.gray));
            if (!sendBtnName.equals("")) {
                tvSend.setText(sendBtnName);
            } else {
                tvSend.setText(ResStringUtil.getString(R.string.wrchatview_send));
            }
            tvSend.setBackground(getResources().getDrawable(R.drawable.qq_style_rect_button_shape_gray));
            tvSend.setTextColor(getResources().getColor(R.color.lightgray));
            tvSend.setClickable(false);
            tvRawPic.setText(ResStringUtil.getString(R.string.wrchatview_original_image));
        }
    }

    private void dealWithRawPicSelected() {
        if (cbRawPic.isChecked()) {
            tvRawPic.setTextColor(getResources().getColor(R.color.chat_red));
            if (selectedPics.size() > 0) {
                LinkedList<String> tempList = new LinkedList<>();
                for (int i = 0; i < selectedPics.size(); i++) {
                    tempList.add(selectedPics.get(i).getPath());
                }
                String size = FileUtils.getFilesSize(tempList);
                tvRawPic.setText(ResStringUtil.getString(R.string.wrchatview_original_image) + "(" + size + ")");
            } else {
                tvRawPic.setText(ResStringUtil.getString(R.string.wrchatview_original_image));
            }
        } else {
            tvRawPic.setText(ResStringUtil.getString(R.string.wrchatview_send));
            tvRawPic.setTextColor(getResources().getColor(R.color.gray));
        }
    }

    @Override
    public void onBackPressed() {

        backAction();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_save) {
            selectedPics.clear();
            Intent intent = new Intent();
            intent.putExtra("cancel", true);
            setResult(RESULT_CANCELED, intent);
            EnvironmentVariable.setProperty("picture_pick_is_raw_pic", "false");
            finish();
            overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
        } else if (id == R.id.tv_raw_pic) {
            cbRawPic.setChecked(!cbRawPic.isChecked());
        } else if (id == R.id.iv_back) {
            backAction();
        } else if (id == R.id.tv_preview) {
            Intent intent = new Intent(this, JFPicturePickBigPictureActivity.class);
            intent.putExtra("selectedPreview", true);
            intent.putExtra("curIndex", selectedPics.size() - 1);
            startActivityForResult(intent, JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE);
        } else if (id == R.id.tv_send_pic) {
            Intent intent = new Intent();
            LinkedList<String> tempList = new LinkedList<>();
            for (int i = 0; i < JFPicturePickPhotoWallActivity.selectedPics.size(); i++) {
                tempList.add(JFPicturePickPhotoWallActivity.selectedPics.get(i).getPath());
            }
            intent.putExtra("mSelectedPics", tempList);
            intent.putExtra("isRawPic", cbRawPic.isChecked());
            setResult(RESULT_OK, intent);
            finish();
            selectedPics.clear();
            EnvironmentVariable.setProperty("picture_pick_is_raw_pic", "false");
            overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE &&
                resultCode == RESULT_OK) {
            setResult(RESULT_OK, data);
            finish();
            selectedPics.clear();
            EnvironmentVariable.setProperty("picture_pick_is_raw_pic", "false");
            overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
        } else if (requestCode == JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE &&
                resultCode == RESULT_CANCELED && data != null) {

            setResult(RESULT_CANCELED, data);
            finish();
            selectedPics.clear();
            EnvironmentVariable.setProperty("picture_pick_is_raw_pic", "false");
            overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
        } else if (requestCode == PictureAndCropManager.PHOTO_REQUEST_TAKEPHOTO) {
            if (resultCode == RESULT_CANCELED) {
                //do nothing
                setResult(RESULT_CANCELED, data);
            } else {
                ArrayList<String> list = new ArrayList<>();
                list.add(pictureAndCropManager.getPicturePath());
                Intent intent = new Intent();
                intent.putExtra("mSelectedPics", list);
                intent.putExtra("isRawPic", cbRawPic.isChecked());
                setResult(RESULT_OK, intent);
            }
            finish();
            selectedPics.clear();
            EnvironmentVariable.setProperty("picture_pick_is_raw_pic", "false");
            overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
        }
    }
}
