package com.yidianling.dynamic.publishTrend;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.base.config.YDLConstants;
import com.ydl.ydlcommon.utils.SharedPreferencesEditor;
import com.ydl.ydlcommon.utils.StatusBarUtils;
import com.ydl.ydlcommon.view.NoScrollViewPager;
import com.yidianling.dynamic.bean.DynamicConstants;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.bean.TrendTabEntity;
import com.yidianling.dynamic.publishTrend.fragment.PublishQuestionAndTrendFragment;

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


/**
 * 发布动态
 */
@Route(path = "/trend/publish")
public class PublishTrendActivity extends BaseActivity {
    private static final String URL = "Test_url";
    private static final String COVER = "Test_cover";
    private static final String TITLE = "Test_title";
    private static final String ISFROMFM = "isfromfm";
    private ImageView mBackIv;
    private TextView mToastView;
    private NoScrollViewPager mViewPager;
    private CommonTabLayout mTableLayout;
    //    private RelativeLayout mNoticeLayout;
    private ArrayList<CustomTabEntity> titleList = new ArrayList<>();
    private List<Fragment> fragmentList = new ArrayList<>();
    private PopupWindow noticePopupWindow;
    private Handler handler;
    private LinearLayout mPublishTrendTitle;

    public static Intent newIntent(Activity activity, String url, String cover, String title) {
        Intent intent = new Intent(activity, PublishTrendActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(URL, url);
        bundle.putString(COVER, cover);
        bundle.putString(TITLE, title);
        intent.putExtra(YDLConstants.BUNDLE, bundle);
        return intent;
    }


    public static Intent newIntentForArticle(Activity activity, String url, String cover, String title) {
        Intent intent = new Intent(activity, PublishTrendActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(URL, url);
        bundle.putString(COVER, cover);
        bundle.putString(TITLE, title);
        bundle.putString(DynamicConstants.PUBLISH_TYPE, "topic_publish");
        bundle.putString("topic_id", "44");
        bundle.putString("topic_title", "今日打卡");
        intent.putExtra(YDLConstants.BUNDLE, bundle);
        return intent;
    }


    public static Intent newIntentForFm(Activity activity, String url, String cover, String title, int isFromFm) {
        Intent intent = new Intent(activity, PublishTrendActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(URL, url);
        bundle.putString(COVER, cover);
        bundle.putString(TITLE, title);
        bundle.putInt(ISFROMFM, isFromFm);
        bundle.putString(DynamicConstants.PUBLISH_TYPE, "topic_publish");
        bundle.putString("topic_id", "44");
        bundle.putString("topic_title", "今日打卡");
        intent.putExtra(YDLConstants.BUNDLE, bundle);
        return intent;
    }

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

    @Override
    protected void initDataAndEvent() {
        SharedPreferencesEditor.putString("trend_state", "");
        handler = new Handler();
        mBackIv = findViewById(R.id.img_back);
        mPublishTrendTitle= findViewById(R.id.publish_trend_title_rel);
        mBackIv.setOnClickListener(v -> {

            finish();
        });
        //发布按钮
        findViewById(R.id.publish_trend_sure_tv).setOnClickListener(v -> {
            if (fragmentList.get(mViewPager.getCurrentItem()) != null) {
                ((PublishQuestionAndTrendFragment) fragmentList.get(mViewPager.getCurrentItem())).publish();
            }
        });
        mViewPager = findViewById(R.id.view_pager);
        mViewPager.setScanScroll(true);
        mViewPager.setOffscreenPageLimit(2);
        mTableLayout = findViewById(R.id.tab_layout);
        mToastView = findViewById(R.id.tv_coustom_toast_view);
        initData();
        StatusBarUtils.Companion.setCustomStatusView(this,mPublishTrendTitle);
    }

    private void initData() {
        titleList.add(new TrendTabEntity("动态", 0, 0));
        titleList.add(new TrendTabEntity("提问", 0, 0));
        mTableLayout.setTabData(titleList);

        fragmentList.add(PublishQuestionAndTrendFragment.getInstance(PublishQuestionAndTrendFragment.TYPE_TREND));
        fragmentList.add(PublishQuestionAndTrendFragment.getInstance(PublishQuestionAndTrendFragment.TYPE_QUESTION));

        FragmentPagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }
        };
        mViewPager.setAdapter(adapter);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (mTableLayout.getCurrentTab() != position) {
                    mTableLayout.setCurrentTab(position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mTableLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (mViewPager.getCurrentItem() != position) {
                    mViewPager.setCurrentItem(position);
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        handler.postDelayed(() -> showNoticeView(), 300);
    }

    /**
     * 展示提问页面的提示窗
     */
    private void showNoticeView() {
        if (mViewPager.getCurrentItem() == 1) {
            //当前已经是提问页面了
            return;
        }

        TextView textView = mTableLayout.getTitleView(1);
        textView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int textViewWidth = textView.getMeasuredWidth();
        View view = LayoutInflater.from(this).inflate(R.layout.dynamic_popup_notice, null);
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int wid = view.getMeasuredWidth();
        noticePopupWindow = new PopupWindow(view);
        noticePopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        noticePopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置点击空白处消失
        noticePopupWindow.setTouchable(true);
        noticePopupWindow.setOutsideTouchable(true);
        noticePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        noticePopupWindow.showAsDropDown(textView, textViewWidth / 2 - wid / 2, -15);
        handler.postDelayed(() -> {
            if (noticePopupWindow != null) {
                noticePopupWindow.dismiss();
            }
        }, 1000);
    }

    /**
     * 显示页面自定的提示
     *
     * @param msg
     */
    public void showCoustomToast(String msg) {
        if (mToastView == null) {
            return;
        }
        mToastView.setText(msg);
        if (mToastView.getVisibility() != View.VISIBLE) {
            TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, -(mToastView.getMeasuredHeight() / 4), 0);
            translateAnimation.setDuration(1000);
            mToastView.setVisibility(View.VISIBLE);
            mToastView.startAnimation(translateAnimation);
            mToastView.postDelayed(() -> {
                if (mToastView == null || mToastView.getVisibility() == View.GONE) {
                    return;
                }
                Animation animation = new AlphaAnimation(1f, 0f);
                animation.setDuration(1000);
                mToastView.setAnimation(animation);
                mToastView.setVisibility(View.GONE);
            }, 1000);
        }
    }

    @Override
    public void onBackPressed() {
        if (fragmentList.get(mViewPager.getCurrentItem()) != null) {
            if (((PublishQuestionAndTrendFragment) fragmentList.get(mViewPager.getCurrentItem())).getEmojiLayoutIsShow()) {
                ((PublishQuestionAndTrendFragment) fragmentList.get(mViewPager.getCurrentItem())).hideEmojiLayout();
            } else {
                super.onBackPressed();
            }
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除任务
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
        }
    }
}
