package com.datarecovery.master.module.member;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Pair;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.atmob.app.lib.base.BaseActivity;
import com.atmob.common.ui.SizeUtil;
import com.datarecovery.master.databinding.ActivityMemberBinding;
import com.datarecovery.master.dialog.AlipayQrCodeDialog;
import com.datarecovery.master.dialog.ChoosePaymentWayDialog;
import com.datarecovery.master.dialog.CommonLoadingDialog;
import com.datarecovery.master.dialog.MemberRetentionDialog;
import com.datarecovery.master.dialog.WechatPayQrCodeDialog;
import com.datarecovery.master.module.audiorecover.AudioRecoverActivity;
import com.datarecovery.master.module.filerecover.FileRecoverActivity;
import com.datarecovery.master.module.imgrecover.ImageRecoverActivity;
import com.datarecovery.master.module.videorecover.VideoRecoverActivity;
import com.datarecovery.master.module.wxrecover.WeChatRecoverActivity;
import com.datarecovery.master.utils.BoxingUtil;
import com.datarecovery.master.utils.GridLayoutItemDecoration;
import com.gyf.immersionbar.ImmersionBar;

import java.util.Objects;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class MemberActivity extends BaseActivity<ActivityMemberBinding> {


    public static final String MEMBER_TYPE = "member_type";
    private MemberViewModel memberViewModel;

    private GoodsItemAdapter goodsItemAdapter;

    private NormalScenesAdapter normalScenesAdapter;
    private SuperScenesAdapter superScenesAdapter;
    private GridLayoutManager gridLayoutManager;
    private GridLayoutItemDecoration gridLayoutItemDecoration;
    private MemberEvaluateAdapter memberEvaluateAdapter;
    private MemberRetentionDialog memberRetentionDialog;
    private ChoosePaymentWayDialog choosePaymentWayDialog;
    private CommonLoadingDialog commonLoadingDialog;
    private AlipayQrCodeDialog alipayQrCodeDialog;
    private WechatPayQrCodeDialog wechatPayQrCodeDialog;

    private int maxScrollY;


    public static void start(Context context, @MemberType String type) {
        Intent intent = new Intent(context, MemberActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(MEMBER_TYPE, type);
        context.startActivity(intent);
    }

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

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            memberViewModel.setMemberType(intent.getStringExtra(MEMBER_TYPE));
        }
    }

    private void initView() {
        goodsItemAdapter = new GoodsItemAdapter(this);
        binding.memberDetailList.setAdapter(goodsItemAdapter);
        binding.memberDetailList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        goodsItemAdapter.setOnItemSelectListener(goodsBean -> memberViewModel.setSelectBean(goodsBean));
        normalScenesAdapter = new NormalScenesAdapter();
        superScenesAdapter = new SuperScenesAdapter();
        gridLayoutManager = new GridLayoutManager(this, 4);
        binding.scenesRyView.setLayoutManager(gridLayoutManager);
        gridLayoutItemDecoration = new GridLayoutItemDecoration();
        binding.scenesRyView.addItemDecoration(gridLayoutItemDecoration);

        memberEvaluateAdapter = new MemberEvaluateAdapter();
        binding.userEvaluateRyView.setLayoutManager(new LinearLayoutManager(this));
        binding.userEvaluateRyView.setAdapter(memberEvaluateAdapter);

        binding.iconBack.setOnClickListener(v -> onBackPressed());

        maxScrollY = (int) (SizeUtil.getScreenHeight() * 0.2f);
        binding.nestedScrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            if (scrollY > maxScrollY) {
                binding.viewStatusBar.setAlpha(1f);
                binding.viewToolBar.setAlpha(1f);
                binding.tvTitle.setAlpha(1f);
            } else {
                binding.viewStatusBar.setAlpha(scrollY * 1f / maxScrollY);
                binding.viewToolBar.setAlpha(scrollY * 1f / maxScrollY);
                binding.tvTitle.setAlpha(scrollY * 1f / maxScrollY);
            }
        });
    }

    private void initObserver() {
        memberViewModel.getOnSubscribeSuccessEvent().observe(this, orderId -> {
            dismissQrCodeDialog(orderId);
            setPaySuccessGo();
        });
        memberViewModel.getGoTargetActEvent().observe(this, o -> setPaySuccessGo());
        memberViewModel.getShowAliQRPaymentEvent().observe(this, this::showAlipayQrCodeDialog);
        memberViewModel.getShowWxQRPaymentEvent().observe(this, this::showWxQrCodeDialog);
        memberViewModel.getShowLoadingEvent().observe(this, this::showLoading);
        memberViewModel.getMemberGoodsList().observe(this, goodsItemAdapter::submit);
        memberViewModel.getSelectBean().observe(this, bean -> {
            if (bean == null) {
                return;
            }
            if (Objects.equals(bean.getAuths(), MemberType.APP_SUPER_RECOVER)) {
                gridLayoutManager.setSpanCount(4);
                gridLayoutItemDecoration.setParam(4, 0, 0.0361111111111111f);
                superScenesAdapter.setData(memberViewModel.getSuperScenesBeans());
                binding.scenesRyView.setAdapter(superScenesAdapter);
            } else {
                gridLayoutManager.setSpanCount(2);
                gridLayoutItemDecoration.setParam(2, 0, 0.0166666666666667f);
                normalScenesAdapter.setData(bean.getScenesArray());
                binding.scenesRyView.setAdapter(normalScenesAdapter);
            }
        });
        memberViewModel.getEvaluateList().observe(this, evaluateBeans -> memberEvaluateAdapter.submit(evaluateBeans));
        memberViewModel.getShowChoicePayWayDialog().observe(this, o -> showChoosePaymentWayDialog());
    }

    private void setPaySuccessGo() {
        finish();
        switch (memberViewModel.getMemberType()) {
            case MemberType.APP_WX_MESSAGE_RECOVER:
                WeChatRecoverActivity.start(this, MemberType.APP_WX_MESSAGE_RECOVER);
                break;
            case MemberType.APP_WX_FRIEND_RECOVER:
                WeChatRecoverActivity.start(this, MemberType.APP_WX_FRIEND_RECOVER);
                break;
            case MemberType.APP_IMAGE_RECOVER:
                ImageRecoverActivity.start(this, ImageRecoverActivity.Type.RECOVER);
                break;
            case MemberType.APP_FILE_RECOVER:
                FileRecoverActivity.start(this);
                break;
            case MemberType.APP_VIDEO_RECOVER:
                VideoRecoverActivity.start(this);
                break;
            case MemberType.APP_AUDIO_RECOVER:
                AudioRecoverActivity.start(this);
                break;
            case MemberType.APP_IMAGE_CLEAN:
                ImageRecoverActivity.start(this, ImageRecoverActivity.Type.DELETE);
                break;
        }
    }

    private void showWxQrCodeDialog(Pair<String, String> params) {
        if (params == null || params.first == null || params.second == null) {
            return;
        }
        if (wechatPayQrCodeDialog == null) {
            wechatPayQrCodeDialog = new WechatPayQrCodeDialog(this);
        }
        wechatPayQrCodeDialog.show(params.first, params.second, memberViewModel);
    }

    private void showAlipayQrCodeDialog(Pair<String, String> params) {
        if (params == null || params.first == null || params.second == null) {
            return;
        }
        if (alipayQrCodeDialog == null) {
            alipayQrCodeDialog = new AlipayQrCodeDialog(this);
        }
        alipayQrCodeDialog.show(params.first, params.second, memberViewModel);
    }

    private void dismissQrCodeDialog(String orderId) {
        if (alipayQrCodeDialog != null) {
            if (Objects.equals(orderId, alipayQrCodeDialog.getCurrentOrderId())) {
                alipayQrCodeDialog.dismiss();
            }
        }
        if (wechatPayQrCodeDialog != null) {
            if (Objects.equals(orderId, wechatPayQrCodeDialog.getCurrentOrderId())) {
                wechatPayQrCodeDialog.dismiss();
            }
        }
    }


    private void showLoading(Boolean show) {
        if (BoxingUtil.boxing(show)) {
            if (commonLoadingDialog == null) {
                commonLoadingDialog = new CommonLoadingDialog(this);
                commonLoadingDialog.setMessageGone();
            }
            commonLoadingDialog.show();
        } else {
            if (commonLoadingDialog != null) {
                commonLoadingDialog.dismiss();
            }
        }
    }

    private void showChoosePaymentWayDialog() {
        if (choosePaymentWayDialog == null) {
            choosePaymentWayDialog = new ChoosePaymentWayDialog(this, this, memberViewModel.getSubscribeTxt(), memberViewModel.getPayWayList().getValue());
        }
        choosePaymentWayDialog.setActionHandler((payPlatform, payMethod) -> memberViewModel.submitOrder(payPlatform, payMethod));
        choosePaymentWayDialog.paymentShow();
    }

    private void showMemberRetentionDialog() {
        if (memberRetentionDialog == null) {
            memberRetentionDialog = new MemberRetentionDialog(this)
                    .setActionHandler(new MemberRetentionDialog.ActionHandler() {
                        @Override
                        public void onCloseClick() {
                            finish();
                        }

                        @Override
                        public void onContinueClick() {
                            memberViewModel.onRetainMemberSubscribeClick();
                        }
                    });
        }
        memberRetentionDialog.show();
    }

    @Override
    public void onBackPressed() {
        if (Objects.equals(memberViewModel.getMemberType(), MemberType.APP_IMAGE_CLEAN)) {
            super.onBackPressed();
            return;
        }
        if (!memberViewModel.isMember()) {
            showMemberRetentionDialog();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void configImmersion(@NonNull ImmersionBar immersionBar) {
        immersionBar.statusBarDarkFont(true);
    }


    @Override
    protected void initViewModel() {
        super.initViewModel();
        memberViewModel = getViewModelProvider().get(MemberViewModel.class);
        binding.setMemberViewModel(memberViewModel);
    }

    @Override
    protected boolean shouldImmersion() {
        return true;
    }
}
