package com.efounder.pansoft.chat.record.voice;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
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.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.util.ToastUtil;

import java.io.File;

import static android.content.ContentValues.TAG;

/**
 * Created by YQS on 2018/3/31.
 */

public class VoiceView412 extends LinearLayout implements View.OnClickListener {
    private Context mContext;
    private LayoutInflater inflater;

    private View rootView;
    private ImageView ivRecordView;
    private TextView tvRecordView;

//    private VoiceLineView leftLineView;
//    private VoiceLineView rightLineView;

    private ImageView ivListener;//试听
    private ImageView ivDelete;//删除
    private LinearLayout lDeteteLayout;
    private LinearLayout lListenerLayout;
    private View lineView;//曲线

    private RelativeLayout rlRecordLayout;
    private RelativeLayout rlListenLayout;

    private TextView tvCannel;//取消
    private TextView tvSend;//发送
    //语音播放圆形
    private CustomProgress playProgressView;
    //录音
    //private RecordManager recordManager;
    //语音播放 录制组件
    private VoiceManager voiceManager;
    //语音播放时长的 textviw
    private TextView tvVoicePlayTimeView;

    //语音文件
    private File currentFile;
    //语音文件放置目录
   // private String folderPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "recordVoice";
    private String folderPath= ImageUtil.amrpath;

    //录音时长
    private long voiceTime = 0;
    //是否显示正在录音的 时长
    private boolean isShowRecordingTime = false;


    //手指在删除按钮上
    private boolean isOnDeleteView = false;
    //手指在播放按钮上
    private boolean isOnListenView = false;

    //是否要发送语音，录音结束抬起手指 如果是发送就会发送，不发送可能是删除或者试听语音
    private boolean isSendVoice = false;

    private MyRecordVoiceListener myRecordVoiceListener;


    public VoiceView412(Context context) {
        this(context, null);
    }

