package com.xxrv.video.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.base.FrameApp;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.util.glide.GlideApp;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.xxfc.imcamera.utile.FileUtils;
import com.xxrv.video.R;
import com.xxrv.video.R2;
import com.xxrv.video.adapter.DiscoveryVideoSelectAdapter;
import com.xxrv.video.adapter.SelectMusicAdapter;
import com.xxrv.video.api.VideoApi;
import com.xxrv.video.audio_x.VoiceManager;
import com.xxrv.video.base.BaseRecAdapter;
import com.xxrv.video.base.BaseRecViewHolder;
import com.xxrv.video.bean.circle.MusicInfo;
import com.xxrv.video.bean.circle.MusicInfoBean;
import com.xxrv.video.bean.circle.VideoIMTokenBean;
import com.xxrv.video.dialog.SelectMusicDialog;
import com.xxrv.video.presenter.VideoPresenter;
import com.xxrv.video.util.ScreenUtil;
import com.xxrv.video.util.downloader.DownloadListener;
import com.xxrv.video.util.downloader.Downloader;
import com.xxrv.video.util.downloader.FailReason;
import com.yuyife.okgo.OkGoUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 选择音乐
 */
public class SelectMusicActivity extends BaseStatusActivity<VideoPresenter> implements View.OnClickListener {


    @BindView(R2.id.search_edit)
    EditText mEditText;
    @BindView(R2.id.tv_null_tip)
    TextView hint;
    @BindView(R2.id.rv_comm)
    RecyclerView mListView;
    LinearLayoutManager mLayoutManager;

    private List<MusicInfo> mdatas = new ArrayList<>();
    private List<MusicInfo> searchDatas = new ArrayList<>();
    private int mPagerIndex;
    private boolean isLoad;
    private int mCurrPlay = -1; // 当前选择的索引
    private MusicInfo mCurrMusic;
    private boolean more = true; // 是否可加载更多
    private Timer SEARCH_TIMER;
    private SearchTimerTask mSearchTask;
    private boolean isSearch; // 是否正在搜索
    private VideoIMTokenBean intokenBean;

    private SelectMusicAdapter adapter;

    public static Intent getIntent(Context context) {
        return new Intent(context, SelectMusicActivity.class);
    }

