package com.baidu.ai.sample;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.ai.sample.adapter.ChatBeanAdapter;
import com.baidu.ai.sample.data.ChatBean;
import com.baidu.ai.sample.util.UIUtils;
import com.baidu.rtc.RTCVideoView;

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

/**
 * 大模型语音对话 + 数字人
 */
public class AiDigitalHumanActivity extends AiChatBaseActivity {
    private static final String TAG = "AiDigitalHumanActivity";
    private ListView mListView;
    private FrameLayout mVideoContainer;
    private TextView mChatView;
    private ArrayList<ChatBean> mData = null;
    private ChatBeanAdapter chatAdapter = null;
    private EditText mInputText;
    private boolean mIsMicMute = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ai_digital_human);
        mStartPath = HttpClient.DH_START_PATH;
        mStopPath = HttpClient.DH_STOP_PATH;
        /** TODO: 配置形象id */
        mClientData.mFigureId = "209403";
        setupAgent();
    }

    @Override
    protected void initAllViews() {
        ((TextView) findViewById(R.id.tv_instance_name)).setText(
                String.format("instance_id：%s", mClientData.mInstanceId));

        mVideoContainer = findViewById(R.id.video_container);
        mInputText = (EditText) findViewById(R.id.input_text);
        mInputText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    // 获取输入内容
                    String inputText = mInputText.getText().toString().trim();

                    aiController.sendText(inputText);
                    mData.add(new ChatBean(true,  inputText));
                    chatAdapter.notifyDataSetChanged();

                    mInputText.setText("");
                    hideInput(mInputText);
                    return true;

                }
                return false;
            }
        });

        findViewById(R.id.mute_call_imageview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mIsMicMute = !mIsMicMute;
                aiController.muteMic(mIsMicMute);
                ImageView iv = null;
                if (view instanceof ImageView) {
                    iv = (ImageView) view;
                }
                if (mIsMicMute) {
                    if (iv != null) {
                        iv.setImageDrawable(getDrawable(R.drawable.microphone_off));
                    }
                } else {
                    if (iv != null) {
                        iv.setImageDrawable(getDrawable(R.drawable.microphone_on));
                    }
                }
            }
        });
        findViewById(R.id.go_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AiDigitalHumanActivity.this.finish();
            }
        });

        LinearLayout toolsBottom = findViewById(R.id.listview_chat_tool);
        LinearLayout bottomActions = findViewById(R.id.bottom_actions);
        int maxHeight = UIUtils.dp2px(this, 152);
        int minHeight = UIUtils.dp2px(this, 72);
        findViewById(R.id.more_imageview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int startHeight = toolsBottom.getHeight();
                boolean showBottom = startHeight >= maxHeight;
                int endHeight = startHeight >= maxHeight ? minHeight : maxHeight;
                bottomActions.setVisibility(showBottom ? View.GONE : View.VISIBLE);
                ValueAnimator animator = ValueAnimator.ofInt(startHeight, endHeight);
                animator.setDuration(300); // 动画持续时间
                animator.addUpdateListener(animation -> {
                    int animatedValue = (int) animation.getAnimatedValue();
                    toolsBottom.getLayoutParams().height = animatedValue;
                    toolsBottom.requestLayout(); // 重新布局
                });
                animator.start();
            }
        });

        findViewById(R.id.camera_imageview).setVisibility(View.GONE);
//        findViewById(R.id.camera_imageview).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                RTCVideoView videoView = aiController.getLocalVideoView();
//
//                if (videoView == null) {
//                    return;
//                }
//                if (mCameraIsMute) {
//                    mVideoContainer.removeView(videoView);
//                } else {
//                    mVideoContainer.addView(videoView);
//                }
//                aiController.muteCamera(mCameraIsMute);
//                mCameraIsMute = !mCameraIsMute;
//            }
//        });

        findViewById(R.id.upload_imageview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                mStartIntentResult.startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_IMAGE_CODE);
            }
        });
        findViewById(R.id.pause_call_imageview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                aiController.interrupt();
            }
        });

        findViewById(R.id.speaker_switch_imageview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSpeakerIsMute = !mSpeakerIsMute;
                aiController.mutePlayback(mSpeakerIsMute);
                ImageView iv = null;
                if (view instanceof ImageView) {
                    iv = (ImageView) view;
                    int id = mSpeakerIsMute ? R.drawable.btn_speaker_off : R.drawable.btn_speaker_on;
                    iv.setImageDrawable(getDrawable(id));
                }
            }
        });

        mData = new ArrayList<ChatBean>();
        if (TextUtils.isEmpty(mClientData.mSay)) {
            mData.add(new ChatBean(false,  "你好呀，你来了!"));
        }

        mListView = (ListView) findViewById(R.id.listview_chat);
        chatAdapter = new ChatBeanAdapter(this, mData, true);
        mListView.setAdapter(chatAdapter);

        mChatView = findViewById(R.id.tv_chat_view);
        mChatView.setVisibility(View.INVISIBLE);
        aiController.setDigitalDisplay(mVideoContainer,
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT),
                RTCVideoView.ScalingType.SCALE_ASPECT_FIT);
    }

    /** 相机未打开 */
    private boolean mCameraIsMute = false;
    /** 播放是否mute */
    private boolean mSpeakerIsMute = false;
    private void initPopView(View rootView) {
        ((ImageView) rootView.findViewById(R.id.pause_call_imageview)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                aiController.interrupt();
            }
        });



        rootView.findViewById(R.id.switch_camera_imageview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mCameraIsMute) {
                    Log.w(TAG, "camera is not open!");
                    return;
                }
                aiController.switchCamera();
            }
        });

        rootView.findViewById(R.id.speaker_switch_imageview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSpeakerIsMute = !mSpeakerIsMute;
                aiController.mutePlayback(mSpeakerIsMute);
                ImageView iv = null;
                if (view instanceof ImageView) {
                    iv = (ImageView) view;
                    int id = mSpeakerIsMute ? R.drawable.btn_speaker_off : R.drawable.btn_speaker_on;
                    iv.setImageDrawable(getDrawable(id));
                }
            }
        });
    }

    @Override
    protected void onUIAIAgentSubtitle(String text, boolean isFinal) {
        super.onUIAIAgentSubtitle(text, isFinal);
        Log.i(TAG, "onUIAIAgentSubtitle:" + text + ",is:" + isFinal);
        if (mChatView.getVisibility() != View.VISIBLE) {
            mChatView.setVisibility(View.VISIBLE);
        }
        mChatView.setText("小文:" + text);
    }

    @Override
    protected void onUIAsrSubtitle(String text, boolean isFinal) {
        super.onUIAsrSubtitle(text, isFinal);
        Log.i(TAG, "onUIAsrSubtitle:" + text + ",is:" + isFinal);
        if (mChatView.getVisibility() != View.VISIBLE) {
            mChatView.setVisibility(View.VISIBLE);
        }
        mChatView.setText("我:" + text);
    }

    @Override
    protected void addFileUploadBean(String path) {
        try {
            File file = new File(path);
            ChatBean bean = new ChatBean(true,  "上传图片: " + file.getName());
            bean.imagePath = path;
            mData.add(bean);
            chatAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}