package com.baidu.ai.sample;

import java.io.File;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.baidu.ai.sample.adapter.ChatBeanAdapter;
import com.baidu.ai.sample.appbuilder.AiAppBuilderClient;
import com.baidu.ai.sample.data.ChatBean;
import com.baidu.ai.sample.util.UIUtils;
import com.baidu.rtc.RTCVideoView;
import com.baidu.rtc.agent.Constants;

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.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;

/**
 * AppBuilder大模型语音对话
 */
public class AiABNewsActivity extends AiChatBaseActivity {
    private static final String TAG = "AiABNewsActivity";
    private static final String FUNC_NAME_FH_NEWS = "run_ab_fenghuang_news";
    private ListView mListView;
    private FrameLayout mVideoContainer;
    private ArrayList<ChatBean> mData = null;
    private ChatBeanAdapter chatAdapter = null;
    private EditText mInputText;
    private boolean mIsMicMute = false;
    private String mAppBuilderAppId;
    private String mAppBuilderToken;
    private AiAppBuilderClient mAppBuilderClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ai_chat);
        mAppBuilderAppId = this.getString(R.string.ab_fh_news_app_id);
        mAppBuilderToken = this.getString(R.string.ab_fh_news_app_key);
        if (TextUtils.isEmpty(mAppBuilderAppId) || TextUtils.isEmpty(mAppBuilderToken)) {
            toastMsg("无法使用AppBuilder功能, 请先配置AppBuilder的appId和apiKey!");
        }
        mAppBuilderClient = new AiAppBuilderClient(mAppBuilderAppId, mAppBuilderToken);
        mAppBuilderClient.setOnAppBuilderClientListener(mAppBuilderClientListener);
        setupAgent();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (aiController != null) {
            aiController.interrupt();
        }
    }

    @Override
    protected void onAIAgentGenerated(String instanceId) {
        super.onAIAgentGenerated(instanceId);
        mAppBuilderClient.createConversationAsync();
    }

    @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 || keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    // 获取输入内容
                    String inputText = mInputText.getText().toString().trim();
                    if (TextUtils.isEmpty(inputText)) {
                        return true;
                    }
                    aiController.sendText(inputText);

                    mData.add(new ChatBean(true, inputText));
                    chatAdapter.notifyDataSetChanged();
                    mInputText.setText("");
                    hideInput(mInputText);

                    return true;
                }

                return false;
            }
        });
        mInputText.setText("用凤凰资讯搜索今日新闻");

        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) {
                AiABNewsActivity.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).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);
    }

    /**
     * 相机未打开
     */
    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));
                        }
                    }
                });
    }

    AiAppBuilderClient.OnAppBuilderClientListener mAppBuilderClientListener =
            new AiAppBuilderClient.OnAppBuilderClientListener() {
                @Override
                public void onCreateConversation(boolean succeed, String conversationId) {
                    Log.d(TAG, "onCreateConversation: " + succeed + ", conversationId: "
                            + conversationId);
                    if (succeed) {
                        toastMsg("创建AppBuilder对话成功: conversationId " + conversationId +
                                "，可尝试使用凤凰资讯搜索xxx");
                    } else {
                        toastMsg("创建AppBuilder对话失败, 请检查网络连接是否正常");
                    }
                }

                @Override
                public void onQueryAnswer(boolean succeed, String answer) {
                    Log.d(TAG, "onQueryAnswer: succeed answer: " + answer);
                    if (succeed) {
                        runOnUiThread(() -> onUIAIAgentSubtitle(answer, true));
                        if (!TextUtils.isEmpty(mFuncCallSessionId)) {
                            aiController
                                    .sendFunctionCallResult(mFuncCallSessionId, filterText(answer));
                        }
                    }
                }
            };

    public static String filterText(String text) {
        // 正则表达式匹配括号及其内容
        String regex = "\\([^()]*\\)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        // 替换匹配到的内容为空字符串
        return matcher.replaceAll("");
    }

    private ChatBean mLastAgentBean = null;
    private ChatBean mLastAsrBean = null;

    @Override
    protected void onUIAIAgentSubtitle(String text, boolean isFinal) {
        Log.i(TAG, "onUIAIAgentSubtitle:" + text + ",is:" + isFinal);
        if (!isFinal) {
            if (mLastAgentBean == null) {
                mLastAgentBean = new ChatBean(false, text);
                mData.add(mLastAgentBean);
            } else {
                mLastAgentBean.say += text;
            }
            chatAdapter.notifyDataSetChanged();
            mListView.setSelection(mData.size() - 1);
        } else {
            if (mLastAgentBean != null) {
                mLastAgentBean.say = text;
            } else {
                mData.add(new ChatBean(false, text));
            }
            chatAdapter.notifyDataSetChanged();
            mListView.setSelection(mData.size() - 1);
            mLastAgentBean = null;
        }
    }

    @Override
    protected void onUIAsrSubtitle(String text, boolean isFinal, Constants.ASRExtInfo info) {
        Log.i(TAG, "onUIAsrSubtitle text:" + text + ", isFinal:" + isFinal);
        if (!isFinal) {
            if (mLastAsrBean == null) {
                mLastAsrBean = new ChatBean(true, text);
                mData.add(mLastAsrBean);
            } else {
                mLastAsrBean.say = text;
            }
            chatAdapter.notifyDataSetChanged();
            mListView.setSelection(mData.size() - 1);
        } else {
            if (mLastAsrBean != null) {
                mLastAsrBean.say = text;
                mLastAsrBean.time = ChatBean.getTime();
            } else {
                mData.add(new ChatBean(true, text));
            }
            chatAdapter.notifyDataSetChanged();
            mListView.setSelection(mData.size() - 1);
            mLastAsrBean = null;
        }
    }

    @Override
    protected void addFileUploadBean(int imageUsageScenario, 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();
        }
    }

    @Override
    protected void onFuncCall(String id, String funcName, String content) {
        super.onFuncCall(id, funcName, content);
        if (TextUtils.equals(funcName, FUNC_NAME_FH_NEWS)) {
            Log.d(TAG, "onFuncCall: news:" + content);
            mAppBuilderClient.sendQueryAsync(content);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAppBuilderClient.onDestroy();
    }
}