    TextWatcher changeListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() > 0) {
                adapter.setNewData(null);
                startSearchTimer(s.toString());
            } else {
                cancelSearchTimer();
                adapter.setNewData(mdatas);
                hint.setVisibility(View.GONE);
                more = true;
            }
        }
    };

    @Override
    protected int setLayout() {
        return R.layout.activity_select_music;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("选择音乐");
        mEditText.addTextChangedListener(changeListener);
        mLayoutManager = new LinearLayoutManager(mActivity);
        mListView.setLayoutManager(mLayoutManager);
        adapter = new SelectMusicAdapter();
        mListView.setAdapter(adapter);

        addListener();

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                int id = view.getId();
                if (id == R.id.rl_content) {
                    playMusic(position);
                } else if (id == R.id.ll_next) {
                    VoiceManager.instance().stop();
                    List<MusicInfo> data = isSearch ? searchDatas : mdatas;
                    MusicInfo info = data.get(position);
                    File file = Downloader.getInstance().getFile(info.getPath());
                    if (file.exists()) { // 动态设置一下
                        info.setPath(file.getAbsolutePath());
                    }
                    getIntent().putExtra("music", info);
                    setResult(203, getIntent());

                    finish();
                }
            }
        });
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        upData();
    }

    @Override
    public void onClick(View v) {

    }

    private void upData() {
        if (OkGoUtil.getToken() != null) {
            Map<String, Object> headMap = new LinkedHashMap<>();
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.postData(RvFrameConfig.HOST, 1, VideoApi.DISCOVERY_IM_LOGIN, VideoIMTokenBean.class, headMap, headMap, false);
        }
    }

    public void startSearchTimer(String key) {
        cancelSearchTimer();
        isSearch = true;
        searchDatas.clear();
        SEARCH_TIMER = new Timer();
        mSearchTask = new SearchTimerTask();
        mSearchTask.setKey(key);
        SEARCH_TIMER.schedule(mSearchTask, 400);
    }

    public void cancelSearchTimer() {
        isSearch = false;
        if (SEARCH_TIMER != null) {
            SEARCH_TIMER.cancel();
        }
        if (mSearchTask != null) {
            mSearchTask.cancel();
        }
    }

    private void addListener() {
        mListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int firstVisibleItem, visibleItemCount, totalItemCount;
            private int previousTotal = 0;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (!more) {
                    // 外界不让加载数据了
                    return;
                }
                visibleItemCount = recyclerView.getChildCount();
                totalItemCount = mLayoutManager.getItemCount();
                firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();

                if (isLoad) {
                    if (totalItemCount > previousTotal) {
                        isLoad = false;
                        previousTotal = totalItemCount;
                    }
                }
                if (!isLoad && (totalItemCount - visibleItemCount) <= firstVisibleItem) {
                    mPagerIndex++;
                    setData(mPagerIndex, "");
                    isLoad = true;
                }
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        VoiceManager.instance().stop();
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 1:
                intokenBean = (VideoIMTokenBean) result;
                setData(0, "");
                break;
            case 2:
                setMusicData((MusicInfoBean) result);
                break;
        }
    }

    private void setMusicData(MusicInfoBean result) {
        List<MusicInfo> data = result.getData();
        if (data.size() > 0) {

            for (int i = 0; i < data.size(); i++) {
                MusicInfo info = data.get(i);
                info.appendDown("http://47.91.232.3:8089");
            }

            if (isSearch) {
                searchDatas.addAll(data);
                adapter.setNewData(searchDatas);
            } else {
                mdatas.addAll(data);
                adapter.setNewData(mdatas);
            }

            if (data.size() < 20) {
                more = false;
            }
            hint.setVisibility(View.GONE);
        } else {
            more = false;
            hint.setVisibility(View.VISIBLE);
        }
    }

    private void setData(int index, String keyword) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("pageIndex", String.valueOf(index));
        map.put("access_token", intokenBean.getData());
        if (!TextUtils.isEmpty(keyword)) {
            map.put("keyword", keyword);
        }
        map.put("type", 4);
        mPresenter.postData(2, VideoApi.DISCOVERY_IM_MUSIC, MusicInfoBean.class, map, index == 1 ? false : false);
    }


    private void playMusic(int position) {
        if (!isSearch && mCurrPlay == position) {
            return;
        }

        VoiceManager.instance().stop();
        List<MusicInfo> data = isSearch ? searchDatas : mdatas;

        if (mCurrPlay > -1 && data.size() > mCurrPlay) {
            data.get(mCurrPlay).state = 0;
            adapter.notifyItemChanged(mCurrPlay);
        }

        mCurrPlay = position;
        mCurrMusic = data.get(position);

        MusicInfo info = data.get(position);

        // 去下载路径找
        Downloader.getInstance().init(FrameApp.getInstance().mFilesDir);
        File file = Downloader.getInstance().getFile(info.getPath());

        Log.e("xuan", "down : " + info.getPath());
        if (file.exists()) {
            data.get(mCurrPlay).state = 1;
            adapter.notifyItemChanged(mCurrPlay);

            VoiceManager.instance().play(file);
        } else {
            data.get(mCurrPlay).state = 2;
            adapter.notifyItemChanged(mCurrPlay);
            Downloader.getInstance().addDownload(info.getPath(), new DownloadListener() {
                @Override
                public void onStarted(String uri, View view) {
                    Log.e("xuan", "开始下载");
                }

                @Override
                public void onFailed(String uri, FailReason failReason, View view) {
                    Log.e("xuan", "onFailed: 下载失败" + mCurrMusic.getPath());
                    showToast(getString(R.string.tip_file_download_failed));
                }

                @Override
                public void onComplete(String uri, String filePath, View view) {
                    Log.e("xuan", "comp: " + filePath);
                    if (Downloader.getInstance().getFile(mCurrMusic.getPath()).getAbsolutePath().equals(filePath)) {
                        mCurrMusic.setPath(filePath);
                        VoiceManager.instance().play(filePath);
                        data.get(mCurrPlay).state = 1;
                        adapter.notifyItemChanged(mCurrPlay);
                    }
                }

                @Override
                public void onCancelled(String uri, View view) {
                    Log.e("xuan", "取消下载");
                }
            });
        }
    }


    public class SearchTimerTask extends TimerTask {
        private String keyword;

        @Override
        public void run() {
            setData(0, keyword);
        }

        public void setKey(String key) {
            this.keyword = key;
        }
    }
}