    public VoiceView412(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VoiceView412(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initView(mContext);
    }

    private void initView(Context mContext) {
        this.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//        this.setPadding(0, DensityUtil.dp2px(10), 0, DensityUtil.dp2px(10));
        this.setGravity(Gravity.CENTER);
        //获取语音布局
        inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rootView = inflater.inflate(R.layout.view_vocie_layout, this, true);


        ivRecordView = (ImageView) rootView.findViewById(R.id.iv_record);
        ivListener = (ImageView) rootView.findViewById(R.id.iv_listener);
        ivDelete = (ImageView) rootView.findViewById(R.id.iv_delete);
        lDeteteLayout = (LinearLayout) rootView.findViewById(R.id.ll_delete);
        lListenerLayout = (LinearLayout) rootView.findViewById(R.id.ll_listen);
        lineView = rootView.findViewById(R.id.lineArcView);

        ivRecordView.setOnTouchListener(new RecordViewTouchListener());
        tvRecordView = (TextView) rootView.findViewById(R.id.tv_record);

//        leftLineView = (VoiceLineView) rootView.findViewById(R.id.voicLineleft);
//        rightLineView = (VoiceLineView) rootView.findViewById(R.id.voicLineright);

        rlRecordLayout = (RelativeLayout) rootView.findViewById(R.id.rl_record);
        rlListenLayout = (RelativeLayout) rootView.findViewById(R.id.rl_listen);
        tvCannel = (TextView) rootView.findViewById(R.id.tv_cannel);
        tvSend = (TextView) rootView.findViewById(R.id.tv_send);
        tvSend.setOnClickListener(this);
        tvCannel.setOnClickListener(this);
        playProgressView = (CustomProgress) rootView.findViewById(R.id.circleProgressView);
        tvVoicePlayTimeView = (TextView) rootView.findViewById(R.id.tv_recordTime);

        //初始化语音播放
        voiceManager = new VoiceManager(mContext);
        //取消按钮点击事件
        tvCannel.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_cannel) {
            //取消按钮
            if (voiceManager.isPlaying()) {
                voiceManager.stopPlay();
            }
            FileDeleteUtil.delete(currentFile);
            playProgressView.setStatus(CustomProgress.FINISH_STATUS);
            rlListenLayout.setVisibility(View.GONE);
            rlRecordLayout.setVisibility(View.VISIBLE);
            lineView.setVisibility(View.INVISIBLE);
        } else if (id == R.id.tv_send) {
            //发送按钮先停止播放在发送
            if (voiceManager.isPlaying()) {
                voiceManager.stopPlay();
            }

            playProgressView.setStatus(CustomProgress.FINISH_STATUS);
            if (myRecordVoiceListener != null) {
                myRecordVoiceListener.recordFinish((int)voiceTime,currentFile);
            }
            rlListenLayout.setVisibility(View.GONE);
            rlRecordLayout.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 录音按钮触摸事件
     */
    private class RecordViewTouchListener implements OnTouchListener {


        private float mDownX;
        // private float mDownY;

        private float currentX;
        //private float currentY;

        @Override
        public boolean onTouch(View v, MotionEvent event) {


            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mDownX = event.getX();
                    //mDownY = event.getY();
                    isOnListenView = false;
                    isOnDeleteView = false;

                    setActionDownState();

                    break;

                case MotionEvent.ACTION_MOVE:
                    currentX = event.getX();
                    // currentY = event.getY();
                    float currentRawX = event.getRawX();
                    float currentRawY = event.getRawY();
                    if (currentX - mDownX > 0) {
                        //向右滑动
                        setRithtSlideState(currentRawX, currentRawY, Math.abs(currentX - mDownX));
                    } else if (currentX - mDownX < 0) {
                        //向左滑动
                        setLeftSlideState(currentRawX, currentRawY, Math.abs(currentX - mDownX));
                    }
                    break;

                case MotionEvent.ACTION_UP:
                    ivRecordView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.record_bacground_normal));
                    //停止录音并拿到录音时长
                    // long time = recordManager.stopRecord();
                    //long time = voiceTime;
                    VoiceManager.VoiceFile voiceFile = voiceManager.stopVoiceRecord();
                    if (voiceFile == null) {
                        voiceFile = new VoiceManager.VoiceFile();
                    }

                    long time = voiceFile.time;
                    voiceTime = time;
                    currentFile = voiceFile.voiceFile;
                    //隐藏两边的view
                    setBothSideViewShow(false);
                    //隐藏声音线
                    showVoiceLineView(false);
                    isSendVoice = false;
                    tvRecordView.setText(R.string.wrchatview_hold_and_talk);


                    if (time < 1) {
                        Toast.makeText(mContext, R.string.wrchatview_record_time_short, Toast.LENGTH_SHORT).show();
                        FileDeleteUtil.delete(currentFile);
                    } else {
                        if (isOnListenView) {
                            //Toast.makeText(mContext, "正在试听", Toast.LENGTH_SHORT).show();
                            rlListenLayout.setVisibility(View.VISIBLE);
                            rlRecordLayout.setVisibility(View.GONE);
                            lineView.setVisibility(INVISIBLE);
                            initPlayEvent(time);
                        } else if (isOnDeleteView) {
                            // Toast.makeText(mContext, "删除录音", Toast.LENGTH_SHORT).show();
                            FileDeleteUtil.delete(currentFile);
                        } else {
                            isSendVoice = true;
                            //录音结束
                            if (isSendVoice && myRecordVoiceListener != null) {
                                myRecordVoiceListener.recordFinish((int)time,currentFile);
                            }
                        }
                    }


                    break;
            }
            return true;

        }
    }


    /**
     * 按下按钮时的操作
     */
    private void setActionDownState() {
        //显示两边的view
        setBothSideViewShow(true);
        ivRecordView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.record_bacground_pressed));
        //动画缩放
        setViewScaleAnimtor(ivRecordView, 500, 1, 0.75f, 1);
        //开始录音
        //tvRecordView.setText("正在录音");
        //显示声音线
        showVoiceLineView(true);
        isShowRecordingTime = true;


        try {
            File voiceFolder = new File(folderPath);
            if (!voiceFolder.exists()) {
                voiceFolder.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showToast(mContext, R.string.wrchatview_voice_folder_settings_incorrect);
            return;
        }
        voiceManager.setVoiceRecordListener(new VoiceManager.VoiceRecordCallBack() {
            @Override
            public void recDoing(long time, String strTime) {
                if (isShowRecordingTime) {
                    tvRecordView.setText(strTime);
                }
            }

            @Override
            public void recVoiceGrade(int amplitude,int db) {
                if (db > 1) {
                    db = (int) (20 * Math.log10(db));
                }

//                leftLineView.setVolume(db);
//                rightLineView.setVolume(db);
            }

            @Override
            public void recStart(boolean init) {
                tvRecordView.setText("00:00");
            }

            @Override
            public void recPause(String str) {

            }

            @Override
            public void recFinish(long length, String strLength, String path) {
//                currentFile = new File(path);
//                voiceTime = length;
//                //录音结束
//                if (isSendVoice && myRecordVoiceListener != null) {
//                    myRecordVoiceListener.recordFinish(currentFile);
//                }
            }
        });
        voiceManager.startVoiceRecord(folderPath);


//        recordManager = new RecordManager(currentFile);
//        recordManager.setOnVolume(new RecordManager.OnVolume() {
//            @Override
//            public void onVolume(int db) {
//                Log.i(TAG, "onVolume: " + db);
//                if (db > 1) {
//                    db = (int) (20 * Math.log10(db));
//                }
//
//                leftLineView.setVolume(db);
//                rightLineView.setVolume(db);
//            }
//        });
//        recordManager.startRecord();
    }


    /**
     * 设置手势向右滑动的动画及文字
     *
     * @param currentRawX
     * @param currentRawY
     * @param slideDistance 滑动距离绝对值
     */
    private void setRithtSlideState(float currentRawX, float currentRawY, double slideDistance) {
        if (calcViewScreenLocation(lDeteteLayout).contains(currentRawX, currentRawY)) {
            //触摸在删除按钮上
            lDeteteLayout.setBackground(ContextCompat.getDrawable(mContext, R.drawable.record_ll_bg_pressed));
            ivDelete.setImageResource(R.drawable.record_delete_pressed);
            isOnDeleteView = true;
            tvRecordView.setText(R.string.wrchatview_unlock_to_send);
            showVoiceLineView(false);
            isShowRecordingTime = false;
        } else {
            lDeteteLayout.setBackground(ContextCompat.getDrawable(mContext, R.drawable.record_ll_bg_normal));
            ivDelete.setImageResource(R.drawable.record_delete_normal);
            isOnDeleteView = false;
            // tvRecordView.setText("正在录音");
            showVoiceLineView(true);
            isShowRecordingTime = true;


            float scale1 = (float) (slideDistance / 1000);
            Log.i(TAG, "scale1: " + scale1);
            if (scale1 > 0.3) {
                return;
            }
            setViewScaleAnimtor(lDeteteLayout, 0, 1f + scale1);
            setViewScaleAnimtor(ivDelete, 0, 1f - scale1);
        }
    }

    /**
     * 设置手势向左滑动的动画及文字
     *
     * @param currentRawX
     * @param currentRawY
     * @param slideDistance 滑动距离绝对值
     */
    private void setLeftSlideState(float currentRawX, float currentRawY, double slideDistance) {
        if (calcViewScreenLocation(ivListener).contains(currentRawX, currentRawY)) {
            isOnListenView = true;
            lListenerLayout.setBackground(ContextCompat.getDrawable(mContext, R.drawable.record_ll_bg_pressed));
            ivListener.setImageResource(R.drawable.record_listen_pressed);
            tvRecordView.setText(R.string.wrchatview_let_go);
            showVoiceLineView(false);
            isShowRecordingTime = false;

        } else {
            lListenerLayout.setBackground(ContextCompat.getDrawable(mContext, R.drawable.record_ll_bg_normal));
            ivListener.setImageResource(R.drawable.record_listen_normal);
            isOnListenView = false;
            //tvRecordView.setText("正在录音");
            showVoiceLineView(true);
            isShowRecordingTime = true;

            float scale1 = (float) (slideDistance / 1000);
            Log.i(TAG, "scale1: " + scale1);
            if (scale1 > 0.3) {
                return;
            }

            setViewScaleAnimtor(lListenerLayout, 0, 1f + scale1);
            setViewScaleAnimtor(ivListener, 0, 1f - scale1);

        }
    }

    //显示录制声音的音量线

    private void showVoiceLineView(boolean isShow) {
//        leftLineView.setVisibility(isShow ? View.VISIBLE : INVISIBLE);
//        rightLineView.setVisibility(isShow ? View.VISIBLE : INVISIBLE);
    }

    //显示或者隐藏两边的view
    private void setBothSideViewShow(boolean isShow) {
        lListenerLayout.setVisibility(isShow ? VISIBLE : GONE);
        lDeteteLayout.setVisibility(isShow ? VISIBLE : GONE);
        lineView.setVisibility(isShow ? VISIBLE : GONE);
        //恢复按钮默认颜色
        lDeteteLayout.setBackground(ContextCompat.getDrawable(mContext, R.drawable.record_ll_bg_normal));
        ivDelete.setImageResource(R.drawable.record_delete_normal);
        lListenerLayout.setBackground(ContextCompat.getDrawable(mContext, R.drawable.record_ll_bg_normal));
        ivListener.setImageResource(R.drawable.record_listen_normal);

        setViewScaleAnimtor(lDeteteLayout, 0, 1);
        setViewScaleAnimtor(lListenerLayout, 0, 1);

        setViewScaleAnimtor(ivListener, 0, 1);
        setViewScaleAnimtor(ivDelete, 0, 1);
    }


    /**
     * 设置view缩放动画
     *
     * @param view     view
     * @param duration 持续时间
     */
    private void setViewScaleAnimtor(View view, long duration, float... values) {
        AnimatorSet animatorSet1 = new AnimatorSet();//组合动画
        ObjectAnimator scaleX1 = ObjectAnimator.ofFloat(view, "scaleX", values);
        ObjectAnimator scaleY1 = ObjectAnimator.ofFloat(view, "scaleY", values);

        animatorSet1.setDuration(duration);
        animatorSet1.setInterpolator(new DecelerateInterpolator());
        animatorSet1.play(scaleX1).with(scaleY1);//两个动画同时开始
        animatorSet1.start();
    }


    /**
     * 计算指定的 View 在屏幕中的坐标。
     */
    public static RectF calcViewScreenLocation(View view) {
        int[] location = new int[2];
        // 获取控件在屏幕中的位置，返回的数组分别为控件左顶点的 x、y 的值
        view.getLocationOnScreen(location);
        return new RectF(location[0], location[1], location[0] + view.getWidth(),
                location[1] + view.getHeight());
    }

    /**
     * (x,y)是否在view的区域内
     *
     * @param view
     * @param x
     * @param y
     * @return
     */
    private boolean isTouchPointInView(View view, float x, float y) {
        if (view == null) {
            return false;
        }

        //getMeasuredWidth()获取的是view原始的大小，
        // 也就是这个view在XML文件中配置或者是代码中设置的大小。getWidth（）
        // 获取的是这个view最终显示的大小，这个大小有可能等于原始的大小也有可能不等于原始大小。
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int left = location[0];
        int top = location[1];
        int right = left + view.getWidth();
        int bottom = top + view.getHeight();

        RectF rectF = new RectF(left, top, right, bottom);
        if (rectF.contains(x, y)) {
            return true;
        }
        return false;
    }

    //播放界面
    private Thread thread;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                playProgressView.setProgress(msg.arg1);
            }
            super.handleMessage(msg);

        }
    };


    /**
     * 初始化语音播放相关
     *
     * @param time 单位是秒
     */
    private void initPlayEvent(final long time) {

        final VoiceTimeUtils ts = VoiceTimeUtils.timeSpanSecond(time);
        tvVoicePlayTimeView.setText(String.format("%02d:%02d",
                ts.mSpanMinute, ts.mSpanSecond));

        playProgressView.setStatus(CustomProgress.FINISH_STATUS);
        playProgressView.setmTotalProgress((int) time * 1000);
        playProgressView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (playProgressView.getIsStart()) {
                    if (thread != null && thread.isAlive()) {
                        thread.interrupt();
                    }
                    if (voiceManager.isPlaying()) {
                        voiceManager.stopPlay();
                    }
                    tvVoicePlayTimeView.setText(String.format("%02d:%02d",
                            ts.mSpanMinute, ts.mSpanSecond));
                    playProgressView.setStatus(CustomProgress.FINISH_STATUS);

                } else {

                    voiceManager.setVoicePlayListener(new VoiceManager.VoicePlayCallBack() {
                        @Override
                        public void voiceTotalLength(long time, String strTime) {
                        }

                        @Override
                        public void playDoing(long time, String strTime) {
                            tvVoicePlayTimeView.setText(strTime);
                        }

                        @Override
                        public void playPause() {

                        }

                        @Override
                        public void playStart() {
                            playProgressView.setStatus(CustomProgress.START_STATUS);
                            thread = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        for (int i = 0; i <= time * 1000; i = i + 16) {
                                            Thread.sleep(16);
                                            Message message = handler.obtainMessage();
                                            message.what = 1;
                                            message.arg1 = i;
                                            handler.sendMessage(message);
                                        }
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                            thread.start();
                        }

                        @Override
                        public void playFinish() {
                            playProgressView.setStatus(CustomProgress.FINISH_STATUS);
                        }
                    });
                    voiceManager.startPlay(currentFile.getAbsolutePath());

                }
            }
        });

    }


    //语音文件目录
    public void setVoiceFileFolder(String folderPath) {
        this.folderPath = folderPath;
    }


    public void setMyRecordVoiceListener(MyRecordVoiceListener listener) {
        this.myRecordVoiceListener = listener;
    }

    public interface MyRecordVoiceListener {
        //time 单位秒
        void recordFinish(int time, File file);
    }
}
