package com.yidianling.fm;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.cardview.widget.CardView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.ydl.media.audio.AudioPlayer;
import com.ydl.media.audio.OnPlayerEventListener;
import com.ydl.media.audio.model.Music;
import com.ydl.media.view.PlayerFloatHelper;
import com.ydl.ydl_image.module.GlideApp;
import com.ydl.ydl_image.transform.GlideCircleRingTransform;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.data.http.ThrowableConsumer;
import com.ydl.ydlcommon.utils.remind.ToastHelper;
import com.ydl.ydlcommon.view.TitleBar;
import com.ydl.ydlcommon.view.dialog.YDLShareDialog;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.common.tools.RxDeviceTool;
import com.yidianling.common.tools.RxImageTool;
import com.yidianling.fm.param.DetailParam;
import com.yidianling.fm.param.FavParam;
import com.yidianling.fm.response.FMDetail;
import com.yidianling.fm.router.FMIn;
import com.yidianling.fm.widget.FMSurfaceView;
import com.yidianling.user.api.event.UserLoginEvent;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import de.greenrobot.event.EventBus;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 电台详情
 * Created by softrice on 15/12/11.
 */
@Route(path = "/fm/detail")
public class FMDetailActivity extends BaseActivity implements View.OnClickListener, OnPlayerEventListener{

    int id;
    boolean isSplash;

    TitleBar tb_title;
    ImageView iv_play;
    TextView tv_fm_title;
    TextView tv_anchor;
    TextView tv_like;
    TextView tv_listen;
    ImageView iv_love;
    ImageView iv_next;
    ImageView iv_last;
    ImageView iv_share;
    LinearLayout ll_bottom;
    TextView tv_currentTime;
    TextView tv_allTime;
    SeekBar fm_progress;
    FMSurfaceView fmSurfaceView;
    LinearLayout ll_last_time;
    ImageView fm_img;
    ImageView refresh_icon;
    CardView fm_card;

    ImageView tv_like_icon;
    ImageView tv_listen_icon;

    private ValueAnimator anim;

    private ArrayList<Integer> fmIdList = new ArrayList();

    private FMDetail fmDetail;
    private SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
    private Date currentTime = new Date();

    private boolean canNext = true;

    private int time;
    private int allTime;
    private int max_progress = 1000;
//    private MyPlayer player;

    private static final String ID = "id";
    private static final String IS_SPLASH = "isSplash";
    //是否跳转到心事动态
    private boolean isToTrend = false;

