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.WindowManager;
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.bean.StatusBarOptions;
import com.ydl.ydlcommon.utils.SharedPreferencesEditor;
import com.ydl.ydlcommon.utils.StatusBarUtils;
import com.ydl.ydlcommon.view.NoScrollViewPager;
import com.ydl.ydlcommon.view.dialog.CommonDialog;
import com.yidianling.dynamic.bean.DynamicConstants;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.bean.TrendTabEntity;
import com.yidianling.dynamic.dialog.DynamicSaveDraftDialog;
import com.yidianling.dynamic.dialog.TrendsAndQuestionDialog;
import com.yidianling.dynamic.dialog.listener.DynamicQuestionSaveListener;
import com.yidianling.dynamic.event.DynamicSaveEvent;
import com.yidianling.dynamic.publishTrend.fragment.PublishQuestionAndTrendFragment;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

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

import de.greenrobot.event.EventBus;


/**
 * 发布动态
 */
@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 TextView 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;
    private DynamicSaveDraftDialog dynamicSaveDraftDialog = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    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;
    }


    @NotNull
    @Override
    public StatusBarOptions getStatusViewOptions() {
        return new StatusBarOptions(true,  true);
    }

    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.mBackIv);
        mPublishTrendTitle= findViewById(R.id.publish_trend_title_rel);
        mBackIv.setOnClickListener(v -> {
            SaveOrNotDialog();

        });
        //发布按钮
        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 SaveOrNotDialog() {
        dynamicSaveDraftDialog=new DynamicSaveDraftDialog(this
                , new DynamicQuestionSaveListener() {
            @Override
            public void notSave() {
                EventBus.getDefault().post(new DynamicSaveEvent(false));
                finish();
            }

            @Override
            public void save() {
            //发送通知给Fragment保留此次编辑
                EventBus.getDefault().post(new DynamicSaveEvent(true));
                finish();
            }
        });
        dynamicSaveDraftDialog.show();
    }

    private void initData() {
        Integer dynamic_question = 1;
        Bundle bundle = getIntent().getBundleExtra("bundle");
        if (null != bundle) {
            dynamic_question= bundle.getInt("dynamic_question", 1);
        }
        if (dynamic_question==1){
            titleList.add(new TrendTabEntity("发动态", 0, 0));
            fragmentList.add(PublishQuestionAndTrendFragment.getInstance(PublishQuestionAndTrendFragment.TYPE_TREND));
        }else{
        titleList.add(new TrendTabEntity("提问题", 0, 0));
        fragmentList.add(PublishQuestionAndTrendFragment.getInstance(PublishQuestionAndTrendFragment.TYPE_QUESTION));
        }
        mTableLayout.setTabData(titleList);


        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(0);
        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 {
                SaveOrNotDialog();
            }
        } else {
            SaveOrNotDialog();
        }
    }

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