package com.fxy.adapter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.elvishew.xlog.XLog;
import com.fxy.common.AudioRecoderDialog;
import com.fxy.utils.AudioRecoderUtils;
import com.fxy.workOrder.WorkOrderOptMainActivity;
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.tools.DateUtils;
import com.luck.picture.lib.tools.StringUtils;
import com.fxy.R;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import es.dmoral.toasty.Toasty;

/**
 * author：luck
 * project：PictureSelector
 * package：com.luck.pictureselector.adapter
 * email：893855882@qq.com
 * data：16/7/27
 */
public class GridImageAdapter extends RecyclerView.Adapter<GridImageAdapter.ViewHolder> {
    public static final int TYPE_CAMERA = 1;
    public static final int TYPE_PICTURE = 2;
    private LayoutInflater mInflater;
    private List<LocalMedia> list = new ArrayList<>();
    //已上传
    private ArrayList<String> ossPhotoList =new ArrayList<>();
    private int selectMax = 9;
    private Context context;
    private Activity mActivity;
    private int pictureType;

    //录音参数 start
    public static final int RECORD_AUDIO = 1024;
    private long downT;
    private AudioRecoderDialog recoderDialog;
    private AudioRecoderUtils recoderUtils;
    private List<LocalMedia> medias = new ArrayList<>();
    //录音参数 end

    /**
     * 点击添加图片跳转
     */
    private onAddPicClickListener mOnAddPicClickListener;

    public interface onAddPicClickListener {
        void onAddPicClick();
    }


    public GridImageAdapter(Context context,Activity activity, onAddPicClickListener mOnAddPicClickListener,int pictureType) {
        this.context = context;
        this.mActivity = activity;
        mInflater = LayoutInflater.from(context);
        this.mOnAddPicClickListener = mOnAddPicClickListener;
        this.pictureType = pictureType;
    }

    public void setSelectMax(int selectMax) {
        this.selectMax = selectMax;
    }

    public void setList(List<LocalMedia> list) {
        this.list = list;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        ImageView mImg;
        LinearLayout ll_del;
        TextView tv_duration;
        ProgressBar progressBar;

        ViewHolder(View view) {
            super(view);
            mImg = view.findViewById(R.id.fiv);
            ll_del = view.findViewById(R.id.ll_del);
            tv_duration = view.findViewById(R.id.tv_duration);
            progressBar = view.findViewById(R.id.progressBar);
        }
    }

    @Override
    public int getItemCount() {
        if (list.size() < selectMax) {
            return list.size() + 1;
        } else {
            return list.size();
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (isShowAddItem(position)) {
            return TYPE_CAMERA;
        } else {
            return TYPE_PICTURE;
        }
    }

    /**
     * 创建ViewHolder
     */
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = mInflater.inflate(R.layout.item_filter_image, viewGroup, false);
        return new ViewHolder(view);
    }

    private boolean isShowAddItem(int position) {
        int size = list.size();
        return position == size;
    }

