package com.cooleshow.teacher.ui.score;

import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.base.widgets.poplist.PopMenuBean;
import com.cooleshow.base.widgets.poplist.PopupListWindow;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.MineLiveCoursePagerAdapter;
import com.cooleshow.teacher.bean.MusicSheetShareBean;
import com.cooleshow.teacher.bean.QuerySubjectBean;
import com.cooleshow.teacher.constants.TeacherInfoConstants;
import com.cooleshow.teacher.contract.MineScoreActContract;
import com.cooleshow.teacher.databinding.ActivityMineScoreBinding;
import com.cooleshow.teacher.presenter.score.MineScoreActPresenter;
import com.cooleshow.teacher.ui.web.HtmlActivity;
import com.cooleshow.teacher.widgets.DialogUtils;
import com.cooleshow.teacher.widgets.FileUtils;
import com.cooleshow.usercenter.helper.UserHelper;
import com.google.android.material.tabs.TabLayout;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/5/20 16:34
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.ScoreCenter.TEACHER_MINE_SCORE)
public class MineScoreActivity extends BaseMVPActivity<ActivityMineScoreBinding, MineScoreActPresenter> implements MineScoreActContract.MineScoreActView, View.OnClickListener {
    private String currentSubjectId = "";
    private String currentSearchStr = "";
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private List<String> titles = new ArrayList<String>(Arrays.asList("已上架", "审核中", "审核失败"));
    private List<String> auditStatusList = new ArrayList<String>(Arrays.asList("PASS", "DOING", "UNPASS"));
    private List<Fragment> fragments = new ArrayList<>();
    private ArrayList<QuerySubjectBean> subjectBeanList = new ArrayList<>();

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right:
                String teacherCertificationStatus = UserHelper.getTeacherCertificationStatus();
                if (!TextUtils.equals(teacherCertificationStatus, TeacherInfoConstants.ENTRY_STATUS_PASS)) {
                    ToastUtil.getInstance().show(this, "您还未通过达人认证");
                    return;
                }
                presenter.musicSheetShare();
                break;
        }

    }

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "我的曲谱");
        viewBinding.toolbarInclude.tvRight.setBackgroundResource(R.drawable.icon_toolbar_share);
        viewBinding.toolbarInclude.tvRight.setVisibility(View.VISIBLE);
        viewBinding.toolbarInclude.tvRight.setOnClickListener(this);
        tabLayout = viewBinding.tablayout;
        viewPager = viewBinding.viewpager;
        viewPager.setCurrentItem(0);
        mShareListener = new CustomShareListener(this);
        viewBinding.searchView.setOnSearchListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String target = viewBinding.searchView.getSearchEdit().getText().toString().trim();
                currentSearchStr = target;
                updateByFilter();
            }
        });

        viewBinding.searchView.setOnLeftClickListener(v -> {
            selectVocalPart();
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
    }

    @Override
    public void initData() {
        super.initData();
        initTabLayoutAndViewPager();
        presenter.querySubjectItem();
    }

    /**
     * 选择声部
     */
    private void selectVocalPart() {
        if (subjectBeanList.size() == 0) {
            subjectBeanList.add(new QuerySubjectBean("声部", 0));
        }
        List<PopMenuBean> popList = new ArrayList<>();
        for (QuerySubjectBean bean : subjectBeanList) {
            PopMenuBean popMenuBean = new PopMenuBean();
            popMenuBean.setActionName(bean.name);
            popList.add(popMenuBean);
        }
        initCoursePop(viewBinding.searchView, popList, position -> {
            QuerySubjectBean bean = subjectBeanList.get(position);
            currentSubjectId = String.valueOf(bean.id);
            viewBinding.searchView.getLeftText().setText(bean.name);
            updateByFilter();
        });
    }

    private void updateByFilter() {
        int currentItem = viewPager.getCurrentItem();
        for (int i = 0; i < fragments.size(); i++) {
            MineScoreFragment mineScoreFragment = (MineScoreFragment) fragments.get(i);
            if (i == currentItem) {
                mineScoreFragment.goSearch(currentSearchStr, currentSubjectId);
            } else {
                mineScoreFragment.updateFilter(currentSearchStr, currentSubjectId);
            }
        }
    }

    /**
     * 选择声部pop
     *
     * @param targetView
     * @param popList
     * @param listener
     */
    private void initCoursePop(View targetView, List<PopMenuBean> popList, PopupListWindow.PopupListListener listener) {
        PopupListWindow popWindow = new PopupListWindow(this);
        popWindow.showListPop(targetView, popList, position -> listener.onPopupListClick(position));
    }

    @Override
    protected ActivityMineScoreBinding getLayoutView() {
        return ActivityMineScoreBinding.inflate(getLayoutInflater());
    }

    @Override
    protected MineScoreActPresenter createPresenter() {
        return new MineScoreActPresenter();
    }

    private void initTabLayoutAndViewPager() {
        tabLayout.removeAllTabs();
        fragments.clear();
        for (int i = 0; i < titles.size(); i++) {
            tabLayout.addTab(tabLayout.newTab().setText(titles.get(i)));
            Fragment adFragment = MineScoreFragment.newInstance(auditStatusList.get(i));
            fragments.add(adFragment);
        }
        viewPager.setAdapter(new MineLiveCoursePagerAdapter(getSupportFragmentManager(), fragments, titles));
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public void musicSheetShareSuccess(MusicSheetShareBean data) {
        if (data != null && data.musicSheetCount > 0) {
            showScoreShareDialog(data);
        } else {
            ToastUtil.getInstance().show(this, "您还没有上架曲谱");
        }
    }

    @Override
    public void querySubjectItemSuccess(List<QuerySubjectBean> data) {
        if (!checkActivityExist()) {
            return;
        }
        subjectBeanList.clear();
        subjectBeanList.add(new QuerySubjectBean("声部", 0));
        subjectBeanList.addAll(data);
    }

    private void showScoreShareDialog(MusicSheetShareBean data) {
        DialogUtils.showScoreShare(this, data, bitmap -> share(bitmap));
    }

    private ShareAction mShareAction;
    private UMShareListener mShareListener;

    private void share(Bitmap bitmap) {
        mShareAction = new ShareAction(MineScoreActivity.this).setDisplayList(
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA)
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        UMImage image = new UMImage(MineScoreActivity.this, bitmap);
                        new ShareAction(MineScoreActivity.this).withMedia(image)
                                .setPlatform(share_media)
                                .setCallback(mShareListener)
                                .share();

                    }
                });
        mShareAction.open();
    }

    private static class CustomShareListener implements UMShareListener {

        private WeakReference<MineScoreActivity> mActivity;

        private CustomShareListener(MineScoreActivity activity) {
            mActivity = new WeakReference(activity);
        }

        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                ToastUtil.getInstance().showShort("收藏成功啦");
            } else {
                if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                        && platform != SHARE_MEDIA.EMAIL
                        && platform != SHARE_MEDIA.FLICKR
                        && platform != SHARE_MEDIA.FOURSQUARE
                        && platform != SHARE_MEDIA.TUMBLR
                        && platform != SHARE_MEDIA.POCKET
                        && platform != SHARE_MEDIA.PINTEREST

                        && platform != SHARE_MEDIA.INSTAGRAM
                        && platform != SHARE_MEDIA.GOOGLEPLUS
                        && platform != SHARE_MEDIA.YNOTE
                        && platform != SHARE_MEDIA.EVERNOTE) {
                    ToastUtil.getInstance().showShort("分享成功啦");
                }

            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                    && platform != SHARE_MEDIA.EMAIL
                    && platform != SHARE_MEDIA.FLICKR
                    && platform != SHARE_MEDIA.FOURSQUARE
                    && platform != SHARE_MEDIA.TUMBLR
                    && platform != SHARE_MEDIA.POCKET
                    && platform != SHARE_MEDIA.PINTEREST

                    && platform != SHARE_MEDIA.INSTAGRAM
                    && platform != SHARE_MEDIA.GOOGLEPLUS
                    && platform != SHARE_MEDIA.YNOTE
                    && platform != SHARE_MEDIA.EVERNOTE) {
                ToastUtil.getInstance().showShort("分享失败啦");

            }

        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtil.getInstance().showShort("分享取消了");
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull @NotNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mShareAction != null) {
            mShareAction.close();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(MineScoreActivity.this).release();
    }
}
