package com.fxy.common;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.elvishew.xlog.XLog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.Permission;
import com.luck.picture.lib.permissions.RxPermissions;
import com.fxy.baselibrary.util.RxTimeTool;
import com.fxy.R;
import com.fxy.adapter.GridImageAdapter;
import com.fxy.constant.SPCache;
import com.fxy.view.FullyGridLayoutManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import io.reactivex.functions.Consumer;

public class PictureSelectorUpload {
    private Activity mActivity;
    private Context mContext;
    private int maxSelectNum = 9;
    private GridImageAdapter adapter;
    private RecyclerView mRecyclerView;
    private PopupWindow pop;

    private boolean onlyCamera = false;
    private boolean isCompress = false;
    private int compressQuality = 100;//默认值
    private int minimumCompressSize = 100;//最小压缩
    private OSSAsyncTask task;
    private ProgressDialog progressDialog;
    List<String> errorList =  new ArrayList<String> ();

    //资源类型
    private int pictureType=1;


    //操作上传
    protected String actionType = "";
    //等待上传
    private List<LocalMedia> awaitUploadList=new ArrayList<>();
    //已失败
    private List<LocalMedia> failUploadList=new ArrayList<>();
    //已上传好的
    private List<LocalMedia> selectList = new ArrayList<>();
    //已上传
    private ArrayList<String> ossPhotoList =new ArrayList<>();
    // 图片上传目录
    private String mPrefix="tally";

    //是否停止上传
    private String resourceUrl = "";

    private String resourceType = "";

    private String resourcePrefix = "";

    private OssService ossService;

    private CosService cosService;



    public PictureSelectorUpload(Activity activity, RecyclerView rvShowImg, String prefix){
        mActivity = activity;
        mContext  = activity.getBaseContext();
        mRecyclerView = rvShowImg;
        mPrefix = prefix;
        initAdapter();
        initData();

    }
    public PictureSelectorUpload(Activity activity, RecyclerView rvShowImg, String prefix,int maxNum){
        maxSelectNum = maxNum;
        mActivity = activity;
        mContext  = activity.getBaseContext();
        mRecyclerView = rvShowImg;
        mPrefix = prefix;
        initAdapter();
        initData();
    }

    public PictureSelectorUpload(Activity activity, RecyclerView rvShowImg, String prefix,int maxNum,int type){
        pictureType = type;
        maxSelectNum = maxNum;
        mActivity = activity;
        mContext  = activity.getBaseContext();
        mRecyclerView = rvShowImg;
        mPrefix = prefix;
        initAdapter();
        initData();

    }

    private void initData() {
        SPCache spCache = SPCache.getInstance(mContext);
        resourceUrl    = spCache.getResourceHost()+"/";
        resourceType   = spCache.getResourceType();
        resourcePrefix = spCache.getResourcePrefix();
    }

    public void setCompress(Boolean isCompress) {
        this.isCompress = isCompress;
    }
    public void setCompress(Boolean isCompress,int compressQuality,int minimumCompressSize) {
        this.isCompress = isCompress;
        this.compressQuality = compressQuality;
        this.minimumCompressSize = minimumCompressSize;
    }

    /**
     * 获取操作类型
     * @param actionType
     */
    public void setActionType(String actionType) {
        this.actionType = actionType;
    }

    public void setPictureType(int pictureType){
        this.pictureType = pictureType;
    }

    public void setOnlyCamera(boolean onlyCamera){
        this.onlyCamera = onlyCamera;
    }

    /**
     * 设置操作类型
     * @return
     */
    public String getActionType() {
       return actionType;
    }

    public ArrayList getPhotoList(){
        return  adapter.getPhotoList();
    }


    public void emptyRemake(){
        selectList.clear();
        ossPhotoList.clear();
        adapter.notifyDataSetChanged();
    }


    //销毁
    public void removeHandler(){
        if (uploadHandler!=null){
            uploadHandler.removeCallbacksAndMessages(null);
        }
    }

