package com.xunao.effectdemo.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.xunao.effectdemo.R;
import com.xunao.effectdemo.bean.MediaBean;
import com.xunao.effectdemo.bean.WordTimeBean;
import com.xunao.effectdemo.net.ApiHttpClient;
import com.xunao.effectdemo.net.ApiUrl;
import com.xunao.effectdemo.net.CSMHttpCallback;
import com.xunao.effectdemo.view.SongLyricTextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.xunao.effectdemo.bean.MediaBean.ResultBean.ListBean.*;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

/**
 * author : 程中强
 * e-mail : 740479946@qq.com
 * date : 2022/9/2214:43
 * desc :
 * version: 1.0
 */
public class NewSongLyricActivity extends Activity {

	private SongLyricTextView textView;
	private Button start,stop,test;
	private MediaPlayer mediaPlayer;
	private String TAG = "NewSongLyricActivity";
	private TagFlowLayout flowLayout;

	private String lyric = "你发如雪\n" +
			"凄美了离别\n" +
			"我焚香感动了谁\n" +
			"邀明月让回忆皎洁\n" +
			"爱在月光下完美\n" +
			"你发如雪\n" +
			"纷飞了眼泪\n" +
			"我等待苍老了谁\n" +
			"红尘醉微醺的岁月\n" +
			"我用无悔\n" +
			"刻永世爱你的碑";

	private String token = "MWIzYmVmOTdiYzI5Y2UwM2ZiOThlMTI3YjRmYWJlNzA=";
	private String member_id = "61128";
	private String steps_id = "48671";
	private String student_id = "180721";
	private String[] lyricList;
	private List<StepsLyricjsonBean> wordList = new ArrayList<>();
	private List<String> list = new ArrayList<>();
	private List<String> timeList = new ArrayList<>();
	private List<WordTimeBean> beanList = new ArrayList<>();
	private WordTimeBean timeBean,currBean;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_songe);
		init();
	}

	void init(){
		textView = findViewById(R.id.text);
		start = findViewById(R.id.start);
		stop = findViewById(R.id.end);
		start.setOnClickListener(v->{
			if(mediaPlayer.isPlaying()){
				mediaPlayer.seekTo(0);
			}else{
				mediaPlayer.start();
			}
			startPlay();
		});
		stop.setOnClickListener(v->{
			mediaPlayer.pause();
			textView.stopPlay();
			handler.removeCallbacks(runnable);
		});
		test = findViewById(R.id.test);
		test.setOnClickListener(v->textView.startNormalLine(
				0,
				startIndex));
		mediaPlayer = new MediaPlayer();
		flowLayout = findViewById(R.id.tab_flowlayout);
		getMedia();
//		setFlowData();
	}

	void getMedia(){
		Map<String, String> params = new HashMap<>();
		params.put("member_id",member_id);
		params.put("token",token);
		params.put("student_id",student_id);
		params.put("steps_id",steps_id);
		ApiHttpClient.get(ApiUrl.getMapsStepsMedias,params, new CSMHttpCallback() {
			@Override
			protected void onSuccess(String jsonStr) {
				MediaBean mediaBean = MediaBean.parse(jsonStr);
				wordList = mediaBean.getResult().getList().getSteps_lyricjson();
				setWord(wordList);

				mediaPlayer.setOnPreparedListener(mp -> Log.i(TAG,"onPrepared:准备完成"));
				mediaPlayer.setOnCompletionListener(mp -> Log.i(TAG,"OnCompletion:播放完成"));
				try {
					mediaPlayer.setDataSource(mediaBean.getResult().getList().getSteps_mp3url());
					mediaPlayer.prepareAsync();// 开始在后台缓冲音频文件并返回
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			@Override
			protected void onFail(String msg) {

			}
		});
	}

	private void setWord(List<StepsLyricjsonBean> wordList){
		String msg = "";
		list.clear();
		for (StepsLyricjsonBean bean:wordList) {

			for (int i = 0; i < bean.getWord().size(); i++) {
				String w = bean.getWord().get(i).replaceAll("<i>","\n    ");
				if (w.contains("\n"))Log.e("MyTag","长度"+w.length());
				list.add(w);
				timeList.add(bean.getWordtims().get(i));

				timeBean = new WordTimeBean();
				timeBean.setStartTime(Integer.parseInt(bean.getStarttime()));
				timeBean.setEndTime(Integer.parseInt(bean.getEndtime()));
				timeBean.setWord(w);
				timeBean.setTime(Integer.parseInt(bean.getWordtims().get(i)));
				beanList.add(timeBean);

				msg+=w;
			}
		}
		textView.setText(msg);
		setFlowData();
	}
	private int num = 0;
	private int canTime = 0;
	private int normal = 0;
	private Handler handler = new Handler(){
		@SuppressLint("HandlerLeak")
		@Override
		public void handleMessage(@NonNull Message msg) {
			super.handleMessage(msg);
			switch (msg.what){
				case 1001:
					if (currBean==null){timeBean = beanList.get(num);}
//					Log.e("MyTag","当前:"+timeBean.toString()+"   "+time);
					if (timeBean.getStartTime()+canTime > time&& timeBean.getStartTime() + canTime-time   <100){
						num++;
						if (num==beanList.size()){
							num = 0;
						}
						if (timeBean.getTime()+timeBean.getStartTime()+canTime == timeBean.getEndTime()){
							canTime =0;
							normal = startIndex;

						}else{
							if (canTime==0){
							}
							canTime +=timeBean.getTime();
						}

						textView.startPlayLine(
								startIndex,
								startIndex + timeBean.getWord().length(), // 因为有个换行符，所以 + 1
								normal,1);
						startIndex += timeBean.getWord().length();


						timeBean = beanList.get(num);
					}
					break;
			}
		}
	};
	int startIndex = 0;
	long delayTime = 0L;

	void startPlay(){
//		String[] lyricList = lyric.split("\n");
		handler.post(runnable);
	}


	Timer timer;
	int time = 0;
	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			Message msg=new Message();
			msg.what=1001;
			handler.sendMessage(msg);
			time+=50;
			handler.postDelayed(runnable,50);
		}
	};

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

	/**
	 * 给流式布局设置值
	 */
	private void setFlowData() {

		flowLayout.setAdapter(new TagAdapter<String>(list) {
			@Override
			public View getView(FlowLayout parent, int position, String s) {

				LayoutInflater inflater = LayoutInflater.from(getApplication());
				TextView textView = (TextView) inflater.inflate(R.layout.item_word_sound, flowLayout, false);

				textView.setText(s);
				return textView;
			}
			//当选中的时候
			@Override
			public void onSelected(int position, View view) {
				super.onSelected(position, view);
				TextView textView = (TextView) view;
				textView.setTextColor(Color.parseColor("#FFFFFF"));
			}

			//当没选中的时候
			@Override
			public void unSelected(int position, View view) {
				super.unSelected(position, view);
				TextView textView = (TextView) view;
				textView.setTextColor(Color.parseColor("#000000"));
			}
		});
	}
}