    public static Intent newIntent(Activity activity, int id) {
        Intent intent = new Intent(activity, FMDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(ID, id);
        intent.putExtra("bundle", bundle);
        return intent;
    }

    public static Intent newIntent(Activity activity, int id, boolean isSplash) {
        Intent intent = new Intent(activity, FMDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(ID, id);
        bundle.putBoolean(IS_SPLASH, isSplash);
        intent.putExtra("bundle", bundle);
        return intent;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (null == intent) {
            finish();
            return;
        }
        Bundle bundle = intent.getBundleExtra("bundle");
        if (null != bundle) {
            id = bundle.getInt(ID, 0);
            isSplash = bundle.getBoolean("isSplash", false);
        }
        //路由跳转 取值
        if (intent.hasExtra("routerParam")) {
            String json = intent.getStringExtra("routerParam");
            if (!TextUtils.isEmpty(json)) {
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    id = jsonObject.getInt("id");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        //重置当前为第一首
        fmIdList.clear();
        getFMDetail(id, true);
    }

    @Override
    protected int layoutResId() {
        return R.layout.fm_activity_fm_detail;
    }

    /**
     * 路由跳转 取值
     */
    private void getParam() {
        if (getIntent().hasExtra("routerParam")) {
            String json = getIntent().getStringExtra("routerParam");
            if (!TextUtils.isEmpty(json)) {
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    id = jsonObject.getInt("id");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void initDataAndEvent() {

        fmIdList.clear();

        EventBus.getDefault().register(this);

        if (null == getIntent()) {
            finish();
            return;
        }
        Bundle bundle = getIntent().getBundleExtra("bundle");
        if (null != bundle) {
            id = bundle.getInt(ID, 0);
            isSplash = bundle.getBoolean("isSplash", false);
        }
        //路由跳转 取值
        getParam();
        tb_title = findViewById(R.id.tb_title);
        iv_play = findViewById(R.id.iv_play);
        tv_fm_title = findViewById(R.id.tv_fm_title);
        tv_anchor = findViewById(R.id.tv_anchor);
        tv_like = findViewById(R.id.tv_like);
        tv_listen = findViewById(R.id.tv_listen);
        iv_love = findViewById(R.id.iv_love);
        iv_next = findViewById(R.id.iv_next);
        iv_last = findViewById(R.id.iv_last);
        iv_share = findViewById(R.id.iv_share);
        ll_bottom = findViewById(R.id.ll_bottom);
        tv_currentTime = findViewById(R.id.tv_currentTime);
        tv_allTime = findViewById(R.id.tv_allTime);
        fm_progress = findViewById(R.id.fm_progress);
        fmSurfaceView = findViewById(R.id.fmSurfaceView);
        ll_last_time = findViewById(R.id.ll_last_time);
        fm_img = findViewById(R.id.fm_img);
        tv_like_icon = findViewById(R.id.tv_like_icon);
        tv_listen_icon = findViewById(R.id.tv_listen_icon);
        refresh_icon = findViewById(R.id.refresh_icon);
        fm_card = findViewById(R.id.fm_card);

        iv_play.setOnClickListener(this);
        iv_love.setOnClickListener(this);
        iv_next.setOnClickListener(this);
        iv_last.setOnClickListener(this);
        iv_share.setOnClickListener(this);
        initRefreshAnimate();
        init();
        initSurfaceView();
        initImg();
    }

    @SuppressLint("WrongConstant")
    private void initRefreshAnimate() {
        anim = ValueAnimator.ofFloat(1f, 1.5f, 1f);
        anim.setDuration(1000);
        anim.setStartDelay(1000);
        anim.setRepeatCount(ValueAnimator.INFINITE);
        anim.setRepeatMode(ValueAnimator.INFINITE);
        anim.setInterpolator(new AccelerateDecelerateInterpolator());
        int refreshIconWidth = RxImageTool.dp2px(25f);
        anim.addUpdateListener(animation -> {
            refresh_icon.setVisibility(View.VISIBLE);
            float currentValue = (float) animation.getAnimatedValue();
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) (refreshIconWidth * currentValue), (int) (refreshIconWidth * currentValue));
            params.addRule(RelativeLayout.CENTER_IN_PARENT);
            refresh_icon.setLayoutParams(params);
        });
    }

    private void initSurfaceView() {
        int width = RxDeviceTool.getScreenWidth(this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, width);
        fmSurfaceView.setLayoutParams(params);
    }

    private void initImg() {
        int screenWidth = RxDeviceTool.getScreenWidth(this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(screenWidth, screenWidth);
        ll_last_time.setLayoutParams(params);

        int width = screenWidth * 140 / 375;
        LinearLayout.LayoutParams cardParams = new LinearLayout.LayoutParams(width, width);
        fm_card.setRadius(width / 2);
        fm_card.setLayoutParams(cardParams);
        FrameLayout.LayoutParams imgParams = new FrameLayout.LayoutParams(width, width);
        fm_img.setLayoutParams(imgParams);
    }

    int changeProgress = 0;

    void init() {
        Window window = getWindow();
        window.setStatusBarColor(Color.TRANSPARENT);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        fm_progress.setMax(max_progress);
        tb_title.setDivideVisible(View.GONE);
        tb_title.setLeftListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Back();
            }
        });
        tb_title.setOnRightTextClick(new TitleBar.OnTitleBarTextClick() {
            @Override
            public void onClick(View view, boolean isActive) {
                startActivity(new Intent(FMDetailActivity.this, FMActivity.class));
            }
        });
        LogUtil.d("id " + id);
        if (PlayerFloatHelper.Companion.getFmId() == id) {
            refresh_icon.setVisibility(View.GONE);
            anim.cancel();
            if (AudioPlayer.Companion.get().isPlaying()) {
                iv_play.setImageResource(R.drawable.fm_stop_2);
            } else {
                iv_play.setImageResource(R.drawable.fm_play_2);
            }
            LogUtil.d("id equal " + id);
        }
        getFMDetail(id, true);
        fm_progress.setProgress(0);
        fm_progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

//                allTime = Integer.parseInt(String.valueOf(AudioPlayer.Companion.get().getDuration()));
                int current = seekBar.getProgress() * allTime / 1000;
                tv_allTime.setText(formatter.format(allTime));
                tv_currentTime.setText(formatter.format(current));
                changeProgress = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                iv_play.setImageResource(R.drawable.fm_play_2);
                AudioPlayer.Companion.get().pausePlayer();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
//                allTime = Integer.parseInt(String.valueOf(AudioPlayer.Companion.get().getDuration()));
                int current = seekBar.getProgress() * allTime / 1000;
                tv_allTime.setText(formatter.format(allTime));
                tv_currentTime.setText(formatter.format(current));
                AudioPlayer.Companion.get().seekTo(-1, current);
            }
        });
//        player.getMediaPlayer().setOnSeekCompleteListener(mp -> iv_play.setImageResource(R.drawable.fm_stop));

    }