    /**
     * 获取选中图片
     * @param data
     */
    public void getSelectImg (Intent data){
        List<LocalMedia>  images = PictureSelector.obtainMultipleResult(data);
        //selectList = PictureSelector.obtainMultipleResult(data);
        awaitUploadList.addAll(images);
        // 例如 LocalMedia 里面返回三种path
        // 1.media.getPath(); 为原图path
        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
        // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的



        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        progressDialog = new ProgressDialog(mActivity);
        progressDialog.setTitle("待上传文件"+awaitUploadList.size()+"个");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        //监听取消事件
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                // TODO Auto-generated method stub
                taskCancel();
                return ;
            }

        });


        filedUpload();
        //new UploadThread().start();;

    }

    //取消任务
    public void taskCancel(){

        if (awaitUploadList.size()>0){
            new AlertDialog.Builder(mActivity)
                    .setTitle(R.string.dl_hint)
                    .setMessage("确定取消上传,并且清空所有上传任务?")
                    .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                            boolean a = progressDialog.isIndeterminate();
                            boolean b = progressDialog.isShowing();
                            if (progressDialog!=null && !progressDialog.isShowing()){
                                progressDialog.show();
                            }
                        }
                    }).setPositiveButton(R.string.str_submit, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    //取消上传任务
                    if (resourceType.equals("tencent")){
                        cosService.taskCancel();
                    }else{
                        ossService.taskCancel();
                    }
                    awaitUploadList.clear();

                }
            }).show();
        }else if(failUploadList.size()>0){
            new AlertDialog.Builder(mActivity)
                    .setTitle(R.string.dl_hint)
                    .setMessage("上传失败是否继续上传?")
                    .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                            progressDialog.dismiss();
                            failUploadList.clear();

                        }
                    }).setPositiveButton(R.string.str_submit, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    awaitUploadList.addAll(failUploadList);
                    filedUpload();
                }
            }).show();
        }



        //task.waitUntilFinished(); // 等待任务完成。
    }




    @SuppressLint("HandlerLeak")
    private Handler uploadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                //XLog.e(msg);
                JSONObject jsonObject = new JSONObject();
                String showTitle = "待上传文件"+(awaitUploadList.size())+"个";

                switch (msg.what){
                    case 0:
                        Toast.makeText(mActivity, "error", Toast.LENGTH_SHORT).show();
                        break;
                    case 1://失败
                        if (awaitUploadList.size()>0){
                            LocalMedia localMedia = awaitUploadList.get(0);
                            awaitUploadList.remove(0);
                            failUploadList.add(localMedia);
                            String message = (String) msg.obj;
                            if (!message.isEmpty()){
                                Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
                            }
                        }
                        break;
                    case 2://成功
                        String file_path = (String) msg.obj;
                        int current = msg.arg1;
                        //表示数据存在
                        if (awaitUploadList.size()>current){
                            LocalMedia localMedia = awaitUploadList.get(current);
                            awaitUploadList.remove(current);
                            selectList.add(localMedia);
                            ossPhotoList.add(file_path);
                            adapter.setPhotoPath(file_path);
                            adapter.setList(selectList);
                            adapter.notifyDataSetChanged();
                            progressDialog.setTitle(showTitle);

                        }
                        break;
                    case 3:
                        //设置进度条
                        progressDialog.setProgress(msg.arg1);
                        //progressDialog.show();
                        return;
                    case 4:
                        //获取上传状态

                        return;
                    default:
                        break;
                }

                if (failUploadList.size()>0){
                    showTitle= showTitle+",失败"+failUploadList.size()+"个";
                }

                progressDialog.setTitle(showTitle);
                if (awaitUploadList.size()>0){
                    filedUpload();
                }else{
                    closeDialog();
                    // 通过接口对象传上传状态
                    if (uploadChangeListener!=null){
                        uploadChangeListener.uploadResult(true,actionType);
                    }

                }
            } catch (Exception e) {
                XLog.e(e.getMessage());
                e.printStackTrace();
                // 通过接口对象传上传状态
                if (uploadChangeListener!=null){
                    uploadChangeListener.uploadResult(false,actionType);
                }

            }
        }
    };

    private void closeDialog(){
        if (progressDialog != null && !progressDialog.isIndeterminate() && progressDialog.isShowing()) {
            progressDialog.cancel();
        }
    }


    // 持有一个接口对象
    UploadChangeListener uploadChangeListener;
    // 状态变化监听
    public interface UploadChangeListener {
        // 回调方法 可以多个
        void uploadResult(boolean State,String actionType);
        void uploadActionType(String actionType);
    }
    // 提供注册事件监听的方法
    public void setOnChangeListener(UploadChangeListener uploadChangeListener) {
        this.uploadChangeListener = uploadChangeListener;
    }



    // 调用回调方法
    //uploadChangeListener.uploadResult(false);

    public void filedUpload(){
        if (awaitUploadList.size()==0){
            progressDialog.cancel();
            return;
        }
        //设置对话框执行内容
        if (progressDialog!=null){
            progressDialog.setTitle("待上传文件"+awaitUploadList.size()+"个");
            progressDialog.setProgress(0);
        }

        //上传第几个
        int num = 0;

        LocalMedia localMedia = awaitUploadList.get(num);
        String urlPath =localMedia.getPath();
        if (isCompress && localMedia.getCompressPath()!=null){
            urlPath = localMedia.getCompressPath();
        }

        if (urlPath.isEmpty()){
            Message msg = new Message();
            msg.obj = "文件路径不存在";
            msg.what = 1;
            uploadHandler.sendMessage(msg);
            return;
        }

        String fileSuffix = "";
        if (urlPath.lastIndexOf(".")>-1) {
            // 获取文件后缀名
            fileSuffix = urlPath.substring(urlPath.lastIndexOf("."));
        }

        String fileName= UUID.randomUUID().toString() + fileSuffix;

        if (resourceType.equals("tencent")){
            if (cosService==null){
                String path_prefix = resourcePrefix+"/android/"+mPrefix+"/"+RxTimeTool.getYestoryDate("yyyyMMd")+"/";
                cosService  = new CosService(mActivity.getBaseContext(),path_prefix);
            }
            //new cosThread(urlPath, fileName , num).start();
            cosService.cosUpload(urlPath, fileName , num,uploadHandler);

        }else{
            if (ossService ==null){
                ossService = new OssService(mActivity,mPrefix);
            }
            ossService.ossUpload(urlPath, fileName , num,uploadHandler);
            //new ossThread(urlPath, fileName , num).start();
        }
        // task.cancel(); // 可以取消任务
        // task.waitUntilFinished(); // 可以等待直到任务完成
    }


    private void initAdapter() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mActivity, 3, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(mActivity,mActivity, onAddPicClickListener,pictureType);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                            com.luck.picture.lib.PictureSelector.create(mActivity).externalPicturePreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            com.luck.picture.lib.PictureSelector.create(mActivity).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            com.luck.picture.lib.PictureSelector.create(mActivity).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            }
        });

        //回调语音
        adapter.setOnAudioListener(new GridImageAdapter.OnAudioListener() {
            @Override
            public void onSaveResult(Intent data) {
                getSelectImg(data);
            }
        });
    }



    public GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {

        @SuppressLint("CheckResult")
        @Override
        public void onAddPicClick() {
            //获取写的权限
            RxPermissions rxPermission = new RxPermissions(mActivity);
            rxPermission.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(new Consumer<Permission>() {
                        @Override
                        public void accept(Permission permission) {
                            if (permission.granted) {// 用户已经同意该权限
                                //第一种方式，弹出选择和拍照的dialog

                                if (pictureType==PictureConfig.TYPE_AUDIO){
                                    authAudio();
                                }else {
                                    if (onlyCamera){
                                        //第二种方式，直接进入相册，但是 是有拍照得按钮的
                                        authCamera();
                                    }else{
                                        showPop();
                                    }


                                }



                            } else {
                                Toast.makeText(mContext, "拒绝", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
            //监听返回当前某个上传类型
            if (uploadChangeListener!=null){
                uploadChangeListener.uploadActionType(actionType);
            }
        }
    };

    private void showAlbum() {
        //参数很多，根据需要添加
        com.luck.picture.lib.PictureSelector.create(mActivity)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(maxSelectNum)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选PictureConfig.MULTIPLE : PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                .enableCrop(true)// 是否裁剪
                .compress(true)// 是否压缩
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                //.selectionMedia(selectList)// 是否传入已选图片
                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                //.compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
                //.compressWH() // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效
                //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                .rotateEnabled(false) // 裁剪是否可旋转图片
                //.scaleEnabled()// 裁剪是否可放大缩小图片
                //.recordVideoSecond()//录制视频秒数 默认60s
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    private void showPop() {
        View bottomView = View.inflate(mContext, R.layout.layout_bottom_dialog, null);
        TextView mAlbum = bottomView.findViewById(R.id.tv_album);
        TextView mCamera = bottomView.findViewById(R.id.tv_camera);
        TextView mCancel = bottomView.findViewById(R.id.tv_cancel);

        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = 0.5f;
        mActivity.getWindow().setAttributes(lp);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                lp.alpha = 1f;
                mActivity.getWindow().setAttributes(lp);
            }
        });
        pop.setAnimationStyle(R.style.main_menu_photo_anim);
        pop.showAtLocation(mActivity.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.tv_album:
                        //相册
                        com.luck.picture.lib.PictureSelector.create(mActivity)
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(maxSelectNum)
                                .minSelectNum(1)
                                .imageSpanCount(4)
                                .selectionMode(PictureConfig.MULTIPLE)
                                .compress(isCompress) // 压缩
                                .cropCompressQuality(compressQuality)// 裁剪压缩质量 默认100
                                .minimumCompressSize(minimumCompressSize) //最新压缩图片

                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_camera:
                        //拍照
                        com.luck.picture.lib.PictureSelector.create(mActivity)
                                .openCamera(PictureMimeType.ofImage())
                                //只需要拍照
                                //.selectionMode(PictureConfig.SINGLE)
                                //.isCamera(true)
                                .compress(isCompress) // 压缩
                                .cropCompressQuality(compressQuality)// 裁剪压缩质量 默认100
                                .minimumCompressSize(minimumCompressSize) //最新压缩图片
                                .forResult(PictureConfig.CHOOSE_REQUEST);

                        break;
                    case R.id.tv_cancel:
                        //取消
                        //closePopupWindow();

                        break;
                }
                closePopupWindow();
            }
        };

        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
        mCancel.setOnClickListener(clickListener);


    }

    /**
     * 外部直接调取拍照接口
     */
    public void authCamera(){
        //拍照
        com.luck.picture.lib.PictureSelector.create(mActivity)
                .openCamera(PictureMimeType.ofImage())
                //只需要拍照
                //.selectionMode(PictureConfig.SINGLE)
                //.isCamera(true)
                //.compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
                .compress(isCompress) // 压缩
                .cropCompressQuality(compressQuality)// 裁剪压缩质量 默认100
                .minimumCompressSize(minimumCompressSize) //最新压缩图片
                .forResult(PictureConfig.CHOOSE_REQUEST);

        //监听返回当前某个上传类型
        if (uploadChangeListener!=null){
            uploadChangeListener.uploadActionType(actionType);
        }
    }

    /**
     * 自动打开录音
     */
    public void authAudio(){
        // 自带音频
        com.luck.picture.lib.PictureSelector.create(mActivity)
                .openCamera(PictureMimeType.ofAudio())
                //只需要音频
                .selectionMode(PictureConfig.TYPE_AUDIO)
                .compress(isCompress) // 压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);



        //监听返回当前某个上传类型
        if (uploadChangeListener!=null){
            uploadChangeListener.uploadActionType(actionType);
        }
    }


    /**
     * 关闭弹窗
     */
    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }




}
