package com.gh.gamecenter.libao;

import static com.gh.gamecenter.common.constant.Constants.LOGIN_TAG;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.ViewSkeletonScreen;
import com.gh.common.filter.RegionSettingHelper;
import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.DetailDownloadUtils;
import com.gh.common.util.DeviceTokenUtils;
import com.gh.common.util.LibaoUtils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.BuildConfig;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.LibaoDetailAdapter;
import com.gh.gamecenter.adapter.viewholder.DetailViewHolder;
import com.gh.gamecenter.common.base.fragment.ToolbarFragment;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.view.VerticalItemDecoration;
import com.gh.gamecenter.eventbus.EBDownloadStatus;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.eventbus.EBUISwitch;
import com.gh.gamecenter.feature.entity.ApkEntity;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.feature.entity.LibaoEntity;
import com.gh.gamecenter.feature.entity.LibaoStatusEntity;
import com.gh.gamecenter.feature.entity.MeEntity;
import com.gh.gamecenter.feature.entity.UserDataLibaoEntity;
import com.gh.gamecenter.feature.utils.ApkActiveUtils;
import com.gh.gamecenter.feature.view.DownloadButton;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.halo.assistant.HaloApp;
import com.lightgame.download.DataWatcher;
import com.lightgame.download.DownloadEntity;
import com.lightgame.utils.Utils;

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

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

public class LibaoDetailFragment extends ToolbarFragment implements LibaoDetailAdapter.OnCodeScrollListener {
    RecyclerView mLibaoDetailRv;
    LinearLayout mLlLoading;
    LinearLayout mNoConnection;
    TextView mNoneDataTv;
    LinearLayout mNoneData;
    LinearLayout mDataExceptionView;
    DownloadButton mDownloadPb;
    View mListSkeleton;
    View mDetailBottom;

    private ViewSkeletonScreen mSkeleton;

    private LibaoDetailAdapter mAdapter;

    private LibaoEntity mLibaoEntity;
    private GameEntity mGameEntity;

    private boolean mIsScroll;
    private String mName;
    private String mTitle;
    private boolean isClickReceiveBtnIn = false;//是否点击领取按钮进入

