package com.efounder.pansoft.chat.input;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import androidx.fragment.app.Fragment;
import androidx.core.content.ContextCompat;
import androidx.legacy.widget.Space;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.activity.RecorderActivity;
import com.efounder.chat.adapter.ChatVoicePlayClickListener;
import com.efounder.chat.listener.onInputLayoutChangeListener;
import com.efounder.chat.model.ChatMenuModel;
import com.efounder.chat.model.VoicePlayingEvent;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.view.voicedictate.VoiceDictatePopManager;
import com.efounder.imageselector.utils.FileUtils;
import com.efounder.message.struct.IMStruct002;
import com.efounder.pansoft.chat.camera.CameraNew;
import com.efounder.pansoft.chat.camera.CameraOld;
import com.efounder.pansoft.chat.camera.CameraSupport;
import com.efounder.pansoft.chat.emoji.EmojiView;
import com.efounder.pansoft.chat.emoji.EmoticonsKeyboardUtils;
import com.efounder.pansoft.chat.emoji.widget.EmoticonsEditText;
import com.efounder.pansoft.chat.listener.CameraControllerListener;
import com.efounder.pansoft.chat.listener.CameraEventListener;
import com.efounder.pansoft.chat.listener.OnCameraCallbackListener;
import com.efounder.pansoft.chat.listener.OnClickEditTextListener;
import com.efounder.pansoft.chat.listener.OnMenuClickListener;
import com.efounder.pansoft.chat.listener.VoiceDictateSendListener;
import com.efounder.pansoft.chat.more.MenuMoreView;
import com.efounder.pansoft.chat.photo.JFMessagePicturePickView;
import com.efounder.pansoft.chat.record.voice.VoiceView;
import com.efounder.pansoft.chat.shake.ShakeView;
import com.efounder.util.EnvSupportManager;
import com.efounder.utils.CommonUtils;
import com.efounder.utils.EasyPermissionUtils;
import com.utilcode.util.UriUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class ChatInputView extends LinearLayout
        implements View.OnClickListener, TextWatcher,
        JFChatMenuManager.OnMenuMoreItemClickListener,
        JFMessagePicturePickView.OnPicSendListener,
        // OnFileSelectedListener,
        ShakeView.ShakeOnclickListener,
        CameraEventListener, ViewTreeObserver.OnPreDrawListener, VoiceDictateSendListener {

    private static final String TAG = "ChatInputView";
    //相机拍摄的照片 requestcode
    public static final int REQUEST_CODE_CAMERA = 18;
    //选择文件
    public static final int REQUEST_CODE_FILE = 6;
    //拍摄小视频
    public static final int REQUEST_CODE_SELECT_VIDEO = 200;
    //false 的时候表示 不监听@
    private boolean enableWatcher = true;


    //输入框
    private EmoticonsEditText mChatInputEditText;

    private TextView mSendCountTv;
    //输入的字符
    private CharSequence mInput;
    //做左边距
    private Space mInputMarginLeft;
    //右边距
    private Space mInputMarginRight;
    //语音按钮
    private ImageButton mVoiceBtn;
    //照片按钮
    private ImageButton mPhotoBtn;
    //拍照按钮
    private ImageButton mCameraBtn;
    //抖一抖按钮
    private ImageButton mShakeBtn;
    //红包按钮
    private ImageButton mRedPackageBtn;
    //gif按钮
    private ImageButton mGifBtn;
    //表情按钮
    private ImageButton mEmojiBtn;
    //视频按钮
    private ImageButton mVideoBtn;
    //add按钮
    private ImageButton mAddButton;
    //发送按钮（new 现在使用这个）
    private Button mChatSendButton;

    //消息输入的linearlayout
    private LinearLayout mChatInputContainer;
    //输入框下方的菜单
    private LinearLayout mMenuItemContainer;
    //语音 表情 视频 文件等布局
    private FrameLayout mMenuContainer;

    //录音组件
    private VoiceView recordVoiceView;
    //表情组件
    private EmojiView mEmojiView;
    //抖一抖组件
    private ShakeView mShakeView;
    //加号 更多组件
    private MenuMoreView menuMoreView;
    //选择照片组件
    //SelectPhotoView mSelectPhotoView;
    JFMessagePicturePickView mPickPhotoView;
    //暂未用到
    private ImageButton mSelectAlbumIb;
    //拍照组件
    private FrameLayout mCameraFl;
    private TextureView mTextureView;
    private ImageButton mCaptureBtn;
    private ImageButton mCloseBtn;
    private ImageButton mSwitchCameraBtn;
    private ImageButton mFullScreenBtn;
    private ImageButton mRecordVideoBtn;

    //表情 拍照 选图 选文件点击回调
    private OnMenuClickListener onMenuClickListener;
    private OnCameraCallbackListener mCameraListener;


    private OnClickEditTextListener mEditTextListener;
    private CameraControllerListener mCameraControllerListener;

    //提及@功能
    private OnMentionInputListener onMentionInputListener;


    //xml中解析属性
    private ChatInputStyle mStyle;
    //输入法管理
    private InputMethodManager mInputMethodManager;
    //窗口
    private Window mWindow;

    //屏幕宽度
    private int mScreenWidth;
    //屏幕高度
    private int mScreenHeight;
    //键盘高度
    private int mSoftKeyboardHeight;
    //语音 表情 视频 文件等布局的高度 默认值，可以通过set方法设置
    public static int menuLayoutHeight = 831;
    //语音 表情 视频 文件等布局的最小
    public int minMenuHeight;
    private boolean mPendingShowMenu;


    private MediaPlayer mMediaPlayer = new MediaPlayer();
    // 判断如果是记录视频模式
    private boolean mIsRecordVideoMode = false;

    // 判断现在是录制视频
    private boolean mIsRecordingVideo = false;
    // 判断是完成录制视频
    private boolean mFinishRecordingVideo = false;

    // 视频文件保存路径
    private String mVideoFilePath;

    private int mVideoDuration;

    // If audio file has been set
    private boolean mSetData;
    private FileInputStream mFIS;
    private FileDescriptor mFD;
    private boolean mIsEarPhoneOn;

    //拍照文件
    private File cameraFile;


    private CameraSupport mCameraSupport;
    //摄像头id
    private int mCameraId = -1;
    private boolean mIsBackCamera = true;
    private boolean mIsFullScreen = false;
    private Context mContext;
    private Rect mRect = new Rect();
    private LinearLayout mCameraBtnContainer;
    View voiceBtnContainer;
    View photoBtnContainer;
    View emojiBtnContainer;
    View shakeBtnContainer;
    View redPackageContainer;
    View gifContainer;
    View addContainer;
    View videoContainer;

    //是否是fragment 加载此view 是的话 startactivityForResult 需要fragment
    private boolean isFragment = false;
    private Fragment loadFragment;
    private boolean banSpeak;

    private LinearLayout llSpeakInputLayout;
    private LinearLayout llBanspeakInputLayout;
    private TextView tvBanText;

    //语音听写按钮
    private ImageView aurora_menuitem_iv_voicedictate;
    //语音听写的弹窗管理器
    private VoiceDictatePopManager voiceDictatePopManager;
    //是否支持发送识别语音
    private boolean isSupportRecognizeVoiceSend;
    //是否在界面变化的时候弹出语音识别的窗口
    private boolean isShowPop;
    //当前聊天的人
    private int toUserId;
    //聊天类型
    private int chatType;

    //每5s发送一次正在输入的系统消息
    private long lastSendTime;

    public ChatInputView(Context context) {
        super(context);
        init(context);
    }

    public ChatInputView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public ChatInputView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context) {
        isSupportRecognizeVoiceSend = EnvSupportManager.isSupportRecognizeVoiceSend();
        mContext = context;
        inflate(context, R.layout.view_chatinput_dark, this);

        voiceDictatePopManager = new VoiceDictatePopManager(mContext);
        voiceDictatePopManager.setVoiceDictateSendListener(this);
        // 菜单按钮
        mChatInputEditText = (EmoticonsEditText) findViewById(R.id.aurora_et_chat_input);
        // mChatInputEditText.setTextColor(getResources().getColor(R.color.jfchatactivity_bottom_editext_text_color));
        mVoiceBtn = (ImageButton) findViewById(R.id.aurora_menuitem_ib_voice);
        mPhotoBtn = (ImageButton) findViewById(R.id.aurora_menuitem_ib_photo);
        mCameraBtn = (ImageButton) findViewById(R.id.aurora_menuitem_ib_camera);
        mEmojiBtn = (ImageButton) findViewById(R.id.aurora_menuitem_ib_emoji);
        mAddButton = (ImageButton) findViewById(R.id.aurora_menuitem_ib_add);
        mChatSendButton = (Button) findViewById(R.id.btn_chat_send);
        mShakeBtn = (ImageButton) findViewById(R.id.aurora_menuitem_ib_shake);
        mRedPackageBtn = (ImageButton) findViewById(R.id.aurora_menuitem_ib_red);
        mGifBtn = (ImageButton) findViewById(R.id.aurora_menuitem_ib_gif);
        mVideoBtn = (ImageButton) findViewById(R.id.aurora_menuitem_ib_video);

        aurora_menuitem_iv_voicedictate = findViewById(R.id.aurora_menuitem_iv_voicedictate);
        aurora_menuitem_iv_voicedictate.setOnClickListener(onMenuItemClickListener);
        if (!isSupportRecognizeVoiceSend) {
            aurora_menuitem_iv_voicedictate.setVisibility(View.GONE);
        }

        voiceBtnContainer = findViewById(R.id.aurora_framelayout_menuitem_voice);
        photoBtnContainer = findViewById(R.id.aurora_framelayout_menuitem_photo);
        mCameraBtnContainer = findViewById(R.id.aurora_ll_menuitem_camera_container);
        emojiBtnContainer = findViewById(R.id.aurora_framelayout_menuitem_emoji);
        shakeBtnContainer = findViewById(R.id.aurora_framelayout_menuitem_shake);
        redPackageContainer = findViewById(R.id.aurora_framelayout_menuitem_red);
        gifContainer = findViewById(R.id.aurora_framelayout_menuitem_gif);
        addContainer = findViewById(R.id.aurora_framelayout_menuitem_add);
        videoContainer = findViewById(R.id.aurora_framelayout_menuitem_video);
        voiceBtnContainer.setOnClickListener(onMenuItemClickListener);
        photoBtnContainer.setOnClickListener(onMenuItemClickListener);
        mCameraBtnContainer.setOnClickListener(onMenuItemClickListener);
        emojiBtnContainer.setOnClickListener(onMenuItemClickListener);

        shakeBtnContainer.setOnClickListener(onMenuItemClickListener);
        redPackageContainer.setOnClickListener(onMenuItemClickListener);
        gifContainer.setOnClickListener(onMenuItemClickListener);
        addContainer.setOnClickListener(onMenuItemClickListener);
        videoContainer.setOnClickListener(onMenuItemClickListener);
        mChatSendButton.setOnClickListener(onMenuItemClickListener);


        mSendCountTv = (TextView) findViewById(R.id.aurora_menuitem_tv_send_count);
        mInputMarginLeft = (Space) findViewById(R.id.aurora_input_margin_left);
        mInputMarginRight = (Space) findViewById(R.id.aurora_input_margin_right);
        mChatInputContainer = (LinearLayout) findViewById(R.id.aurora_ll_input_container);
        mMenuItemContainer = (LinearLayout) findViewById(R.id.aurora_ll_menuitem_container);
        mMenuContainer = (FrameLayout) findViewById(R.id.aurora_fl_menu_container);


        recordVoiceView = findViewById(R.id.voiceVoiew);
        mCameraFl = (FrameLayout) findViewById(R.id.aurora_fl_camera_container);
        mTextureView = (TextureView) findViewById(R.id.aurora_txtv_camera_texture);
        mCloseBtn = (ImageButton) findViewById(R.id.aurora_ib_camera_close);
        mFullScreenBtn = (ImageButton) findViewById(R.id.aurora_ib_camera_full_screen);
        mRecordVideoBtn = (ImageButton) findViewById(R.id.aurora_ib_camera_record_video);
        mCaptureBtn = (ImageButton) findViewById(R.id.aurora_ib_camera_capture);
        mSwitchCameraBtn = (ImageButton) findViewById(R.id.aurora_ib_camera_switch);


        //mSelectPhotoView = (SelectPhotoView) findViewById(R.id.aurora_view_selectphoto);
        mPickPhotoView = (JFMessagePicturePickView) findViewById(R.id.aurora_view_selectphoto1);
        mPickPhotoView.setOnPicSendListener(this);


        mSelectAlbumIb = (ImageButton) findViewById(R.id.aurora_imagebtn_selectphoto_album);
//        mSelectPhotoView.setOnFileSelectedListener(this);
//        mSelectPhotoView.initData();
        mEmojiView = (EmojiView) findViewById(R.id.aurora_rl_emoji_container);
        mEmojiView.setEditext(mChatInputEditText);

        mShakeView = findViewById(R.id.aurora_rl_shake_container);
        mShakeView.setShakeOnclickListener(this);

        menuMoreView = findViewById(R.id.menu_more_view);
        menuMoreView.setOnMenuMoreItemClickListener(this);
        llSpeakInputLayout = (LinearLayout) findViewById(R.id.ll_speak_input_layout);
        llBanspeakInputLayout = (LinearLayout) findViewById(R.id.ll_banspeak_input_layout);
        tvBanText = (TextView) findViewById(R.id.tv_ban_text);

        //隐藏布局
        mMenuContainer.setVisibility(GONE);
        //文件变化监听
        mChatInputEditText.addTextChangedListener(this);
        //输入框返回键监听
        mChatInputEditText.setOnBackKeyClickListener(new EmoticonsEditText.OnBackKeyClickListener() {
            @Override
            public void onBackKeyClick() {
                if (mMenuContainer.getVisibility() == VISIBLE) {
                    dismissMenuLayout();
                    setAllImageButtonNotSelect();
                } else if (isKeyboardVisible()) {
                    EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInputEditText);
                    setAllImageButtonNotSelect();
                }
                //发送取消 正在输入的消息
                if (chatType == StructFactory.TO_USER_TYPE_PERSONAL && onMenuClickListener != null
                        && EnvSupportManager.isSupportShowInputting()) {
                    IMStruct002 imStruct002 = StructFactory.getInstance().createWhetherBeInputtingImStruct(toUserId, false);
                    onMenuClickListener.onSendStruct002Message(imStruct002);
                }
            }
        });

        //设置触摸事件 触摸editext的时候，下方功能按钮还原默认灰色
        mChatInputEditText.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                setAllImageButtonNotSelect();
                return false;
            }
        });

        mCloseBtn.setOnClickListener(this);
        mFullScreenBtn.setOnClickListener(this);
        mRecordVideoBtn.setOnClickListener(this);
        mCaptureBtn.setOnClickListener(this);
        mSwitchCameraBtn.setOnClickListener(this);

        mInputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        mWindow = ((Activity) context).getWindow();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        mScreenWidth = dm.widthPixels;
        mScreenHeight = dm.heightPixels;

        //设置操作区高度zui小为屏幕1/3+20
        minMenuHeight = mScreenHeight / 3 + 50;
        setMenuContainerHeight(minMenuHeight);

        getViewTreeObserver().addOnPreDrawListener(this);
    }

    private void init(Context context, AttributeSet attrs) {
        init(context);

        mStyle = ChatInputStyle.parse(context, attrs);

//        mChatInputEditText.setMaxLines(mStyle.getInputMaxLines());
//        mChatInputEditText.setHint(mStyle.getInputHint());
//        mChatInputEditText.setText(mStyle.getInputText());
//        mChatInputEditText.setHintTextColor(mStyle.getInputHintColor());
//        mChatInputEditText.setBackgroundResource(mStyle.getInputEditTextBg());
//        mChatInputEditText.setPadding(mStyle.getInputPaddingLeft(), mStyle.getInputPaddingTop(),
//                mStyle.getInputPaddingRight(), mStyle.getInputPaddingBottom());

//        mInputMarginLeft.getLayoutParams().width = mStyle.getInputMarginLeft();
//        mInputMarginRight.getLayoutParams().width = mStyle.getInputMarginRight();
//        mVoiceBtn.setImageResource(mStyle.getVoiceBtnIcon());
//        mVoiceBtn.setBackground(mStyle.getVoiceBtnBg());
//        mPhotoBtn.setBackground(mStyle.getPhotoBtnBg());
//        mPhotoBtn.setImageResource(mStyle.getPhotoBtnIcon());
//        mCameraBtn.setBackground(mStyle.getCameraBtnBg());
//        mCameraBtn.setImageResource(mStyle.getCameraBtnIcon());
//        mSendBtn.setBackground(mStyle.getSendBtnBg());
//        mSendBtn.setImageResource(mStyle.getSendBtnIcon());
//        mSendCountTv.setBackground(mStyle.getSendCountBg());
        mSelectAlbumIb.setVisibility(mStyle.getShowSelectAlbum() ? VISIBLE : INVISIBLE);

        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });


    }

    public void onBackPressed() {
        if (mMenuContainer.getVisibility() == VISIBLE) {
            dismissMenuLayout();
            setAllImageButtonNotSelect();
        }

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
//如果SpData字符串完整性被破坏，移除Spdata和对应的样式
//        if (count == 1 && after == 0) {
//            EmoticonsEditText.SpData[] spDatas = mChatInputEditText.getSpDatas();
//            for (EmoticonsEditText.SpData spData : spDatas) {
//                if (start < spData.getEnd() && start >= spData.getStart()) {
//                    Editable editable = mChatInputEditText.getEditableText();
//                    editable.removeSpan(spData);
//                    if (spData.getCustomSpan() != null) {
//                        editable.removeSpan(spData.getCustomSpan());
//                    }
//                }
//            }
//        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        mInput = s;
        //if (mSelectPhotoView.getSelectFiles() == null || mSelectPhotoView.getSelectFiles().size() == 0) {
        //开启发送按钮动画
        if (s.length() >= 1 && start == 0 && before == 0) { // Starting input
            mChatSendButton.setEnabled(true);
            //triggerSendButtonAnimation(mSendBtn, true, false);
        } else if (s.length() == 0 && before >= 1) { // Clear content
            mChatSendButton.setEnabled(false);
            //triggerSendButtonAnimation(mSendBtn, false, false);
        }
        //if (enableWatcher && count == 1 && s.charAt(s.length() - 1) == "@".charAt(0)) {
        if (enableWatcher && count == 1 && s.charAt(start) == "@".charAt(0)) {
            //@界面
            if (onMentionInputListener != null) {
                onMentionInputListener.onMentionCharacterInput();
            }
        }
        //}
    }

    @Override
    public void afterTextChanged(Editable editable) {
        //输入框没有内容就不发了
        if (TextUtils.isEmpty(editable)) {
            return;
        }
        if ("".equals(editable.toString().trim())) {
            return;
        }
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - lastSendTime > 4 * 1000) {
                lastSendTime = currentTime;
                //发送取消 正在输入的消息
                if (onMenuClickListener != null && EnvSupportManager.isSupportShowInputting()) {
                    IMStruct002 imStruct002 = StructFactory.getInstance().createWhetherBeInputtingImStruct(toUserId, true);
                    onMenuClickListener.onSendStruct002Message(imStruct002);
                }
            }
        }
    }

    public void setEnableWatcher(boolean enableWatcher) {
        this.enableWatcher = enableWatcher;
    }

    public EditText getInputView() {
        return mChatInputEditText;
    }

    private OnClickListener onMenuItemClickListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (banSpeak) {
                //如果禁言中。 不允许点击菜单
                return;
            }
            if (view.getId() == R.id.btn_chat_send) {
                // 允许同时发送文本和图片
                if (onSubmit()) {
                    mChatInputEditText.setText("");
                }
                // if (mSelectPhotoView.getSelectFiles() != null && mSelectPhotoView.getSelectFiles().size() > 0) {
                // onMenuClickListener.onSendFiles(mSelectPhotoView.getSelectFiles());

//                    mSendBtn.setImageDrawable(ContextCompat.getDrawable(getContext(),
//                            R.drawable.aurora_menuitem_send));

//                mSendCountTv.setVisibility(View.INVISIBLE);
//                // mSelectPhotoView.resetCheckState();
//                dismissMenuLayout();
//                mInputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0);
//                mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                // }

            } else {
                mChatInputEditText.clearFocus();
                if (view.getId() == R.id.aurora_framelayout_menuitem_voice) {
                    //点击录音按钮
                    if (onMenuClickListener != null && onMenuClickListener.switchToMicrophoneMode()) {
                        if (recordVoiceView.getVisibility() == VISIBLE && mMenuContainer.getVisibility() == VISIBLE) {
                            dismissMenuLayout();
                            setAllImageButtonNotSelect();
                        } else if (isKeyboardVisible()) {
                            //在显示menu
                            mPendingShowMenu = true;
                            EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInputEditText);
                            showRecordVoiceLayout();
                            setImageButtonSelected(mVoiceBtn);

                        } else {
                            setImageButtonSelected(mVoiceBtn);

                            showMenuLayout();
                            showRecordVoiceLayout();
                        }
                    }
                } else if (view.getId() == R.id.aurora_framelayout_menuitem_photo) {
                    //点击选图按钮
                    if (onMenuClickListener != null && onMenuClickListener.switchToGalleryMode()) {
                        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        if (mPickPhotoView.getVisibility() == VISIBLE && mMenuContainer.getVisibility() == VISIBLE) {
                            dismissMenuLayout();
                            setAllImageButtonNotSelect();
                        } else if (isKeyboardVisible()) {
                            mPendingShowMenu = true;
                            mPickPhotoView.refreshPickView();
                            EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInputEditText);
                            setImageButtonSelected(mPhotoBtn);
                            showSelectPhotoLayout();
                        } else {
                            mPickPhotoView.refreshPickView();
                            setImageButtonSelected(mPhotoBtn);
                            showMenuLayout();
                            showSelectPhotoLayout();
                        }
                    }
                } else if (view.getId() == R.id.aurora_ll_menuitem_camera_container) {
                    //点击拍照按钮
                    if (onMenuClickListener != null && onMenuClickListener.switchToCameraMode()) {
                        takePicByCamera();
                    }
                } else if (view.getId() == R.id.aurora_framelayout_menuitem_emoji) {
                    //点击表情按钮
                    if (onMenuClickListener != null && onMenuClickListener.switchToEmojiMode()) {
                        if (mEmojiView.getVisibility() == VISIBLE && mMenuContainer.getVisibility() == VISIBLE) {
                            dismissMenuLayout();
                            setAllImageButtonNotSelect();
                        } else if (isKeyboardVisible()) {
                            mPendingShowMenu = true;
                            EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInputEditText);
                            showEmojiLayout();
                            setImageButtonSelected(mEmojiBtn);
                        } else {
                            setImageButtonSelected(mEmojiBtn);
                            showMenuLayout();
                            showEmojiLayout();
                        }
                    }
                } else if (view.getId() == R.id.aurora_framelayout_menuitem_shake) {
                    //点击抖一抖按钮
                    if (onMenuClickListener != null) {
                        if (mShakeView.getVisibility() == VISIBLE && mMenuContainer.getVisibility() == VISIBLE) {
                            dismissMenuLayout();
                            setAllImageButtonNotSelect();
                        } else if (isKeyboardVisible()) {
                            mPendingShowMenu = true;
                            EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInputEditText);
                            showShakeLayout();
                            setImageButtonSelected(mShakeBtn);
                        } else {
                            setImageButtonSelected(mShakeBtn);
                            showMenuLayout();
                            showShakeLayout();
                        }
                    }
                } else if (view.getId() == R.id.aurora_framelayout_menuitem_add) {
                    //点击add图标 切换蓝色 并开始动画
                    if (menuMoreView.getVisibility() == VISIBLE && mMenuContainer.getVisibility() == VISIBLE) {
                        //动画

                        dismissMenuLayout();
                        setAllImageButtonNotSelect();
                        startAddViewRotationAnimation(135, 0, 300);

                    } else if (isKeyboardVisible()) {
                        //动画
                        mPendingShowMenu = true;
                        EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInputEditText);
                        showMenuMoreLayout();
                        setImageButtonSelected(mAddButton);
                        startAddViewRotationAnimation(0, 135, 300);

                    } else {
                        setImageButtonSelected(mAddButton);
                        showMenuLayout();
                        showMenuMoreLayout();
                        startAddViewRotationAnimation(0, 135, 300);

                    }

                } else if (view.getId() == R.id.aurora_framelayout_menuitem_video) {
                    //视频
                    //ToastUtil.showToast(mContext.getApplicationContext(), "录制视频");
                    // 点击摄像图标
                    Intent intent = new Intent(mContext, RecorderActivity.class);
                    if (isFragment) {
                        loadFragment.startActivityForResult(intent, ChatInputView.REQUEST_CODE_SELECT_VIDEO);
                        ((Activity) mContext).overridePendingTransition(R.anim.push_bottom_in, R.anim.push_top_out);
                    } else {
                        ((Activity) mContext).startActivityForResult(intent, ChatInputView.REQUEST_CODE_SELECT_VIDEO);
                        ((Activity) mContext).overridePendingTransition(R.anim.push_bottom_in, R.anim.push_top_out);
                    }

                    //语音听写按钮的点击事件
                } else if (view.getId() == R.id.aurora_menuitem_iv_voicedictate) {
                    //先检查录音权限
                    if (!EasyPermissionUtils.checkAudioPermission()) {
                        EasyPermissionUtils.requestAudioPermission((Activity) mContext);
                        return;
                    }

                    dismissMenuLayout();
                    setAllImageButtonNotSelect();


                    //先停止播放语音
                    if (ChatVoicePlayClickListener.currentPlayListener != null && ChatVoicePlayClickListener.isPlaying) {
                        ChatVoicePlayClickListener.currentPlayListener.stopPlayVoice();
                        EventBus.getDefault().post(new VoicePlayingEvent(false));
                    }
                    ChatVoicePlayClickListener.currentPlayListener = null;

                    final int[] viewLocation = new int[2];

                    if (isKeyboardVisible()) {
                        //隐藏键盘需要延时显示pop 否则位置获取错误
                        EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInputEditText);
                        isShowPop = true;
                        //监听键盘隐藏打开动作
                        ((Activity) mContext).getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new onInputLayoutChangeListener(((Activity) mContext).getWindow().getDecorView()) {
                            @Override
                            public void onLayoutChange(int intputTop, int windowHeight) {
                                //当inputTop == windowheight的时候  说明软件盘收起
                                if (intputTop == windowHeight && isShowPop == true) {
                                    isShowPop = false;
                                    aurora_menuitem_iv_voicedictate.getLocationInWindow(viewLocation);
                                    voiceDictatePopManager.showTopPopWindow(aurora_menuitem_iv_voicedictate, viewLocation[1], "", true);
                                    ((Activity) mContext).getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
                                }
                            }
                        });
                    } else {
                        aurora_menuitem_iv_voicedictate.getLocationInWindow(viewLocation);
                        voiceDictatePopManager.showTopPopWindow(aurora_menuitem_iv_voicedictate, viewLocation[1], "", true);
                    }

                }
            }
        }
    };

    //+号按钮的动画
    private void startAddViewRotationAnimation(int start, int end, int duration) {
//        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mAddButton, "rotation", start, end);
//        objectAnimator.setDuration(duration);
//        objectAnimator.start();
    }

    @Override
    public void onClick(View view) {
//
//        if (view.getId() == R.id.aurora_ib_camera_full_screen) {
//            // full screen/recover screen button in texture view
//            if (!mIsFullScreen) {
//                if (mCameraControllerListener != null) {
//                    mCameraControllerListener.onFullScreenClick();
//                }
//                //fullScreen();
//            } else {
//                if (mCameraControllerListener != null) {
//                    mCameraControllerListener.onRecoverScreenClick();
//                }
//                recoverScreen();
//            }
//
//        } else if (view.getId() == R.id.aurora_ib_camera_record_video) {
//            // click record video button
//            // if it is not record video mode
//            if (mCameraControllerListener != null) {
//                mCameraControllerListener.onSwitchCameraModeClick(!mIsRecordVideoMode);
//            }
//            if (!mIsRecordVideoMode) {
//                mIsRecordVideoMode = true;
//                mCaptureBtn.setBackgroundResource(R.drawable.aurora_preview_record_video_start);
//                mRecordVideoBtn.setBackgroundResource(R.drawable.aurora_preview_camera);
//                // fullScreen();
//                mCloseBtn.setVisibility(VISIBLE);
//            } else {
//                mIsRecordVideoMode = false;
//                mRecordVideoBtn.setBackgroundResource(R.drawable.aurora_preview_record_video);
//                mCaptureBtn.setBackgroundResource(R.drawable.aurora_menuitem_send_pres);
//                mFullScreenBtn.setBackgroundResource(R.drawable.aurora_preview_recover_screen);
//                mFullScreenBtn.setVisibility(VISIBLE);
//                mCloseBtn.setVisibility(GONE);
//            }
//
//        }
//        else if (view.getId() == R.id.aurora_ib_camera_capture) {
//            // click capture button in preview camera view
//            // is record video mode
//            if (mIsRecordVideoMode) {
//                if (!mIsRecordingVideo) {   // start recording
//                    mCameraSupport.startRecordingVideo();
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            mCaptureBtn.setBackgroundResource(R.drawable.aurora_preview_record_video_stop);
//                            mRecordVideoBtn.setVisibility(GONE);
//                            mSwitchCameraBtn.setVisibility(GONE);
//                            mCloseBtn.setVisibility(VISIBLE);
//                        }
//                    }, 200);
//                    mIsRecordingVideo = true;
//
//                } else {    // finish recording
//                    mVideoFilePath = mCameraSupport.finishRecordingVideo();
//                    mIsRecordingVideo = false;
//                    mIsRecordVideoMode = false;
//                    mFinishRecordingVideo = true;
//                    mCaptureBtn.setBackgroundResource(R.drawable.aurora_menuitem_send_pres);
//                    mRecordVideoBtn.setVisibility(GONE);
//                    mSwitchCameraBtn.setBackgroundResource(R.drawable.aurora_preview_delete_video);
//                    mSwitchCameraBtn.setVisibility(VISIBLE);
//                    if (mVideoFilePath != null) {
//                        playVideo();
//                    }
//                }
//                // if finished recording video, send it
//            } else if (mFinishRecordingVideo) {
//                if (onMenuClickListener != null && mVideoFilePath != null) {
//                    File file = new File(mVideoFilePath);
//                    VideoItem video = new VideoItem(mVideoFilePath, file.getName(), file.length() + "", System.currentTimeMillis() + "", mMediaPlayer.getDuration() / 1000);
//                    List<FileItem> list = new ArrayList<>();
//                    list.add(video);
//                    onMenuClickListener.onSendFiles(list);
//                    mVideoFilePath = null;
//                }
//                mFinishRecordingVideo = false;
//                mMediaPlayer.stop();
//                mMediaPlayer.release();
//                recoverScreen();
//                dismissMenuLayout();
//                // take picture and send it
//            } else {
//                mCameraSupport.takePicture();
//            }
//        } else if (view.getId() == R.id.aurora_ib_camera_close) {
//            try {
//                if (mCameraControllerListener != null) {
//                    mCameraControllerListener.onCloseCameraClick();
//                }
//                mMediaPlayer.stop();
//                mMediaPlayer.release();
//                if (mCameraSupport != null) {
//                    mCameraSupport.cancelRecordingVideo();
//                }
//            } catch (IllegalStateException e) {
//                e.printStackTrace();
//            }
//            recoverScreen();
//            dismissMenuLayout();
//            mIsRecordVideoMode = false;
//            mIsRecordingVideo = false;
//            if (mFinishRecordingVideo) {
//                mFinishRecordingVideo = false;
//            }
//        } else if (view.getId() == R.id.aurora_ib_camera_switch) {
//            if (mFinishRecordingVideo) {
//                mCameraSupport.cancelRecordingVideo();
//                mSwitchCameraBtn.setBackgroundResource(R.drawable.aurora_preview_switch_camera);
//                mRecordVideoBtn.setBackgroundResource(R.drawable.aurora_preview_camera);
//                mRecordVideoBtn.setVisibility(VISIBLE);
//                mVideoFilePath = null;
//                mFinishRecordingVideo = false;
//                mIsRecordVideoMode = true;
//                mCaptureBtn.setBackgroundResource(R.drawable.aurora_preview_record_video_start);
//                mMediaPlayer.stop();
//                mMediaPlayer.release();
//                mCameraSupport.open(mCameraId, mScreenWidth, mScreenHeight, mIsBackCamera);
//            } else {
//                for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
//                    Camera.CameraInfo info = new Camera.CameraInfo();
//                    Camera.getCameraInfo(i, info);
//                    if (mIsBackCamera) {
//                        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
//                            mCameraId = i;
//                            mIsBackCamera = false;
//                            mCameraSupport.release();
//                            mCameraSupport.open(mCameraId, mTextureView.getWidth(),
//                                    mTextureView.getHeight(), mIsBackCamera);
//                            break;
//                        }
//                    } else {
//                        if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
//                            mCameraId = i;
//                            mIsBackCamera = true;
//                            mCameraSupport.release();
//                            mCameraSupport.open(mCameraId, mTextureView.getWidth(),
//                                    mTextureView.getHeight(), mIsBackCamera);
//                            break;
//                        }
//                    }
//                }
//            }
//        }
    }

    /**
     * 照相获取图片
     */
    public void takePicByCamera() {
        if (!CommonUtils.isExitsSdcard()) {
            Toast.makeText(mContext.getApplicationContext(), "SD卡不存在，不能拍照", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
//        Toast.makeText(AppContext.getInstance(), "打开相机", Toast.LENGTH_SHORT)
//                .show();
        cameraFile = FileUtils.createTmpFile(mContext);
        // 跳转到系统照相机
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(mContext.getPackageManager()) != null) {
            // 设置系统相机拍照后的输出路径

            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    UriUtils.getUriForFile(cameraFile));
            if (isFragment) {
                loadFragment.startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA);
                mContext.sendBroadcast(
                        new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
                                .fromFile(cameraFile)));// 刷新系统相册
            } else {
                ((Activity) mContext).startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA);
                mContext.sendBroadcast(
                        new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
                                .fromFile(cameraFile)));// 刷新系统相册
            }

        } else {
            Toast.makeText(mContext, R.string.msg_no_camera,
                    Toast.LENGTH_SHORT).show();
        }
    }

    private void playVideo() {
        try {
            mCameraSupport.release();
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setDataSource(mVideoFilePath);
            Surface surface = new Surface(mTextureView.getSurfaceTexture());
            mMediaPlayer.setSurface(surface);
            surface.release();
            mMediaPlayer.setLooping(true);
            mMediaPlayer.prepareAsync();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void setAudioPlayByEarPhone(int state) {
        AudioManager audioManager = (AudioManager) getContext()
                .getSystemService(Context.AUDIO_SERVICE);
        int currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
        audioManager.setMode(AudioManager.MODE_IN_CALL);
        if (state == 0) {
            mIsEarPhoneOn = false;
            audioManager.setSpeakerphoneOn(true);
            audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                    audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
                    AudioManager.STREAM_VOICE_CALL);
        } else {
            mIsEarPhoneOn = true;
            audioManager.setSpeakerphoneOn(false);
            audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, currVolume,
                    AudioManager.STREAM_VOICE_CALL);
        }
    }

    public void initCamera() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mCameraSupport = new CameraNew(getContext(), mTextureView);
        } else {
            mCameraSupport = new CameraOld(getContext(), mTextureView);
        }
        ViewGroup.LayoutParams params = mTextureView.getLayoutParams();
        params.height = mSoftKeyboardHeight == 0 ? menuLayoutHeight : mSoftKeyboardHeight;
        mTextureView.setLayoutParams(params);
        Log.e(TAG, "TextureView height: " + mTextureView.getHeight());
        mCameraSupport.setCameraCallbackListener(mCameraListener);
        mCameraSupport.setCameraEventListener(this);
        for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                mCameraId = i;
                break;
            }
        }
        if (mTextureView.isAvailable()) {
            mCameraSupport.open(mCameraId, mScreenWidth, menuLayoutHeight, mIsBackCamera);
        } else {
            mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
                @Override
                public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
                    Log.d("ChatInputView", "Opening camera");
                    if (mCameraSupport == null) {
                        initCamera();
                    } else {
                        mCameraSupport.open(mCameraId, width, height, mIsBackCamera);
                    }

                }

                @Override
                public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width,
                                                        int height) {
                    Log.d("ChatInputView", "Texture size changed, Opening camera");
                    if (mTextureView.getVisibility() == VISIBLE && mCameraSupport != null) {
                        mCameraSupport.open(mCameraId, width, height, mIsBackCamera);
                    }
                }

                @Override
                public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
                    if (null != mCameraSupport) {
                        mCameraSupport.release();
                    }
                    return false;
                }

                @Override
                public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

                }
            });
        }
    }

    /**
     * Full screen mode
     */
    private void fullScreen() {
        // hide top status bar
        Activity activity = (Activity) getContext();
        WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        activity.getWindow().setAttributes(attrs);
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        mFullScreenBtn.setBackgroundResource(R.drawable.aurora_preview_recover_screen);
        mFullScreenBtn.setVisibility(VISIBLE);
        mChatInputContainer.setVisibility(GONE);
        mMenuItemContainer.setVisibility(GONE);
        int height = mScreenHeight;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Display display = mWindow.getWindowManager().getDefaultDisplay();
            DisplayMetrics dm = getResources().getDisplayMetrics();
            display.getRealMetrics(dm);
            height = dm.heightPixels;
        }
        MarginLayoutParams marginParams1 = new MarginLayoutParams(mCaptureBtn.getLayoutParams());
        marginParams1.setMargins(marginParams1.leftMargin, marginParams1.topMargin, marginParams1.rightMargin, dp2px(40));
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(marginParams1);
        params.gravity = Gravity.BOTTOM | Gravity.CENTER;
        mCaptureBtn.setLayoutParams(params);

        MarginLayoutParams marginParams2 = new MarginLayoutParams(mRecordVideoBtn.getLayoutParams());
        marginParams2.setMargins(dp2px(20), marginParams2.topMargin, marginParams2.rightMargin, dp2px(48));
        FrameLayout.LayoutParams params2 = new FrameLayout.LayoutParams(marginParams2);
        params2.gravity = Gravity.BOTTOM | Gravity.START;
        mRecordVideoBtn.setLayoutParams(params2);

        MarginLayoutParams marginParams3 = new MarginLayoutParams(mSwitchCameraBtn.getLayoutParams());
        marginParams3.setMargins(marginParams3.leftMargin, marginParams3.topMargin, dp2px(20), dp2px(48));
        FrameLayout.LayoutParams params3 = new FrameLayout.LayoutParams(marginParams3);
        params3.gravity = Gravity.BOTTOM | Gravity.END;
        mSwitchCameraBtn.setLayoutParams(params3);

        mMenuContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, height));
        mTextureView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height));
        mIsFullScreen = true;
    }

    public int dp2px(float value) {
        float scale = getResources().getDisplayMetrics().density;
        return (int) (value * scale + 0.5f);
    }

    /**
     * Recover screen
     */
    @Deprecated
    private void recoverScreen() {
        final Activity activity = (Activity) getContext();
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
                attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                activity.getWindow().setAttributes(attrs);
                activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                mIsFullScreen = false;
                mIsRecordingVideo = false;
                mIsRecordVideoMode = false;
                mCloseBtn.setVisibility(GONE);
                mFullScreenBtn.setBackgroundResource(R.drawable.aurora_preview_full_screen);
                mFullScreenBtn.setVisibility(VISIBLE);
                mChatInputContainer.setVisibility(VISIBLE);
                mMenuItemContainer.setVisibility(VISIBLE);
                int height = menuLayoutHeight;
                if (mSoftKeyboardHeight != 0) {
                    height = mSoftKeyboardHeight;
                }
                setMenuContainerHeight(height);
                ViewGroup.LayoutParams params = new FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, height);
                mTextureView.setLayoutParams(params);
                mRecordVideoBtn.setBackgroundResource(R.drawable.aurora_preview_record_video);
                mRecordVideoBtn.setVisibility(VISIBLE);
                mSwitchCameraBtn.setBackgroundResource(R.drawable.aurora_preview_switch_camera);
                mSwitchCameraBtn.setVisibility(VISIBLE);
                mCaptureBtn.setBackgroundResource(R.drawable.aurora_menuitem_send_pres);

                MarginLayoutParams marginParams1 = new MarginLayoutParams(mCaptureBtn.getLayoutParams());
                marginParams1.setMargins(marginParams1.leftMargin, marginParams1.topMargin, marginParams1.rightMargin, dp2px(12));
                FrameLayout.LayoutParams params1 = new FrameLayout.LayoutParams(marginParams1);
                params1.gravity = Gravity.BOTTOM | Gravity.CENTER;
                mCaptureBtn.setLayoutParams(params1);

                MarginLayoutParams marginParams2 = new MarginLayoutParams(mRecordVideoBtn.getLayoutParams());
                marginParams2.setMargins(dp2px(20), marginParams2.topMargin, marginParams2.rightMargin, dp2px(20));
                FrameLayout.LayoutParams params2 = new FrameLayout.LayoutParams(marginParams2);
                params2.gravity = Gravity.BOTTOM | Gravity.START;
                mRecordVideoBtn.setLayoutParams(params2);

                MarginLayoutParams marginParams3 = new MarginLayoutParams(mSwitchCameraBtn.getLayoutParams());
                marginParams3.setMargins(marginParams3.leftMargin, marginParams3.topMargin, dp2px(20), dp2px(20));
                FrameLayout.LayoutParams params3 = new FrameLayout.LayoutParams(marginParams3);
                params3.gravity = Gravity.BOTTOM | Gravity.END;
                mSwitchCameraBtn.setLayoutParams(params3);
            }
        });
    }

    public void dismissMenuLayout() {
        mMenuContainer.setVisibility(GONE);
        if (mCameraSupport != null) {
            mCameraSupport.release();
            mCameraSupport = null;
        }
    }

    //设置所有的菜单按钮为不选中
    public void setAllImageButtonNotSelect() {
        mVoiceBtn.setSelected(false);
        mPhotoBtn.setSelected(false);
        mCameraBtn.setSelected(false);
        mEmojiBtn.setSelected(false);
        mAddButton.setSelected(false);
        mShakeBtn.setSelected(false);
        mRedPackageBtn.setSelected(false);
        mGifBtn.setSelected(false);
        mVideoBtn.setSelected(false);
        startAddViewRotationAnimation(0, 0, 300);
        //取消选中的图片
        //mSelectPhotoView.resetCheckState();
//        mVoiceBtn.setImageDrawable(ContextCompat.getDrawable(mContext,R.drawable.qqstyle_icon_menu_record_normal));
//        mPhotoBtn.setImageDrawable(ContextCompat.getDrawable(mContext,R.drawable.qqstyle_icon_menu_image_normal));
//        mCameraBtn.setImageDrawable(ContextCompat.getDrawable(mContext,R.drawable.qqstyle_icon_menu_camera_normal));
//        mShakeBtn.setImageDrawable(ContextCompat.getDrawable(mContext,R.drawable.qqstyle_icon_menu_shake_normal));
//        mEmojiBtn.setImageDrawable(ContextCompat.getDrawable(mContext,R.drawable.qqstyle_icon_menu_emoji_normal));
//        mAddButton.setImageDrawable(ContextCompat.getDrawable(mContext,R.drawable.qqstyle_icon_menu_add_normal));
//        mRedPackageBtn.setImageDrawable(ContextCompat.getDrawable(mContext,R.drawable.qqstyle_icon_menu_redpackage_normal));
//        mGifBtn.setImageDrawable(ContextCompat.getDrawable(mContext,R.drawable.qqstyle_icon_menu_gif_normal));
    }

    /**
     * 设置某一个被选中（先将所有的设置为未选中）
     *
     * @param button
     */
    public void setImageButtonSelected(ImageButton button, int drawable) {
        setAllImageButtonNotSelect();
        button.setSelected(true);
        //  button.setImageDrawable(ContextCompat.getDrawable(mContext,drawable));
    }

    public void setImageButtonSelected(ImageButton button) {
        setAllImageButtonNotSelect();
        button.setSelected(true);
    }

    public void invisibleMenuLayout() {
        mMenuContainer.setVisibility(INVISIBLE);
    }

    public void showMenuLayout() {
        EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInputEditText);
        mMenuContainer.setVisibility(VISIBLE);
    }

    public void showRecordVoiceLayout() {
        mPickPhotoView.setVisibility(GONE);
        mCameraFl.setVisibility(GONE);
        mEmojiView.setVisibility(GONE);
        recordVoiceView.setVisibility(View.VISIBLE);
        menuMoreView.setVisibility(GONE);
        mShakeView.setVisibility(GONE);

    }


    public void showSelectPhotoLayout() {
        recordVoiceView.setVisibility(View.GONE);
        mCameraFl.setVisibility(GONE);
        mEmojiView.setVisibility(GONE);
        mPickPhotoView.setVisibility(VISIBLE);
        menuMoreView.setVisibility(GONE);
        mShakeView.setVisibility(GONE);

    }

    public void dismissPhotoLayout() {
        mPickPhotoView.setVisibility(View.GONE);

    }

    public void showCameraLayout() {
        recordVoiceView.setVisibility(View.GONE);
        mPickPhotoView.setVisibility(GONE);
        mEmojiView.setVisibility(GONE);
        mCameraFl.setVisibility(VISIBLE);
        menuMoreView.setVisibility(GONE);
    }

    public void dismissCameraLayout() {
        if (mCameraSupport != null) {
            mCameraSupport.release();
            mCameraSupport = null;
        }
        mCameraFl.setVisibility(GONE);
        ViewGroup.LayoutParams params =
                new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, menuLayoutHeight);
        mTextureView.setLayoutParams(params);
    }

    public void showEmojiLayout() {
        recordVoiceView.setVisibility(View.GONE);
        mPickPhotoView.setVisibility(GONE);
        mCameraFl.setVisibility(GONE);
        mEmojiView.setVisibility(VISIBLE);
        menuMoreView.setVisibility(GONE);
        mShakeView.setVisibility(GONE);

    }

    public void showShakeLayout() {
        recordVoiceView.setVisibility(View.GONE);
        mPickPhotoView.setVisibility(GONE);
        mCameraFl.setVisibility(GONE);
        mEmojiView.setVisibility(GONE);
        menuMoreView.setVisibility(GONE);
        mShakeView.setVisibility(VISIBLE);
    }

    public void showMenuMoreLayout() {
        recordVoiceView.setVisibility(View.GONE);
        mPickPhotoView.setVisibility(GONE);
        mCameraFl.setVisibility(GONE);
        mEmojiView.setVisibility(GONE);
        menuMoreView.setVisibility(VISIBLE);
        mShakeView.setVisibility(GONE);

    }

    public void dismissEmojiLayout() {
        mEmojiView.setVisibility(GONE);
    }

    /**
     * Set menu container's height, invoke this method once the menu was initialized.
     *
     * @param height Height of menu, set same height as soft keyboard so that display to perfection.
     */
    public void setMenuContainerHeight(int height) {
        if (height > 0 && height >= minMenuHeight) {
            menuLayoutHeight = height;
            ViewGroup.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, height);
            mMenuContainer.setLayoutParams(params);
            if (mPickPhotoView != null) {
                mPickPhotoView.setImageHeight(menuLayoutHeight);

            }

        }
    }

    private boolean onSubmit() {
        return onMenuClickListener != null && onMenuClickListener.onSendTextMessage(mInput);
    }

    public int getMenuState() {
        return mMenuContainer.getVisibility();
    }

    /**
     * Select photo callback
     */