    /**
     * @param id
     * @param type 为true则为下一首，否则为上一首
     */
    private void getFMDetail(int id, boolean type) {
        canNext = false;
        if (PlayerFloatHelper.Companion.getFmId() != id) {
            anim.start();
            iv_play.setImageResource(R.drawable.fm_stop_2);
            fmSurfaceView.stopTimer();
            fm_progress.setEnabled(false);
            if (type) {
                fmIdList.add(id);
            } else {
                fmIdList.remove(fmIdList.size() - 1);
            }
        }
        FmDataManager.INSTANCE.getHttp().fmDetail(new DetailParam(id))
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(fmDetail -> {
                    this.fmDetail = fmDetail;
                    this.id = fmDetail.getId();
                    setData();
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        ToastHelper.Companion.show(msg);
                    }
                });
    }

    void setData() {
        if (!TextUtils.isEmpty(fmDetail.getImage_url())) {
            GlideApp.with(this)
                    .load(fmDetail.getImage_url())
                    .placeholder(fm_img.getDrawable())
                    .transform(new GlideCircleRingTransform(this))
                    .into(fm_img);
        }
        if (!TextUtils.isEmpty(fmDetail.getAuthor())) {
            tv_anchor.setText("主播：" + fmDetail.getAuthor());
            tv_anchor.setVisibility(View.VISIBLE);
        }
        if (!TextUtils.isEmpty(fmDetail.getTitle())) {
            tv_fm_title.setText(fmDetail.getTitle());
            tv_fm_title.setVisibility(View.VISIBLE);
        }
        if (!TextUtils.isEmpty(fmDetail.getCount_favorite())) {
            tv_like.setText("" + fmDetail.getCount_favorite());
            tv_like_icon.setVisibility(View.VISIBLE);
            tv_like.setVisibility(View.VISIBLE);
        }
        if (!TextUtils.isEmpty(String.valueOf(fmDetail.getHits()))) {
            tv_listen.setText("" + fmDetail.getHits());
            tv_listen_icon.setVisibility(View.VISIBLE);
            tv_listen.setVisibility(View.VISIBLE);
        }
        if (fmDetail.is_favorite() == 1) {//love
            iv_love.setImageResource(R.drawable.fm_love_h_2);
        } else {
            iv_love.setImageResource(R.drawable.fm_love_n_2);
        }
        canNext = true;
        LogUtil.d("fmDetail.id " + fmDetail.getId());
        if (PlayerFloatHelper.Companion.getFmId() != fmDetail.getId()) {
            if (!TextUtils.isEmpty(fmDetail.getFm_url())) {
                Music music = new Music();
                music.setPath(fmDetail.getFm_url());
                music.setAlbum(fmDetail.getImage_url());
                music.setArtist(fmDetail.getAuthor());
                music.setCoverPath(fmDetail.getImage_url());
                music.setTitle(fmDetail.getTitle());
                AudioPlayer.Companion.get().prev();
                AudioPlayer.Companion.get().singlePlay(music, false);
            }
            LogUtil.d("fmDetail.id not equal " + fmDetail.getId());
            HashMap<String,String> map = new HashMap();
            PlayerFloatHelper.Companion.getPlayTempData().clear();
            map.put("fmId", String.valueOf(fmDetail.getId()));
            map.put("fmTitle", String.valueOf(fmDetail.getTitle()));
            map.put("fmAuthor", String.valueOf(fmDetail.getAuthor()));
            map.put("fmImageUrl", String.valueOf(fmDetail.getImage_url()));
            PlayerFloatHelper.Companion.setPlayTempData(map);
            iv_play.setImageResource(R.drawable.fm_stop_2);
            fm_progress.setProgress(0);
        }else {
            this.time = Integer.parseInt(String.valueOf(AudioPlayer.Companion.get().getCurrentPosition()));
                    //PlayProgressUtil.INSTANCE.getProgress(this, fmDetail.getFm_url());
            updateThread();
        }
        AudioPlayer.Companion.get().addOnPlayEventListener(this);
    }

    //todo xujian 通知栏改变状态修改应用内播放状态图标
