package com.hw.nativeapp.ui.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.qrcode.encoder.QRCode;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hw.nativeapp.MApplication;
import com.hw.nativeapp.R;
import com.hw.nativeapp.httpnet.ErrorConsumer;
import com.hw.nativeapp.httpnet.ResponseConsumer;
import com.hw.nativeapp.utils.ActivityUtils;
import com.hw.nativeapp.utils.ImageUtils;
import com.hw.nativeapp.utils.RxUtil;
import com.squareup.picasso.Picasso;

import butterknife.BindView;
import butterknife.OnClick;


public class PaymentMethodActivity extends BaseActivity  {

    public static final Integer COUNTDOWN_TIME = 120000;
    private CountDownTimer timer;
    private CountDownTimer orderTimer;
    private TitleBar titleBar;

    @BindView(R.id.wechat_pay)
    ImageView wechat_pay;


    private String orderId = "";
    private String total = "";
    private String totalPeice = "";
    private String idcard = "";
    private JSONArray viewerList = new  JSONArray();

    @Override
    void initView() {
        titleBar = findViewById(R.id.tb_main_bar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                stopOrderCountDownTimer();
                ActivityUtils.activityFinish(PaymentMethodActivity.this, true );
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });
        getPageTransmitParams();
        getGotoNativePay();
        startCountDownTimer();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment_method);
    }

    //获取页面传递参数
    private void getPageTransmitParams(){
        Intent transmitIntent = getIntent();
        orderId = transmitIntent.getStringExtra("orderId");
        idcard = transmitIntent.getStringExtra("idcard");
        total = transmitIntent.getStringExtra("total");
        totalPeice = transmitIntent.getStringExtra("totalPeice");
        viewerList = JSONArray.parseArray(transmitIntent.getStringExtra("viewerList"));
    }
    // 订单支付
    private void getGotoNativePay(){
        JSONObject options = new JSONObject();
        options.put("orderId", orderId);
        MApplication.getApiService().gotoNativePay( options, System.currentTimeMillis() / 1000)
                .compose(RxUtil.applyObservableAsync())
                .subscribe(new ResponseConsumer<JSONObject>() {
                    @Override
                    public void onSuccess(JSONObject data) {
                        if(data.getBooleanValue("needPay")){
                            String payInfo = data.getString("payInfo");
                            //微信支付
                            Bitmap weiEQ = ImageUtils.createQRImage(payInfo, 600, 600);
                            wechat_pay.setImageBitmap(weiEQ);
//                            String payType = "alipay";
//                            if(payType.equals("alipay")){
//                                //支付宝支付
//
//                            } else {
//                                //微信支付
//                                Bitmap weiEQ = ImageUtils.createQRImage(payInfo, 600, 600);
//                                wechat_pay.setImageBitmap(weiEQ);
//                            }
                            // 开始循环查询订单状态
                            orderCountDownTimer();
                        }
                    }

                    @Override
                    public void onFailed(int code, String msg) {

                    }
                }, new ErrorConsumer());
    }
    // 订单支付
    private void getPayQuery(){
        JSONObject options = new  JSONObject();
        options.put("orderId", orderId);
        MApplication.getApiService().payQuery( options, System.currentTimeMillis() / 1000)
                .compose(RxUtil.applyObservableAsync())
                .subscribe(new ResponseConsumer<JSONObject>() {
                    @Override
                    public void onSuccess(JSONObject data) {
                        // 支付状态: 0-未支付 1-已支付 2-支付中 3-支付失败 4-支付退款
                        if(data.getIntValue("payStatus") != 0 && data.getIntValue("payStatus") != 2){
                            stopOrderCountDownTimer();
                            Bundle bundle = new Bundle();
                            bundle.putString("orderId", orderId);
                            bundle.putString("idcard", idcard);
                            bundle.putString("total", total);
                            bundle.putString("totalPeice", totalPeice);
                            bundle.putString("payAmount", data.getString("payAmount"));
                            bundle.putString("payStatus", String.valueOf(data.getIntValue("payStatus")));
//                            bundle.putString("viewerList", JSONArray.toJSONString(viewerList));
                            ActivityUtils.launchActivity(PaymentMethodActivity.this, ScanCodePayActivity.class, bundle);
                            ActivityUtils.activityFinish(PaymentMethodActivity.this, true );
                        }
                    }

                    @Override
                    public void onFailed(int code, String msg) {

                    }
                }, new ErrorConsumer());
    }

    private void stopOrderCountDownTimer(){
        if (orderTimer != null){
            orderTimer.cancel();
        }
    }
    private void orderCountDownTimer(){
        orderTimer = new CountDownTimer(COUNTDOWN_TIME, 2000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                getPayQuery();
            }

            @Override
            public void onFinish() {

            }
        };
        orderTimer.start();
    }

    private void jumpToLogin(){
        stopCountDownTimer();
        ActivityUtils.activityFinish(PaymentMethodActivity.this, true);
    }
    private void stopCountDownTimer(){
        if (timer != null){
            timer.cancel();
        }
        stopOrderCountDownTimer();
    }
    private void startCountDownTimer(){
        timer = new CountDownTimer(COUNTDOWN_TIME, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                titleBar.setRightTitle(millisUntilFinished / 1000 + "s");
            }

            @Override
            public void onFinish() {
                jumpToLogin();
            }
        };
        timer.start();
    }
}