package com.gh.gamecenter.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProviders;

import com.gh.common.util.NewLogUtils;
import com.gh.gamecenter.core.iinterface.SearchBarHint;
import com.gh.gamecenter.common.base.fragment.BaseLazyFragment;
import com.gh.common.constant.Config;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.common.databind.BindingAdapters;
import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.DataCollectionUtils;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.utils.PackageFlavorHelper;
import com.gh.common.util.IntegralLogHelper;
import com.gh.common.util.LogUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.core.utils.SPUtils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.MessageActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.SearchActivity;
import com.gh.gamecenter.entity.GameUpdateEntity;
import com.gh.gamecenter.eventbus.EBDownloadStatus;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.message.MessageUnreadViewModel;
import com.gh.gamecenter.packagehelper.PackageViewModel;
import com.gh.gamecenter.teenagermode.TeenagerModeActivity;
import com.halo.assistant.HaloApp;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import kotlin.text.StringsKt;


/**
 * Created by LGT on 2016/9/9.
 * 工具栏 搜索控制
 */
public class SearchToolbarFragment extends BaseLazyFragment implements View.OnClickListener, SearchBarHint {

    private MessageUnreadViewModel mUnreadViewModel;
    private PackageViewModel mPackageViewModel;

    private AlphaAnimation mAlphaAnimation;

    private static final int REQUEST_MESSAGE = 198;
    private ArrayList<String> mHintList;
    private int mHintIndex;
    private String mLocation;