    /**
     * 设置值
     */
    @Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
        //少于8张，显示继续添加的图标
        if (getItemViewType(position) == TYPE_CAMERA) {
            viewHolder.ll_del.setVisibility(View.INVISIBLE);
            if (pictureType==PictureConfig.TYPE_AUDIO){
                viewHolder.mImg.setImageResource(R.drawable.recod_start_f01);
                intAudioView(viewHolder);//

            }else{
                viewHolder.mImg.setImageResource(R.drawable.ic_add_img);
                viewHolder.mImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOnAddPicClickListener.onAddPicClick();
                    }
                });
            }
        } else {
            viewHolder.ll_del.setVisibility(View.VISIBLE);
            viewHolder.ll_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int index = viewHolder.getAdapterPosition();
                    // 这里有时会返回-1造成数据下标越界,具体可参考getAdapterPosition()源码，
                    // 通过源码分析应该是bindViewHolder()暂未绘制完成导致，知道原因的也可联系我~感谢
                    if (index != RecyclerView.NO_POSITION) {
                        list.remove(index);
                        ossPhotoList.remove(index);//删除oss
                        notifyItemRemoved(index);
                        notifyItemRangeChanged(index, list.size());
                        Log.i("delete position:", index + "--->remove after:" + list.size());
                    }
                }
            });
            LocalMedia media = list.get(position);
            int mimeType = media.getMimeType();
            String path;
            if (media.isCut() && !media.isCompressed()) {
                // 裁剪过
                path = media.getCutPath();
            } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                path = media.getCompressPath();
            } else {
                // 原图
                path = media.getPath();
            }
            // 图片
            if (media.isCompressed()) {
                Log.i("compress image result:", new File(media.getCompressPath()).length() / 1024 + "k");
                Log.i("压缩地址::", media.getCompressPath());
            }

            Log.i("原图地址::", media.getPath());
            int pictureType = PictureMimeType.isPictureType(media.getPictureType());
            if (media.isCut()) {
                Log.i("裁剪地址::", media.getCutPath());
            }
            long duration = media.getDuration();
            viewHolder.tv_duration.setVisibility(pictureType == PictureConfig.TYPE_VIDEO
                    ? View.VISIBLE : View.GONE);
            if (mimeType == PictureMimeType.ofAudio()) {
                viewHolder.tv_duration.setVisibility(View.VISIBLE);
                Drawable drawable = ContextCompat.getDrawable(context, R.drawable.picture_audio);
                StringUtils.modifyTextViewDrawable(viewHolder.tv_duration, drawable, 0);
            } else {
                Drawable drawable = ContextCompat.getDrawable(context, R.drawable.video_icon);
                StringUtils.modifyTextViewDrawable(viewHolder.tv_duration, drawable, 0);
            }
            viewHolder.tv_duration.setText(DateUtils.timeParse(duration));
            if (mimeType == PictureMimeType.ofAudio()) {
                viewHolder.mImg.setImageResource(R.drawable.audio_placeholder);
            } else {
                RequestOptions options = new RequestOptions()
                        .centerCrop()
                        .placeholder(R.color.color_f6)
                        .diskCacheStrategy(DiskCacheStrategy.ALL);
                Glide.with(viewHolder.itemView.getContext())
                        .load(path)
                        .apply(options)
                        .into(viewHolder.mImg);
            }
            //itemView 的点击事件
            if (mItemClickListener != null) {
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int adapterPosition = viewHolder.getAdapterPosition();
                        mItemClickListener.onItemClick(adapterPosition, v);
                    }
                });
            }
        }
    }

    private OnItemClickListener mItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(int position, View v);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mItemClickListener = listener;
    }

    public void setPhotoPath(String photoPath) {
        ossPhotoList.add(photoPath);
    }
    public void setPhotoPath( ArrayList<String> AllPhotoPath) {
        ossPhotoList = AllPhotoPath;
    }
    public ArrayList<String> getPhotoList(){
        return ossPhotoList;
    }


    @SuppressLint("ClickableViewAccessibility")
    //初始化录音按钮
    private void intAudioView(ViewHolder viewHolder){
        recoderDialog = new AudioRecoderDialog(context);
        recoderDialog.setOnCallbackListener(new AudioRecoderDialog.CallbackListener() {
            @Override
            public void closeResult() {
                stopRecord();
            }
        });
        viewHolder.mImg.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //⑧申请录制音频的动态权限
                        if(ContextCompat.checkSelfPermission(context, android.Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){
                            ActivityCompat.requestPermissions(mActivity,new String[]{android.Manifest.permission.RECORD_AUDIO},RECORD_AUDIO);
                        }else {
                            startRecord(view);
                        }
                        return true;
                    case MotionEvent.ACTION_UP:
                        stopRecord();
                        return true;
                }
                return false;
            }
        });






    }

    private void startRecord(View view){
        recoderDialog.showAtLocation(view, Gravity.CENTER, 0, 0);
        recoderDialog.setShowAlpha(0.58f);
        String fileName = UUID.randomUUID().toString() + ".amr";
        String pathName = Environment.getExternalStorageDirectory() + "/"+fileName;
        recoderUtils = new AudioRecoderUtils(new File(pathName));
        recoderUtils.setOnAudioStatusUpdateListener(new AudioRecoderUtils.OnAudioStatusUpdateListener() {
            @Override
            public void onUpdate(double db) {
                if(null != recoderDialog) {
                    int level = (int) db;
                    recoderDialog.setLevel((int)db);
                    recoderDialog.setTime(System.currentTimeMillis() - downT);
                }
            }
        });


        recoderUtils.startRecord();
        downT = System.currentTimeMillis();

    }

    private void stopRecord(){


        long diff = recoderUtils.stopRecord();
        recoderDialog.close();

        XLog.e( "录音存储到了"+recoderUtils.getFilePath());
        XLog.e( "说话时间："+diff);
        if (diff>1000L){
            medias.clear();
            String mediaPath = recoderUtils.getFilePath();
            String pictureType = "audio/mpeg";
            int duration = PictureMimeType.getLocalVideoDuration(mediaPath);
            LocalMedia media = new LocalMedia();
            media.setPath(mediaPath);
            media.setPictureType(pictureType);
            media.setDuration(duration);
            media.setMimeType(PictureMimeType.ofAudio());
            medias.add(media);
            Intent intent = new Intent().putExtra(PictureConfig.EXTRA_RESULT_SELECTION, (Serializable) medias);

            if (audioListener!=null){
                audioListener.onSaveResult(intent);
            }
        }else{
            Toasty.error(context, "说话时间太短" , Toast.LENGTH_SHORT).show();
            recoderDialog.setShowAlpha(1.0f);
        }


    }

    //回调到
    private OnAudioListener audioListener;
    public interface OnAudioListener {
        void onSaveResult(Intent data);
    }
    public void setOnAudioListener(OnAudioListener listener) {
        this.audioListener = listener;
    }

}