//    @Override
//    public void onFileSelected() {
//        int size = mSelectPhotoView.getSelectFiles().size();
//        Log.i("ChatInputView", "select file size: " + size);
//        if (mInput.length() == 0 && size == 1) {
//            // triggerSendButtonAnimation(mSendBtn, true, true);
//        } else if (mInput.length() > 0 && mSendCountTv.getVisibility() != View.VISIBLE) {
//            mSendCountTv.setVisibility(View.VISIBLE);
//        }
//        mSendCountTv.setText(String.valueOf(size));
//    }

    /**
     * Cancel select photo callback
     */
//    @Override
//    public void onFileDeselected() {
//        int size = mSelectPhotoView.getSelectFiles().size();
//        Log.i("ChatInputView", "deselect file size: " + size);
//        if (size > 0) {
//            mSendCountTv.setText(String.valueOf(size));
//        } else {
//            mSendCountTv.setVisibility(View.INVISIBLE);
//            if (mInput.length() == 0) {
//                //  triggerSendButtonAnimation(mSendBtn, false, true);
//            }
//        }
//    }

    //选择图片回调
    @Override
    public void onPicSend(LinkedList<String> mSelectedPics, boolean isRawPic) {
        Log.d(TAG, mSelectedPics + " " + isRawPic);
        if (onMenuClickListener != null) {
            List<String> list = new ArrayList<>();
            list.addAll(mSelectedPics);
            onMenuClickListener.onSendFiles(list, isRawPic);

        }
    }

    /**
     * Trigger send button animation
     *
     * @param sendBtn       send button
     * @param hasContent    EditText has content or photos have been selected
     * @param isSelectPhoto check if selecting photos
     */
    private void triggerSendButtonAnimation(final ImageButton sendBtn, final boolean hasContent,
                                            final boolean isSelectPhoto) {
        float[] shrinkValues = new float[]{0.6f};
        AnimatorSet shrinkAnimatorSet = new AnimatorSet();
        shrinkAnimatorSet.playTogether(ObjectAnimator.ofFloat(sendBtn, "scaleX", shrinkValues),
                ObjectAnimator.ofFloat(sendBtn, "scaleY", shrinkValues));
        shrinkAnimatorSet.setDuration(100);

        float[] restoreValues = new float[]{1.0f};
        final AnimatorSet restoreAnimatorSet = new AnimatorSet();
        restoreAnimatorSet.playTogether(ObjectAnimator.ofFloat(sendBtn, "scaleX", restoreValues),
                ObjectAnimator.ofFloat(sendBtn, "scaleY", restoreValues));
        restoreAnimatorSet.setDuration(100);

        restoreAnimatorSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
                mSendCountTv.bringToFront();
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
                    requestLayout();
                    invalidate();
                }