    TextView mDownloadHintTv;
    TextView mSearchHintTv;
    View mSearchContainerView;
    View mDownloadView;
    TextView mMessageUnread;
    View mContainer;
    ImageView mSearchRightView;
    View mTeenagerModelView;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_MESSAGE) {
            if (mUnreadViewModel != null) mUnreadViewModel.retry();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_toolbar;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);

        mDownloadHintTv = mCachedView.findViewById(R.id.action_tip);
        mSearchHintTv = mCachedView.findViewById(R.id.actionbar_search_input);
        mSearchContainerView = mCachedView.findViewById(R.id.actionbar_search_rl);
        mDownloadView = mCachedView.findViewById(R.id.actionbar_rl_download);
        mMessageUnread = mCachedView.findViewById(R.id.message_unread_hint);
        mContainer = mCachedView.findViewById(R.id.home_actionbar);
        mSearchRightView = mCachedView.findViewById(R.id.actionbar_search_right);
        mTeenagerModelView = mCachedView.findViewById(R.id.actionbar_teenager_model);

        initActionBar(view);

        final ScaleAnimation scaleAnimation = new ScaleAnimation(0.4f, 1.0f, 0.4f, 1.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(500);

        mAlphaAnimation = new AlphaAnimation(1f, 0.2f);
        mAlphaAnimation.setDuration(300);
        mAlphaAnimation.setStartOffset(5000);

        scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (mAlphaAnimation != null) {
                    mSearchHintTv.setAnimation(mAlphaAnimation);
                    mAlphaAnimation.start();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        mAlphaAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // 切换数据
                if (mHintIndex > mHintList.size() - 1) {
                    mHintIndex = 0;
                }
                mSearchHintTv.setHint(mHintList.get(mHintIndex));
                mHintIndex++;

                if (scaleAnimation != null) {
                    mSearchHintTv.setAnimation(scaleAnimation);
                    scaleAnimation.start();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        if (mHintList != null && mHintList.size() > 0) {
            if (mHintList.size() > 1) {
                mSearchHintTv.setAnimation(mAlphaAnimation);
            } else {
                String hint = mHintList.get(0);
                mSearchHintTv.setHint(hint);
            }
        }

    }

    public void updateSearchToolbarColor(int color) {
        mContainer.setBackgroundColor(color);
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.menu_concern, menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null && getArguments().getString(EntranceConsts.KEY_LOCATION) != null) {
            mLocation = getArguments().getString(EntranceConsts.KEY_LOCATION);
        }
        mHintIndex = 0;
        if (savedInstanceState != null) {
            mHintList = savedInstanceState.getStringArrayList(EntranceConsts.KEY_HINT);
        }
        mPackageViewModel = ViewModelProviders.of(this, new PackageViewModel.Factory()).get(PackageViewModel.class);
        mPackageViewModel.getFilterSameUpdateLiveData().observe(this, this::setDownloadHint);

        mUnreadViewModel = ViewModelProviders.of(this,
                new MessageUnreadViewModel.Factory(HaloApp.getInstance().getApplication())).get(MessageUnreadViewModel.class);
        mUnreadViewModel.getLiveData().observe(this, unreadEntity -> {
            if (unreadEntity != null) {
                int count = unreadEntity.getTotal() - unreadEntity.getFans();
                mMessageUnread.setVisibility(count > 0 ? View.VISIBLE : View.GONE);
                BindingAdapters.setMessageUnread(mMessageUnread, count);
            } else {
                mMessageUnread.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mHintList != null && !mHintList.isEmpty()) {
            outState.putStringArrayList(EntranceConsts.KEY_HINT, mHintList);
        }
    }

    private void initActionBar(View view) {

        if (getActivity() != null && getActivity().getActionBar() != null) {
            getActivity().getActionBar().setCustomView(R.layout.toolbar_search);
        }

        mDownloadView.setOnClickListener(this);

        view.findViewById(R.id.actionbar_iv_search).setOnClickListener(this);
        view.findViewById(R.id.actionbar_notification).setOnClickListener(this);
        view.findViewById(R.id.actionbar_search_rl).setOnClickListener(this);

        if (Config.isShow()) {
            mDownloadView.setVisibility(View.VISIBLE);
        } else {
            mDownloadView.setVisibility(View.INVISIBLE);
        }

        if (SPUtils.getBoolean(Constants.SP_TEENAGER_MODE)) {
            mTeenagerModelView.setVisibility(View.VISIBLE);
            mSearchContainerView.setVisibility(View.GONE);
            mSearchRightView.setVisibility(View.VISIBLE);
        } else {
            mTeenagerModelView.setVisibility(View.GONE);
            mSearchContainerView.setVisibility(View.VISIBLE);
            mSearchRightView.setVisibility(View.GONE);
        }

        mTeenagerModelView.setOnClickListener(this);
        mSearchHintTv.setOnClickListener(this);
        mSearchRightView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        Intent intent;

        if (id == R.id.actionbar_rl_download) {
            MtaHelper.onEvent("首页_点击", "顶栏", "下载管理");
//                MtaHelper.onEvent("下载管理", "下载管理入口", "首页");
            DataCollectionUtils.uploadClick(getActivity(), "下载图标", "主页");

            startActivity(DownloadManagerActivity.getDownloadMangerIntent(requireContext(), "(工具栏)"));
        } else if (id == R.id.actionbar_iv_search) {
            MtaHelper.onEvent("首页_点击", "顶栏", "搜索");
            DataCollectionUtils.uploadClick(getActivity(), "搜索图标", "主页");

            intent = SearchActivity.getIntent(requireContext(), true, mSearchHintTv.getHint().toString(), "(工具栏)", mLocation);
            startActivity(intent);
        } else if (id == R.id.actionbar_search_input || id == R.id.actionbar_search_rl || id == R.id.actionbar_search_right) {
            MtaHelper.onEvent("首页_点击", "顶栏", "搜索");
            DataCollectionUtils.uploadClick(getActivity(), "搜索框", "主页");
            if ("首页".equals(mLocation) || "游戏库".equals(mLocation)) {
                LogUtils.uploadSearchGame("access_to_search", mLocation, "", "");
            }

            intent = SearchActivity.getIntent(requireContext(), false, mSearchHintTv.getHint().toString(), "(工具栏)", mLocation);
            startActivity(intent);
        } else if (id == R.id.actionbar_notification) {
            MtaHelper.onEvent("首页_点击", "顶栏", "消息中心");
            DataCollectionUtils.uploadClick(getActivity(), "消息图标", "主页");

            CheckLoginUtils.checkLogin(requireContext(), "(工具栏)", () -> {
                NewLogUtils.logMessageInformBellClick(mMessageUnread.getVisibility() == View.VISIBLE, mLocation);
                Intent i = MessageActivity.getIntent(requireContext(), "(工具栏)");
                startActivityForResult(i, REQUEST_MESSAGE);
            });
        } else if (id == R.id.actionbar_teenager_model) {
            startActivity(TeenagerModeActivity.getIntent(requireContext()));
        }
    }

    // 打开下载按钮事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBReuse reuse) {
        if ("Refresh".equals(reuse.getType())) {
            if (Config.isShow()) {
                mDownloadView.setVisibility(View.VISIBLE);
            } else {
                mDownloadView.setVisibility(View.GONE);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBDownloadStatus status) {
        setDownloadHint(mPackageViewModel.getFilterSameUpdateLiveData().getValue());
    }

    private void setDownloadHint(List<GameUpdateEntity> updateList) {
        String count = DownloadManager.getInstance().getDownloadOrUpdateCount(updateList);
        if (count != null) {
            mDownloadHintTv.setVisibility(View.VISIBLE);
            mDownloadHintTv.setText(count);

            ViewGroup.LayoutParams params = mDownloadHintTv.getLayoutParams();
            if (TextUtils.isEmpty(count)) {
                params.width = DisplayUtils.dip2px(6);
                params.height = DisplayUtils.dip2px(6);
            } else {
                params.width = DisplayUtils.dip2px(12);
                params.height = DisplayUtils.dip2px(12);
            }
            mDownloadHintTv.setLayoutParams(params);
        } else {
            mDownloadHintTv.setVisibility(View.GONE);
        }
    }

    @Override
    public void setHint(ArrayList<String> hint) {
        if (hint != null && hint.size() > 0) {
            mHintList = new ArrayList<>();

            for (String h : hint) {
                mHintList.add(StringsKt.removeSuffix(h, "."));
            }

            if (hint.size() == 1 && mSearchHintTv != null) {
                mSearchHintTv.setHint(mHintList.get(0));
            } else if (mAlphaAnimation != null && mSearchHintTv != null) {
                mSearchHintTv.setAnimation(mAlphaAnimation);
            }
        }
    }

    public void updateStyle(boolean useLightStyle) {
        if (mCachedView == null) return;

        if (useLightStyle) {
            ((ImageView) mCachedView.findViewById(R.id.actionbar_iv_search)).setImageResource(R.drawable.toolbar_search_icon_light);
            ((ImageView) mCachedView.findViewById(R.id.actionbar_download)).setImageResource(R.drawable.toolbar_download_light);
            ((ImageView) mCachedView.findViewById(R.id.actionbar_message)).setImageResource(R.drawable.toolbar_message_light);
            ((ImageView) mCachedView.findViewById(R.id.actionbar_teenager_model_iv)).setImageResource(R.drawable.toolbar_teenager_light);
            ((TextView) mCachedView.findViewById(R.id.actionbar_teenager_model_tv)).setTextColor(Color.WHITE);
            mSearchRightView.setImageResource(R.drawable.toolbar_search_light);
            mTeenagerModelView.setBackgroundResource(R.drawable.button_round_black_alpha_10);
            mSearchHintTv.setHintTextColor(ContextCompat.getColor(requireContext(), R.color.search_text_color_light));
            mSearchContainerView.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.home_search_bg_light));
        } else {
            ((ImageView) mCachedView.findViewById(R.id.actionbar_iv_search)).setImageResource(R.drawable.toolbar_search_icon);
            ((ImageView) mCachedView.findViewById(R.id.actionbar_download)).setImageResource(R.drawable.toolbar_download);
            ((ImageView) mCachedView.findViewById(R.id.actionbar_message)).setImageResource(R.drawable.toolbar_message);
            ((ImageView) mCachedView.findViewById(R.id.actionbar_teenager_model_iv)).setImageResource(R.drawable.toolbar_teenager);
            ((TextView) mCachedView.findViewById(R.id.actionbar_teenager_model_tv)).setTextColor(ContextCompat.getColor(requireContext(), R.color.text_subtitle));
            mSearchRightView.setImageResource(R.drawable.toolbar_search);
            mTeenagerModelView.setBackgroundResource(R.drawable.button_round_f2f4f7);
            mSearchHintTv.setHintTextColor(ContextCompat.getColor(requireContext(), R.color.search_text_color_default));
            mSearchContainerView.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.home_search_bg));
        }
    }

    private void updateSearchToolbar() {
        if (getParentFragment() instanceof SearchToolWrapperFragment) {
            if (getParentFragment() instanceof HomeSearchToolWrapperFragment) {
                mContainer.setBackground(null);
                return;
            }
            updateStyle(mIsDarkModeOn);
            updateSearchToolbarColor(ContextCompat.getColor(requireContext(), R.color.background_white));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateSearchToolbar();
    }

    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        updateSearchToolbar();
    }
}
