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.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.CharacterData;
import com.baidu.ai.sample.data.ChatBean;
import com.baidu.ai.sample.util.CharacterDataParser;
import com.baidu.ai.sample.util.UIUtils;
import com.baidu.rtc.RTCVideoView;
import com.baidu.rtc.agent.Constants;

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

/**
 * 大模型语音对话
 */
public class AiChatActivity extends AiChatBaseActivity {
    private static final String TAG = "AiChatActivity";
    private ListView mListView;
    private FrameLayout mVideoContainer;
    private ArrayList<ChatBean> mData = null;
    private ChatBeanAdapter chatAdapter = null;
    private EditText mInputText;
    private boolean mIsMicMute = false;
    private boolean mLiteracychecked = false;
    private int mImageUsageScenario;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ai_chat);
        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 || keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    // 获取输入内容
                    String inputText = mInputText.getText().toString().trim();

                    if (TextUtils.isEmpty(inputText)) {
                        return true;
                    }
                    Log.i(TAG, "onEditorAction == " + inputText);

                    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) {
                AiChatActivity.this.finish();
            }
        });

        LinearLayout toolsBottom = findViewById(R.id.listview_chat_tool);
        LinearLayout bottomActions = findViewById(R.id.bottom_actions);
        int maxHeight = UIUtils.dp2px(this, 160);
        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.upload_refer_image).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_TAKE_REFER_IMAGE_CODE);
            }
        });

        findViewById(R.id.iv_pic_literacy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mLiteracychecked = !mLiteracychecked;
                aiController.updateSystemPrompt(Constants.ModelType.VISION_MODEL,
                        mLiteracychecked ? CharacterPrompt.LITERACY_PROMPT_TEXT : "");
                ImageView iv = null;
                if (view instanceof ImageView) {
                    iv = (ImageView) view;
                    int id = mLiteracychecked ? R.drawable.btn_character_selected
                            : R.drawable.btn_character;
                    iv.setImageDrawable(getDrawable(id));
                }
                if (mLiteracychecked) {
                    toastMsg("已开启拍图识字模式");
                } else {
                    toastMsg("已切换视觉理解模式");
                }
            }
        });
        findViewById(R.id.pause_call_imageview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                aiController.interrupt();
                // aiController.sendTextToTTS("北京欢迎你，我家大门常打开 开放怀抱等你，拥抱过就有了默契 你会爱上这里。");
            }
        });

        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, false);
        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));
                }
            }
        });
    }
    private ChatBean mLastAgentBean = null;
    private ChatBean mLastAsrBean = null;
    private int mImageGeneratePos = -1;
    private HashMap<Long, Integer> mGeneratingImgMap = new HashMap<>();

    @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 + ",info:" + getASRExtInfo(info));
        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 {
            String content = text;
            if (info != null && !TextUtils.isEmpty(info.speakerName)) {
                content += "[" + info.speakerName + "," + info.similarity + "]";
            }
            if (mLastAsrBean != null) {
                mLastAsrBean.say = content;
                mLastAsrBean.time = ChatBean.getTime();
            } else {
                mData.add(new ChatBean(true, content));
            }
            chatAdapter.notifyDataSetChanged();
            mListView.setSelection(mData.size() - 1);
            mLastAsrBean = null;
        }
    }

    @Override
    protected void addFileUploadBean(int imageUsageScenario, String path) {
        try {
            mImageUsageScenario = imageUsageScenario;
            if (imageUsageScenario == Constants.ImageUsageScenario.IMAGE_GENERATE) {
                mInputText.setHint("编辑图片为涂鸦风格？");
            } else if (imageUsageScenario == Constants.ImageUsageScenario.VISION) {
                mInputText.setHint("图片中是什么？");
            }
            File file = new File(path);
            ChatBean bean = new ChatBean(true,  "上传图片: " + file.getName());
            bean.imagePath = path;
            bean.imageUrls = new String[]{path};
            mData.add(bean);
            chatAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void uploadFileStatus(int code, String msg) {
        Log.d(TAG, "onFileUploadStatus, code:" + code + ", msg:" + msg);
        if (code == Constants.NO_ERROR) {
            if (mImageUsageScenario == Constants.ImageUsageScenario.IMAGE_GENERATE) {
                toastMsg("图片上传成功, 试试说：编辑图片为漫画风格!");
            } else {
                toastMsg("图片上传成功, 试试说：图片中是什么？");
            }
        }
    }

    @Override
    protected void mediaGenerateStart(long taskId, String query) {
        try {
            String path = "android.resource://" + getPackageName() + "/" + R.drawable.bg_image_loading;
            ChatBean bean = new ChatBean(true,  "正在创作图片...");
            bean.imagePath = path;
            bean.queryId = taskId;
            mData.add(bean);
            chatAdapter.notifyDataSetChanged();
            int pos  = mData.size() - 1;
            mGeneratingImgMap.put(taskId, pos);
            mListView.setSelection(pos);
            mInputText.setHint("");
            Log.d(TAG, "mediaGenerateStart: " + taskId + ", pos:" + pos);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected  void updateGenerateImage(long taskId, int type, int error,
                                        String msgRes, ArrayList<String> resList) {
        Log.d(TAG, "updateGenerateImage type:" + type + ", pos:"+ mImageGeneratePos
                + ", error:" + error + ", resList:" + resList);
        if (error != Constants.NO_ERROR || resList == null || resList.isEmpty()) {
            toastMsg("生成图片失败");
            return;
        }
        int pos = -1;
        try {
            pos = mGeneratingImgMap.get(taskId);
        } catch (Exception e) {}
        toastMsg("图片已生成: pos:" + pos + ", size:" + resList.size() + ", task:" + taskId + ", urls:" + resList );

        if (pos >= 0) {
            chatAdapter.updateImage(pos, error, resList);
            mGeneratingImgMap.remove(taskId);
        }
    }

    @Override
    protected void onCustomTagMessage(String text, boolean isFinal) {
        Log.i(TAG, "onCustomTagMessage:" + text);
        if (isFinal && CharacterDataParser.hasCustomTag(text)) {
            CharacterData characterData = CharacterDataParser.parseJsonString(text);
            if (characterData != null) {
                ChatBean bean = new ChatBean(false,  "");
                bean.characterData = characterData;
                bean.hasCustomTag = true;
                bean.say =
                        characterData.getCustom().getNameCh() + " / " + characterData.getCustom().getNameEn();
                mData.add(bean);
                chatAdapter.notifyDataSetChanged();
            }
        }
    }

}