    @Override
    protected void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what == 0) {
            long time = Utils.getTime(requireContext()) - 5; // -5 防止获取服务器时间延迟发生的计算错误（）
            Calendar calendar = Calendar.getInstance();
            Date date = new Date(time * 1000);
            calendar.setTime(date);
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MINUTE, 59);
            calendar.add(Calendar.SECOND, 1);

            long targetTime = calendar.getTimeInMillis();
            long delayedTime = targetTime - time * 1000;
            if (BuildConfig.DEBUG) {
                toast("领取时间剩余： " + (delayedTime / 1000) + " 秒");
            }
            mBaseHandler.sendEmptyMessageDelayed(1, delayedTime);
        } else if (msg.what == 1) {
            String beforeStatus = mLibaoEntity.getBeforeStatus();
            if ("ling".equals(beforeStatus)) {
                mLibaoEntity.setStatus("repeatLinged"); // 可以重复领取
            } else {
                mLibaoEntity.setStatus("repeatTaoed"); // 可以重复领取
            }
            mAdapter.notifyItemChanged(0);
            performClickReceiveBtn();
        }
    }

    private DataWatcher dataWatcher = new DataWatcher() {
        @Override
        public void onDataChanged(DownloadEntity downloadEntity) {
            if (mGameEntity != null && mGameEntity.getApk().size() == 1) {
                String url = mGameEntity.getApk().get(0).getUrl();
                if (url.equals(downloadEntity.getUrl())) {
                    if (!"pause".equals(DownloadManager.getInstance().
                            getStatus(downloadEntity.getUrl()))) {
                        DetailDownloadUtils.updateViewHolder(getDetailViewHolder());
                    }
                }
            }
        }

        @Override
        public void onDataInit(@NonNull DownloadEntity downloadEntity) {
            onDataChanged(downloadEntity);
        }
    };

    private DetailViewHolder getDetailViewHolder() {
        // 每次获取需要重新创建, 防止数据刷新
        return new DetailViewHolder(mCachedView, null, mGameEntity, false, mEntrance, mName, mTitle, null, false, null, null); // 下载按钮ViewHolder
    }

    public LibaoEntity getLibaoEntity() {
        return mLibaoEntity;
    }

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

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        HaloApp.put(LibaoEntity.TAG, mAdapter.getLibaoEntity());
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mLibaoDetailRv = view.findViewById(R.id.libaodetail_rv_show);
        mLlLoading = view.findViewById(R.id.reuse_ll_loading);
        mNoConnection = view.findViewById(R.id.reuse_no_connection);
        mNoneDataTv = view.findViewById(R.id.reuseNoneDataTv);
        mNoneData = view.findViewById(R.id.reuse_none_data);
        mDataExceptionView = view.findViewById(R.id.reuse_data_exception);
        mDownloadPb = view.findViewById(R.id.detail_progressbar);
        mListSkeleton = view.findViewById(R.id.list_skeleton);
        mDetailBottom = view.findViewById(R.id.detail_ll_bottom);

        mName = getString(R.string.libao_detail);
        setNavigationTitle(mName);
        mLibaoEntity = (LibaoEntity) HaloApp.get(LibaoEntity.TAG, false);
        isClickReceiveBtnIn = requireArguments().getBoolean(EntranceConsts.KEY_IS_CLICK_RECEIVE_BTN, false);
        if (mLibaoEntity != null) {
            mLibaoEntity.setClickReceiveBtnIn(isClickReceiveBtnIn);
        }
        mIsScroll = true;

        mSkeleton = Skeleton.bind(mListSkeleton).shimmer(false).load(R.layout.activity_libaodetail_skeleton).show();
        mAdapter = new LibaoDetailAdapter(requireContext(), this, this, mLibaoEntity, mDownloadPb, mEntrance);
        mLibaoDetailRv.setLayoutManager(new LinearLayoutManager(requireContext()) {
            @Override
            public boolean canScrollVertically() {
                return mIsScroll;
            }
        });
        mLibaoDetailRv.addItemDecoration(getItemDecoration());
        mLibaoDetailRv.setAdapter(mAdapter);

        mNoConnection.setOnClickListener(v -> {
            mSkeleton.show();
            mNoConnection.setVisibility(View.GONE);
            mLlLoading.setVisibility(View.VISIBLE);
            mBaseHandler.postDelayed(this::getGameDigest, 1000);
        });

        if (mLibaoEntity == null) {
            String id = requireArguments().getString(EntranceConsts.KEY_ID);
            if (!TextUtils.isEmpty(id)) {
                getLibaoDigest(id);
            }
        } else {
            if (!mLibaoEntity.isActive()) {
                checkLibaoStatus();
            }
            getGameDigest();
        }

        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mDetailBottom.getLayoutParams();
        params.topMargin = 0;
        mDetailBottom.setLayoutParams(params);
    }

    private RecyclerView.ItemDecoration getItemDecoration() {
        return new VerticalItemDecoration(requireContext(), 8, false);
    }

    @Override
    public void onPause() {
        super.onPause();
        DownloadManager.getInstance().removeObserver(dataWatcher);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mGameEntity != null
                && (mGameEntity.getApk().size() == 1 || mGameEntity.isReservable())) {
            DetailDownloadUtils.updateViewHolder(getDetailViewHolder());
        }
        DownloadManager.getInstance().addObserver(dataWatcher);
    }

    // 检查礼包是否可以重复领取
    private void checkLibaoStatus() {
        if (mLibaoEntity != null && mLibaoEntity.getRepeat() > 0 && mLibaoEntity.getMe() != null
                && mLibaoEntity.getMe().getUserDataLibaoList() != null) {

            mTitle = mLibaoEntity.getName();
            String status = mLibaoEntity.getStatus();
            String beforeStatus = mLibaoEntity.getBeforeStatus();

            MeEntity userData = mLibaoEntity.getMe();
            List<UserDataLibaoEntity> userDataLibaoList = userData.getUserDataLibaoList();

            int repeat = mLibaoEntity.getRepeat();
            int curStatusCount = 0; // 当前状态的领取/淘号数量

            for (UserDataLibaoEntity userDataLibaoEntity : userDataLibaoList) {
                if (beforeStatus != null && beforeStatus.equals(userDataLibaoEntity.getType())) {
                    curStatusCount++;
                }
            }

            // 由领取到淘号的状态转换
            if (repeat <= curStatusCount || curStatusCount == 0) { // 当前领取/淘号总数是否超过总重复领取次数 / 当前状态的礼包没有领取/淘号过
                if (curStatusCount == 0 && ("ling".equals(beforeStatus) || "tao".equals(beforeStatus))) {
                    if (isCanLing()) { // 恢复原始状态
                        mLibaoEntity.setStatus(beforeStatus);
                        mAdapter.notifyItemChanged(0);
                        performClickReceiveBtn();
                    }
                }
                return;
            }


            if ((("linged").equals(status) || ("taoed").equals(status)) &&
                    ("ling".equals(beforeStatus) || "tao".equals(beforeStatus))) { //检查是否到了重复领取时间
                if (isCanLing()) {
                    mBaseHandler.sendEmptyMessage(1);
                } else {
                    if ("ling".equals(beforeStatus)) {
                        mLibaoEntity.setStatus("repeatLing"); // 预备重复领取
                    } else {
                        mLibaoEntity.setStatus("repeatTao"); // 预备重复领取
                    }
                    mAdapter.notifyItemChanged(0);
                    performClickReceiveBtn();

                    DeviceTokenUtils.syncServerTime(requireContext());
                    mBaseHandler.sendEmptyMessageDelayed(0, 5000);
                }
            }
        } else {
            performClickReceiveBtn();
        }
    }

    private void performClickReceiveBtn() {
        if (isClickReceiveBtnIn) {
            CheckLoginUtils.checkLogin(requireContext(), mEntrance, () ->
                    mLibaoDetailRv.postDelayed(() -> {
                        if (mAdapter.libaoDetailTopViewHolder != null) {
                            try {
                                mAdapter.libaoDetailTopViewHolder.binding.libaodetailCopyBtn.performClick();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, 200)
            );
        }
    }

    /**
     * 检查是否可以领取/淘号
     * 最后领取/淘号时间不是当天
     */
    public boolean isCanLing() {
        List<UserDataLibaoEntity> userDataLibaoList = mLibaoEntity.getMe().getUserDataLibaoList();
        UserDataLibaoEntity userDataLibaoEntity = userDataLibaoList.get(userDataLibaoList.size() - 1);
        SimpleDateFormat formatDay = new SimpleDateFormat("dd", Locale.CHINA);
        long lingTime = userDataLibaoEntity.getTime() * 1000;
        long curTime = Utils.getTime(requireContext()) * 1000;
        int lingDay = Integer.parseInt(formatDay.format(lingTime));
        int curDay = Integer.parseInt(formatDay.format(curTime));
        if (curDay != lingDay || curTime - lingTime > 24 * 60 * 60 * 1000) {
            return true;
        } else {
            return false;
        }
    }

    private void getLibaoDigest(final String libaoId) {
        RetrofitManager.getInstance().getApi().getLibaoDigest(libaoId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<LibaoEntity>() {
                    @Override
                    public void onResponse(LibaoEntity response) {
                        response.setActive(true); // addLibaoDetail设置userData
                        if (mLibaoEntity != null) {
                            mLibaoEntity.resetLibaoEntity(response);
                        } else {
                            mLibaoEntity = response;
                        }
                        mAdapter.setLibaoEntity(mLibaoEntity);
                        mAdapter.notifyDataSetChanged();
                        getGameDigest();
                        getLibaoStatus(libaoId);
                        checkLibaoStatus();
                    }
                });
    }

    private void getLibaoStatus(String libaoId) {
        LibaoUtils.getLibaoStatus(libaoId, new LibaoUtils.PostLibaoListener() {
            @Override
            public void postSucceed(Object response) {
                List<LibaoStatusEntity> statusList = (List<LibaoStatusEntity>) response;

                LibaoUtils.initLiBaoEntity(statusList.get(0), mLibaoEntity);

                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void postFailed(Throwable error) {

            }
        });
    }

    // 获取游戏摘要
    private void getGameDigest() {
        if (mLibaoEntity.getGame() == null) return;
        String gameId = mLibaoEntity.getGame().getId();
        if (RegionSettingHelper.shouldThisGameBeFiltered(gameId)) {
            loadNotFound();
            return;
        }
        RetrofitManager.getInstance().getApi().getGameNewsDigest(gameId)
                .map(ApkActiveUtils.filterMapper)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<GameEntity>() {
                    @Override
                    public void onResponse(GameEntity response) {
                        ApkActiveUtils.filterHideApk(response);
                        mGameEntity = response;
                        mAdapter.setGameEntity(mGameEntity);

                        // 添加启动弹窗的相关信息
                        if (mEntrance.contains(EntranceConsts.ENTRANCE_WELCOME)
                                && ExtensionsKt.countOccurrences(mEntrance, ("+")) <= 1) {
                            mGameEntity.setWelcomeDialogInfoIfAvailable();
                        }

                        DetailDownloadUtils.updateViewHolder(getDetailViewHolder());

                        mAdapter.addLibaoDetail(requireContext(), true);
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        if (e != null && e.code() == 404) {
                            mAdapter.addLibaoDetail(requireContext(), false);
                        } else {
                            loadError();
                        }
                    }
                });
    }

    @Override
    public void isScroll(boolean isScroll) {
        mIsScroll = isScroll;
    }

    @Override
    public void loadDone() {
        if (mLlLoading != null) {
            mLlLoading.setVisibility(View.GONE);
            mLibaoDetailRv.setVisibility(View.VISIBLE);
        }
        // 从存号箱进入 获取userData后 检查领取状态(是否可以重复领取/重复淘号)
        if (mLibaoEntity.isActive() && mLibaoEntity.getMe() != null) {
            if ("ling".equals(mLibaoEntity.getStatus()) || "tao".equals(mLibaoEntity.getStatus())) {
                List<UserDataLibaoEntity> userLibaooList = mLibaoEntity.getMe().getUserDataLibaoList();
                if (userLibaooList != null && userLibaooList.size() > 0) {
                    UserDataLibaoEntity userDataLibaoEntity = userLibaooList.get(userLibaooList.size() - 1);
                    if ("ling".equals(userDataLibaoEntity.getType())) {
                        mLibaoEntity.setStatus("linged");
                    } else {
                        mLibaoEntity.setStatus("taoed");
                    }
                }
            }
            checkLibaoStatus();
        } else {
            performClickReceiveBtn();
        }
        mSkeleton.hide();
    }

    @Override
    public void loadDone(Object obj) { // 在当前详情页领取获取淘号的数据
        if (obj != null) {
            Intent data = new Intent();
            data.putExtra(UserDataLibaoEntity.TAG, (UserDataLibaoEntity) obj);
            requireActivity().setResult(Activity.RESULT_OK, data);
        }
    }

    @Override
    public void loadError() {
        mLibaoDetailRv.setVisibility(View.GONE);
        mLlLoading.setVisibility(View.GONE);
        mLibaoDetailRv.setPadding(0, 0, 0, 0);
        mNoConnection.setVisibility(View.VISIBLE);

        mSkeleton.hide();
    }

    @Override
    public void loadEmpty() {
        mLibaoDetailRv.setVisibility(View.GONE);
        mLlLoading.setVisibility(View.GONE);
        mNoneData.setVisibility(View.VISIBLE);
        mLibaoDetailRv.setPadding(0, 0, 0, 0);
//        if (mAdapter.getLibaoDetailEntity() == null) {
//            mNoneDataTv.setText("页面不见了~");
//            toast("内容可能已被删除");
//        } else {
//            mNoneDataTv.setText("天了噜~页面不见了");
//        }

        mSkeleton.hide();
    }

    @Override
    public void loadNotFound() {
        mLibaoDetailRv.setVisibility(View.GONE);
        mLlLoading.setVisibility(View.GONE);
        mDataExceptionView.setVisibility(View.VISIBLE);
        mLibaoDetailRv.setPadding(0, 0, 0, 0);

        mSkeleton.hide();
    }

    // 领取/淘号失败，根据返回的时间重新倒数
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBUISwitch swith) {
        if (LibaoUtils.REFRESH_LIBAO_TIME.equals(swith.getFrom())) {
            mBaseHandler.sendEmptyMessageDelayed(1, swith.getPosition());
        }
    }

    // 接收下载被删除消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EBDownloadStatus status) {
        if ("delete".equals(status.getStatus())
                && mGameEntity != null
                && mGameEntity.getApk().size() == 1) {
            String url = mGameEntity.getApk().get(0).getUrl();
            if (url.equals(status.getUrl())) {
                DetailDownloadUtils.updateViewHolder(getDetailViewHolder());
            }
        }
    }

    // 接受安装、卸载消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBPackage busFour) {
        if (mGameEntity != null
                && mGameEntity.getApk().size() > 0) {
            for (ApkEntity apkEntity : mGameEntity.getApk()) {
                String packageName = apkEntity.getPackageName();
                if (packageName.equals(busFour.getPackageName())) {
                    ApkActiveUtils.filterHideApk(mGameEntity);
                    DetailDownloadUtils.updateViewHolder(getDetailViewHolder());
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBReuse reuse) {
        if (reuse.getType().equals(LOGIN_TAG) && mLibaoEntity != null) { // 登入
            getLibaoDigest(mLibaoEntity.getId());
        }
    }


    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        ExtensionsKt.setRootBackgroundColor(mCachedView, com.gh.gamecenter.common.R.color.ui_background);
        mDetailBottom.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_background));
        mLibaoDetailRv.getRecycledViewPool().clear();
        mAdapter.notifyItemRangeChanged(0, mAdapter.getItemCount());
        if (mGameEntity != null) {
            DetailDownloadUtils.updateViewHolder(getDetailViewHolder());
        }
        if (mLibaoDetailRv.getItemDecorationCount() > 0) {
            mLibaoDetailRv.removeItemDecorationAt(0);
            mLibaoDetailRv.addItemDecoration(getItemDecoration());
        }
    }
}