//    public void onEventMainThread(UpdatePlayStatusEvent status) {
//        if (PlayerFloatHelper.Companion.isFmPlaying()) {
//            iv_play.setImageResource(R.drawable.fm_stop_2);
//        } else {
//            iv_play.setImageResource(R.drawable.fm_fm_play_2);
//        }
//    }

    public void onEvent(UserLoginEvent event) {
        if (isToTrend) {
            isToTrend = false;
            toTrend();
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.iv_play) {
            if (AudioPlayer.Companion.get().isPlaying()) {
                AudioPlayer.Companion.get().pausePlayer();
                iv_play.setImageResource(R.drawable.fm_play_2);
                fmSurfaceView.stopTimer();
            } else {
                AudioPlayer.Companion.get().startPlayer();
                iv_play.setImageResource(R.drawable.fm_stop_2);
                fmSurfaceView.playTimer();
            }

        } else if (i == R.id.iv_love) {
            if (!FMIn.INSTANCE.loginByOneKeyLogin(this,true)){
                return;
            }
            collect();

        } else if (i == R.id.iv_next) {// 锁
            if (canNext)
                getFMDetail(fmDetail.getNext_id(), true);

        } else if (i == R.id.iv_last) {
            //这里调用canNext同样的状态控制，以及判定是否还有上一首,如果id数组大小为1，则当前已经是第一首了
            if (canNext && fmIdList.size() >= 2) {
                getFMDetail(fmIdList.get(fmIdList.size() - 2), false);
            } else if (fmIdList.size() <= 1) {
                ToastHelper.Companion.show("前面没有了哦");
            }
        } else if (i == R.id.iv_share) {
            share();
        }
    }


    private void share() {
        if (fmDetail == null)
            return;
        YDLShareDialog dialog = YDLShareDialog.Companion.style1(this, fmDetail.getTitle(), fmDetail.getShare_url(), "", fmDetail.getImage_url());
        dialog.setCallBack(type -> {
            if (1 == type) {
                if (!FMIn.INSTANCE.loginByOneKeyLogin(this,true)){
                    isToTrend = true;
                }else {
                    //分享到心事动态
                    toTrend();
                }
            }
        });
        dialog.show(getFragmentManager(), "lose");
    }

    private void toTrend() {
        //分享到心事动态
        Intent fmIntent = FMIn.INSTANCE.publisFmToTrend(FMDetailActivity.this, fmDetail.getShare_url(), fmDetail.getImage_url(), fmDetail.getTitle());
        if (null != fmIntent) {
            FMDetailActivity.this.startActivity(fmIntent);
        }
    }

    private void collect() {
        FmDataManager.INSTANCE.getHttp().favFM(new FavParam(id))
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(favFM -> {
                    if (favFM.getStatus() == 1) {
                        iv_love.setImageResource(R.drawable.fm_love_h_2);
                    } else {
                        iv_love.setImageResource(R.drawable.fm_love_n_2);
                    }
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        ToastHelper.Companion.show(msg);
                    }
                });
    }

    private void updateAnimateStatus() {
        //如果FM是在播放状态，那么就进行动画
        if (AudioPlayer.Companion.get().isPlaying()) {
            fmSurfaceView.playTimer();
        } else {
            fmSurfaceView.stopTimer();
        }
    }

    public void updateThread() {
        runOnUiThread(() -> {
//            allTime = Integer.parseInt(String.valueOf(AudioPlayer.Companion.get().getDuration()));
            currentTime.setTime(time - 8 * 60 * 60 * 1000);
            int percent = (int) (1000.0 * time / allTime);
            fm_progress.setProgress(percent);
            tv_currentTime.setText(formatter.format(currentTime));
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        fmSurfaceView.surfaceCreated(null);

        if (PlayerFloatHelper.Companion.isShow()) {
            PlayerFloatHelper.Companion.removeView();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void Back() {
        if (isSplash) {
//            FMOut.INSTANCE.startMain(this);
            FMIn.INSTANCE.mainIntent(this);
            finish();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        anim.cancel();

        EventBus.getDefault().unregister(this);
        AudioPlayer.Companion.get().removeOnPlayEventListener(this);
    }

    @Override
    public boolean onPreLoad(int playPosition) {
        return true;
    }

    @Override
    public void onLoad(@NotNull Music music) {

    }

    @Override
    public void onStartPlay() {
        iv_play.setImageResource(R.drawable.fm_stop_2);
        fmSurfaceView.playTimer();
    }

    @Override
    public void onPausePlay() {
        iv_play.setImageResource(R.drawable.fm_play_2);
        fmSurfaceView.stopTimer();
    }

    @Override
    public void onPublish(int percent, long currentPosition) {
        this.time = Integer.parseInt(String.valueOf(currentPosition));
        updateThread();
        updateAnimateStatus();
    }

    @Override
    public void onBufferingUpdate(int percent) {

    }

    @Override
    public void onPrepared(long duration) {
        this.allTime = Integer.parseInt(String.valueOf(duration));
        tv_allTime.setText(formatter.format(allTime));
        iv_play.setVisibility(View.VISIBLE);
        refresh_icon.setVisibility(View.GONE);
        anim.cancel();
        fm_progress.setEnabled(true);
        iv_play.setImageResource(R.drawable.fm_stop_2);
        fmSurfaceView.playTimer();
    }

    @Override
    public void onComplete() {
        fm_progress.setProgress(max_progress);
        updateAnimateStatus();
        getFMDetail(fmDetail.getNext_id(), true);
    }
}
