package com.tjzhxx.union.activity;

import android.os.Bundle;

import androidx.lifecycle.Lifecycle;

import com.tjzhxx.union.R;
import com.tjzhxx.union.entity.BaseResponse;
import com.tjzhxx.union.entity.request.GetPayInfoRequest;
import com.tjzhxx.union.entity.request.WxPayReq;
import com.tjzhxx.union.public_store.ConstDefine;
import com.tjzhxx.union.public_store.retrofit.RetrofitUtils;
import com.tjzhxx.union.public_store.retrofit.UnionServices;
import com.tjzhxx.union.public_store.rx.ProgressSubscriber;
import com.tjzhxx.union.system.BaseActivity;
import com.tjzhxx.union.weixinapi.WxPay;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 描述:
 *
 * @author yhx
 * @create 2021/9/11  8:58 PM
 */
public class PayActivity extends BaseActivity {
    private WxPayReq wxPayReq;
    @Override
    public int getContentViewLayoutID() {
        return R.layout.activity_pay;
    }

    @Override
    public void bindViewAndEvent(Bundle savedInstanceState) {
        initTitle("缴纳会费");
        getOrderInfoForApp();
    }


    @OnClick(R.id.pay)
    public void onClick() {
        WxPay wxPay = new WxPay(this);
        wxPay.setOnPayResultListener(new WxPay.OnPayResultListener() {
            @Override
            public void onSuccess() {
                showSnackBar("支付成功");
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        PayActivity.this.finish();
                        cancel();
                        ConstDefine.userInfo.setIsactive("1");
                    }
                }, 1000);

            }

            @Override
            public void onError() {
                    showSnackBar("支付失败");
            }
        });
        wxPay.pay(wxPayReq);
    }

    private void getOrderInfoForApp() {
        GetPayInfoRequest request = new GetPayInfoRequest();
        request.setWid(ConstDefine.userInfo.getWid());
        UnionServices services = RetrofitUtils.createApi(UnionServices.class, ConstDefine.HttpAdress);
        services.getOrderInfoForApp(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(AutoDispose.<BaseResponse<WxPayReq>>autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                .subscribe(new ProgressSubscriber<BaseResponse<WxPayReq>>(this) {
                    @Override
                    public void success(BaseResponse<WxPayReq> value) {
                        wxPayReq = value.getData();
                    }
                });
    }
}