package com.tencent.qcloud.tuikit.tuichat.ui.view.input.inputmore;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

import com.google.android.material.tabs.TabLayout;
import com.tencent.qcloud.tuikit.tuichat.R;
import com.tencent.qcloud.tuikit.tuichat.ui.view.input.BaseInputFragment;
import com.tencent.qcloud.tuikit.tuichat.widget.TabFragmentAdapter;
import com.zxhl.cms.localmodle.EventBusUpdateXinDongZhiBean;
import com.zxhl.cms.net.ApiClient;
import com.zxhl.cms.net.RxSchedulers;
import com.zxhl.cms.net.SettingPreference;
import com.zxhl.cms.net.callback.BaseObserver;
import com.zxhl.cms.net.model.chat.ChatGiftListBackEntity;
import com.zxhl.cms.net.model.uc.UserInfo;
import com.zxhl.cms.pay.StarCoinPayActivity;
import com.zxhl.cms.utils.UserDataUtils;
import com.zxhl.cms.utils.Utils;
import com.zxhl.cms.widget.ChatDialogUtils;

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

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

/**
 * @Description: java类作用描述
 * @Author: lidandan
 * @CreateDate: 2021/12/25 4:31 下午
 */
public class CustomInputGiftFragment extends BaseInputFragment {

    private TabLayout mConversionChatTL;
    private ViewPager mConversionChatVP;

    private TabFragmentAdapter mTabFragmentAdapter;
    private List<Fragment> mFragmentList;
    //星币余额
    private AppCompatTextView mStarBalanceTV;
    //首次充值
    private AppCompatTextView mFirstRechargeTV;

    private boolean isReCharge = false;

    private String chatUserId;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            chatUserId = bundle.getString("chatUserId");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View baseView = inflater.inflate(R.layout.fragment_conversion_chat_gift, container, false);

        return baseView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mStarBalanceTV = view.findViewById(R.id.star_balance_tv);
        mConversionChatTL = view.findViewById(R.id.conversion_chat_gift_tl);
        mConversionChatVP = view.findViewById(R.id.conversion_chat_gift_vp);
        mConversionChatTL.setTabTextColors(Color.parseColor("#5C5F66"), Color.parseColor("#AA60FF"));
        mConversionChatTL.setTabMode(TabLayout.MODE_SCROLLABLE);
        mConversionChatTL.setTabGravity(TabLayout.GRAVITY_START);

        mFragmentList = new ArrayList<>();
        //点击充值
        view.findViewById(R.id.chat_goto_recharge_tv).setOnClickListener(v -> {
            isReCharge = true;
            Intent intent = new Intent(getContext(), StarCoinPayActivity.class);
            startActivity(intent);
        });

        mFirstRechargeTV = view.findViewById(R.id.chat_first_goto_recharge_tv);
        mFirstRechargeTV.setOnClickListener(v -> {
            ChatDialogUtils.showFirstReChargeDialog(getActivity(), new ChatDialogUtils.ChatDialogCallBack() {
                @Override
                public void confirm() {
                    isReCharge = true;
                    Intent intent = new Intent(getContext(), StarCoinPayActivity.class);
                    startActivity(intent);
                }

                @Override
                public void cancel() {

                }
            });
        });

        UserInfo userInfo = SettingPreference.getUserInfoData();
        if (userInfo != null) {
            mStarBalanceTV.setText(userInfo.starBalance + "");
            mFirstRechargeTV.setVisibility(userInfo.noRecharged ? View.VISIBLE : View.GONE);
        }

        ApiClient.INSTANCE.getChatApi().getChatGiftList("").compose(RxSchedulers.observableIO2Main()).subscribe(new BaseObserver<List<ChatGiftListBackEntity>>() {
            @Override
            public void onSuccess(List<ChatGiftListBackEntity> result) {
                if (result != null) {
                    updateGiftInfo(result);
                }
            }

            @Override
            public void onFailure(Throwable e, String code, String errorMsg) {
                Utils.showToast(getContext(), errorMsg);
            }
        });
        EventBus.getDefault().register(this);
    }

    /**
     * 更新礼物相关信息
     */
    private void updateGiftInfo(List<ChatGiftListBackEntity> result) {
        if (result == null || result.size() <= 0) {
            return;
        }
        List<ChatGiftListBackEntity> titleList = new ArrayList<>();
        for (ChatGiftListBackEntity giftListBackEntity : result) {
            if (giftListBackEntity == null || TextUtils.isEmpty(giftListBackEntity.title)) {
                continue;
            }
            titleList.add(giftListBackEntity);
            ConversionChatGiftFragment fragment = new ConversionChatGiftFragment();
            Bundle bundle = new Bundle();
            bundle.putSerializable("giftInfo", giftListBackEntity);
            bundle.putString("chatUserId", chatUserId);
            fragment.setArguments(bundle);
            mFragmentList.add(fragment);
        }

        mTabFragmentAdapter = new TabFragmentAdapter(titleList, getChildFragmentManager(), mFragmentList);
        mConversionChatVP.setAdapter(mTabFragmentAdapter);
        mConversionChatTL.setupWithViewPager(mConversionChatVP);
        mConversionChatTL.setSelectedTabIndicator(0);
        for (int i = 0; i < mConversionChatTL.getTabCount(); i++) {
            TabLayout.Tab tab = mConversionChatTL.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(getTabView(i));
            }
        }
        setSelectedTabView(0);
        mConversionChatVP.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                setSelectedTabView(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

    }

    /**
     * 更新个人星币相关信息
     */
    private void updateGifsInfo() {
        UserInfo userInfo = SettingPreference.getUserInfoData();
        if (userInfo != null) {
            mStarBalanceTV.setText(userInfo.starBalance + "");
        }
    }

    /**
     * 进入初始化tablayout选中状态
     *
     * @param position
     */
    private void setSelectedTabView(int position) {
        for (int i = 0; i < mConversionChatTL.getTabCount(); i++) {
            TabLayout.Tab tab = mConversionChatTL.getTabAt(i);
            if (tab != null) {
                TextView tabTitleTV = (TextView) tab.getCustomView();
                if (position == i) {
                    tabTitleTV.setTextColor(Color.parseColor("#AA60FF"));
                } else {
                    tabTitleTV.setTextColor(Color.parseColor("#5C5F66"));
                }
            }
        }
    }

    /**
     * 创建tablayout布局
     *
     * @param position
     * @return
     */
    private View getTabView(int position) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_conversion_chat_gift_tab, mConversionChatTL, false);

        TextView title = view.findViewById(R.id.tab_title);
        title.setText(mTabFragmentAdapter.getPageTitle(position));
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isReCharge) {
            UserDataUtils.INSTANCE.updateUserInfo((code, result) -> updateGifsInfo());
            isReCharge = false;
        }
    }

    /**
     * 发送完礼物后更新个人星币
     *
     * @param eventBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateStarBalanceInfo(EventBusUpdateXinDongZhiBean eventBean) {
        UserDataUtils.INSTANCE.updateUserInfo((code, result) -> {
            if (code == 0) {
                updateGifsInfo();
            }
        });
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