//                if (mSelectPhotoView.getSelectFiles() != null && mSelectPhotoView.getSelectFiles().size() > 0) {
//                    mSendCountTv.setVisibility(View.VISIBLE);
//                }
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });

        shrinkAnimatorSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                if (!hasContent && isSelectPhoto) {
                    mSendCountTv.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                if (hasContent) {
                    //mSendBtn.setImageDrawable(ContextCompat.getDrawable(getContext(),
                    //mStyle.getSendBtnPressedIcon()));
                } else {
                    //mSendBtn.setImageDrawable(ContextCompat.getDrawable(getContext(),
                    //R.drawable.aurora_menuitem_send));
                }
                restoreAnimatorSet.start();
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });

        shrinkAnimatorSet.start();
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mCameraSupport != null) {
            mCameraSupport.release();
        }
        mMediaPlayer.release();
        getViewTreeObserver().removeOnPreDrawListener(this);
        mMediaPlayer = null;
    }

    @Override
    public void onWindowVisibilityChanged(int visibility) {
        super.onWindowVisibilityChanged(visibility);
        if (visibility == GONE) {
            if (mCameraSupport != null) {
                mCameraSupport.release();
            }
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        if (hasWindowFocus && mScreenHeight <= 0) {
            this.getRootView().getGlobalVisibleRect(mRect);
            mScreenHeight = mRect.bottom;
            Log.d(TAG, "Window focus changed, height: " + mScreenHeight);
        }
    }

    public boolean isKeyboardVisible() {
        return (getDistanceFromInputToBottom() > 300 && mMenuContainer.getVisibility() == GONE)
                || (getDistanceFromInputToBottom() > (mMenuContainer.getHeight() + 300)
                && mMenuContainer.getVisibility() == VISIBLE);
    }

    @Override
    public void onFinishTakePicture() {
        if (mIsFullScreen) {
            recoverScreen();
        }
    }

    public boolean isFullScreen() {
        return this.mIsFullScreen;
    }

    public void setPendingShowMenu(boolean flag) {
        this.mPendingShowMenu = flag;
    }


    @Override
    public boolean onPreDraw() {
        //即将绘制视图树时执行的回调函数。这时所有的视图都测量完成并确定了框架。 客户端可以使用该方法来调整滚动边框，甚至可以在绘制之前请求新的布局。
        if (mPendingShowMenu) {
            if (isKeyboardVisible()) {
                //todo动态调整键盘高度的代码暂时屏蔽，有点问题 闫庆松 20180415
//                ViewGroup.LayoutParams params = mMenuContainer.getLayoutParams();
//                int distance = getDistanceFromInputToBottom();
//                Log.d(TAG, "Distance from bottom: " + distance);
//                if (distance < mScreenHeight / 2 && distance > 300 && distance != params.height) {
//                    //键盘太高，降低一下
//                    if (distance < minMenuHeight) {
//                        distance = minMenuHeight;
//                    } else {
//                        distance = distance - 20;
//                    }
//                    params.height = distance;
//                    mSoftKeyboardHeight = distance;
//                    mMenuContainer.setLayoutParams(params);
//                }
                return false;
            } else {
                showMenuLayout();
                mPendingShowMenu = false;
                return false;
            }
        } else {
            if (mMenuContainer.getVisibility() == VISIBLE && isKeyboardVisible()) {
                dismissMenuLayout();
                return false;
            }
        }
        return true;
    }


    /**
     * 获取从输入框到底部的距离
     *
     * @return
     */
    public int getDistanceFromInputToBottom() {
        //etGlobalVisibleRect方法的作用是获取视图在屏幕坐标系中的偏移量
        mMenuItemContainer.getGlobalVisibleRect(mRect);
        return mScreenHeight - mRect.bottom;
    }

    private final Runnable measureAndLayout = new Runnable() {
        @Override
        public void run() {
            measure(
                    MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
            layout(getLeft(), getTop(), getRight(), getBottom());
        }
    };

    @Override
    public void requestLayout() {
        super.requestLayout();

        // React Native Override requestLayout, since we refresh our layout in native, RN catch the
        //requestLayout event, so that the view won't refresh at once, we simulate layout here.
        // post(measureAndLayout);
    }

    public int getSoftKeyboardHeight() {
        return mSoftKeyboardHeight > 0 ? mSoftKeyboardHeight : menuLayoutHeight;
    }

    public FrameLayout getCameraContainer() {
        return mCameraFl;
    }

    public LinearLayout getmMenuItemContainer() {
        return mMenuItemContainer;
    }

    public LinearLayout getVoiceContainer() {
        return recordVoiceView;
    }

    public LinearLayout getSelectPictureContainer() {
        return mPickPhotoView;
    }

    public EmojiView getEmojiContainer() {
        return mEmojiView;
    }

    public EmoticonsEditText getmChatInputEditText() {
        return mChatInputEditText;
    }

    public View getCameraBtnContainer() {
        return this.mCameraBtnContainer;
    }

    public ChatInputStyle getStyle() {
        return this.mStyle;
    }

    public ImageButton getVoiceBtn() {
        return this.mVoiceBtn;
    }

    public ImageButton getPhotoBtn() {
        return this.mPhotoBtn;
    }

    public ImageButton getCameraBtn() {
        return this.mCameraBtn;
    }

    public ImageButton getEmojiBtn() {
        return this.mEmojiBtn;
    }

    public Button getSendBtn() {
        return this.mChatSendButton;
    }


    public ImageButton getSelectAlbumBtn() {
        return this.mSelectAlbumIb;
    }

    public MenuMoreView getMenuMoreView() {
        return this.menuMoreView;
    }

    /**
     * 获取语音识别的popowindow是否显示
     *
     * @return
     */
    public boolean getVoiceRecognitionPopWindowIsShown() {
        return voiceDictatePopManager.isShowPop();
    }

    //获取拍摄的照片
    public File getTakePictureFile() {
        return cameraFile;
    }

    //释放一些资源
    public void release() {
        if (voiceDictatePopManager.getPop() != null && voiceDictatePopManager.getPop().isShowing()) {
            voiceDictatePopManager.getPop().dismiss();
        }

    }

    /**
     * 设置光标的drawable
     *
     * @param drawable
     */
    private void setCursor(Drawable drawable) {
        try {
            Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
            f.setAccessible(true);
            f.set(mChatInputEditText, drawable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置menu点击回调
     *
     * @param listener
     */
    public void setMenuClickListener(OnMenuClickListener listener) {
        onMenuClickListener = listener;
    }

    @Deprecated
    public void setOnCameraCallbackListener(OnCameraCallbackListener listener) {
        mCameraListener = listener;
    }

    @Deprecated
    public void setCameraControllerListener(CameraControllerListener listener) {
        mCameraControllerListener = listener;
    }

    @Deprecated
    public void setOnClickEditTextListener(OnClickEditTextListener listener) {
        mEditTextListener = listener;
    }

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

    //设置语音录制回调
    public void setMyRecordVoiceListener(VoiceView.MyRecordVoiceListener listener) {
        this.recordVoiceView.setMyRecordVoiceListener(listener);
    }

    //更多按钮点击 item的监听
    @Override
    public void onMenuItemClick(ChatMenuModel model) {
        if (onMenuClickListener != null) {
            onMenuClickListener.clickMoreMenuItem(model);
        }
    }


    //todo 必须调用这个方法（设置用户menu 菜单权限）
    public void setChatUserInfo(int toUserId, int chatType, String chatPermission) {
        this.toUserId = toUserId;
        this.chatType = chatType;
        if (menuMoreView != null) {
            menuMoreView.setMenuUserInfo(toUserId, chatType, chatPermission);
        }
    }

    //todo 隐藏键盘和menu布局
    public void hideKeyBoardAndMenuContainer() {
        mInputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0);
        mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        dismissMenuLayout();
        setAllImageButtonNotSelect();
    }

    /**
     * todo 设置是否禁言
     *
     * @param banSpeak
     * @param isSingle 是全员还是单独禁言某个人
     */
    public void setBanSpeak(boolean banSpeak, boolean isSingle) {
        this.banSpeak = banSpeak;
        if (banSpeak) {
            llBanspeakInputLayout.setVisibility(View.VISIBLE);
            llSpeakInputLayout.setVisibility(View.GONE);
            //隐藏表情等以及布局
            hideKeyBoardAndMenuContainer();
        } else {
            llBanspeakInputLayout.setVisibility(View.GONE);
            llSpeakInputLayout.setVisibility(View.VISIBLE);
        }
        if (isSingle) {
            tvBanText.setText(R.string.wechat_mute);
        } else {
            tvBanText.setText(R.string.wechat_all_mute);
        }
    }

    @Override
    public void shakeItemOnClick(String type) {
        if (onMenuClickListener != null) {
            onMenuClickListener.onSendShakeAnim(type);
        }
    }

    public void SetFragment(Fragment fragment) {
        if (fragment != null) {
            isFragment = true;
            this.loadFragment = fragment;
            mPickPhotoView.setFragment(fragment);
        }
    }

    /**
     * 设置按钮是否可以点击，解决一个穿透问题
     *
     * @param canClick
     */
    public void setMenuClickbale(boolean canClick) {
        if (canClick) {
            voiceBtnContainer.setClickable(true);
            photoBtnContainer.setClickable(true);
            emojiBtnContainer.setClickable(true);
            shakeBtnContainer.setClickable(true);
            redPackageContainer.setClickable(true);
            addContainer.setClickable(true);
            videoContainer.setClickable(true);
            gifContainer.setClickable(true);
            mCameraBtnContainer.setClickable(true);

        } else {
            voiceBtnContainer.setClickable(false);
            photoBtnContainer.setClickable(false);
            emojiBtnContainer.setClickable(false);
            shakeBtnContainer.setClickable(false);
            redPackageContainer.setClickable(false);
            addContainer.setClickable(false);
            videoContainer.setClickable(false);
            gifContainer.setClickable(false);
            mCameraBtnContainer.setClickable(false);
        }
    }

    public void setOnMentionInputListener(OnMentionInputListener onMentionInputListener) {
        this.onMentionInputListener = onMentionInputListener;
    }

    @Override
    public void onViceDictateSendListener(String content, String voicePath) {
        if (voiceDictateSendListener != null) {
            voiceDictateSendListener.onViceDictateSendListener(content, voicePath);
        }
    }

    public interface OnMentionInputListener {
        /**
         * call when '@' character is inserted into EditText
         */
        void onMentionCharacterInput();
    }

    private VoiceDictateSendListener voiceDictateSendListener;

    public void setVoiceDictateSendListener(VoiceDictateSendListener voiceDictateSendListener) {
        this.voiceDictateSendListener = voiceDictateSendListener;
    }
}
