package com.sheep.gamegroup.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.entity.PayOrder;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;

import java.util.List;
import java.util.Locale;

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

/**
 * Created by realicing on 2018/10/18.
 * realicing@sina.com
 * 支付界面
 */
public class ActPay extends BaseActivity{


    @Override
    protected boolean needButterKnife() {
        return false;
    }

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

    private TextView pay_commit;
    private TextView pay_msg_tv;
    private TextView pay_info;
    private TextView pay_amount;
    private TextView pay_amount2;

    private List<View> payOrderViewList = ListUtil.emptyList();
    private List<View> successViewList = ListUtil.emptyList();
    private List<View> failedViewList = ListUtil.emptyList();
    @Override
    public void initView() {
        ImageView title_img_back = findViewById(R.id.title_img_back);
        pay_commit = findViewById(R.id.pay_commit);
        TextView title_cancel = findViewById(R.id.title_cancel);
        pay_msg_tv = findViewById(R.id.pay_msg_tv);
        View pay_line = findViewById(R.id.pay_line);
        ImageView pay_sheep_iv = findViewById(R.id.pay_sheep_iv);
        pay_info = findViewById(R.id.pay_info);
        pay_amount = findViewById(R.id.pay_amount);
        pay_amount2 = findViewById(R.id.pay_amount2);
        TextView pay_success = findViewById(R.id.pay_success);
        TextView pay_failed = findViewById(R.id.pay_failed);
        TextView pay_failed_reason = findViewById(R.id.pay_failed_reason);
        payOrderViewList.add(title_img_back);
        payOrderViewList.add(title_cancel);
        payOrderViewList.add(pay_msg_tv);
        payOrderViewList.add(pay_amount);
        payOrderViewList.add(pay_line);

        successViewList.add(pay_sheep_iv);
        successViewList.add(pay_info);
        successViewList.add(pay_amount2);
        successViewList.add(pay_success);

        failedViewList.add(pay_sheep_iv);
        failedViewList.add(pay_info);
        failedViewList.add(pay_amount2);
        failedViewList.add(pay_failed);
        failedViewList.add(pay_failed_reason);
        setViewListVisible(successViewList, View.INVISIBLE);
        setViewListVisible(failedViewList, View.INVISIBLE);
        resetView();
    }
    //设置viewList中的view是否可见
    private void setViewListVisible(List<View> viewList, int visible) {
        for (View view : viewList) {
            view.setVisibility(visible);
        }
    }

    private void resetView() {
        ViewUtil.setDefaultText(pay_msg_tv);
        ViewUtil.setDefaultText(pay_amount);
    }

    @Override
    public void initListener() {
        pay_commit.setEnabled(false);
    }

    private PayOrder payOrder;
    private String token;

    @Override
    public void initData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        String order_no = null;
        if(bundle != null) {
            order_no = bundle.getString("order_no");
            token = bundle.getString("token");
        }
        if(TextUtils.isEmpty(order_no)){//传过来的数据有问题
            status = STATUS_INIT_ERROR_ORDER_NO;
            G.showToast(R.string.coming_soon);
            return;
        }
        if(TextUtils.isEmpty(order_no)){//传过来的数据有问题
            status = STATUS_INIT_ERROR_TOKEN;
            G.showToast(R.string.coming_soon);
            return;
        }
        if(BuildConfig.DEBUG)
            G.showToast(String.format(Locale.CHINA, "%s\t%s", order_no, token));
        //初始化PayOrder
        SheepApp.getInstance().getNetComponent().getApiService().sdkFindOrder(token, order_no)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        payOrder = baseMessage.getData(PayOrder.class);
                        if (payOrder != null) {
                            status = STATUS_GET_ORDER_SUCCESS;
                            pay_commit.setEnabled(true);
                            loadPayOrder();
                        } else {
                            status = STATUS_GET_ORDER_SUCCESS_ERROR;
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        status = STATUS_GET_ORDER_ERROR;
                        G.showToast(baseMessage);
                    }
                });
    }
    //加载PayOrder
    private void loadPayOrder() {
        ViewUtil.setText(pay_msg_tv, payOrder.getName());
        String amountText = getString(R.string.x_yuan, NumberFormatUtils.retainMost2(payOrder.getPayMoney()));
        ViewUtil.setColorMapText(pay_amount, amountText, "元", "#FFFFFF");
        ViewUtil.setColorMapText(pay_amount2, amountText, "元", "#FFFFFF");
        ViewUtil.setText(pay_info, getString(R.string.sheep_order_no, payOrder.getName(), payOrder.getOrderNo()));
    }
    //点击底部按钮
    public void onClickBottomBtn(View view) {
        switch (status) {
            case STATUS_GET_ORDER_SUCCESS://立即支付
                SheepApp.getInstance().getNetComponent().getApiService().sdkPayOrder(token, payOrder.getOrderNo())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                            @Override
                            public void onNext(BaseMessage baseMessage) {
                                status = STATUS_PAY_ORDER_SUCCESS;
                                G.showToast(baseMessage);
                                showPaySuccess();
                            }

                            @Override
                            public void onError(BaseMessage baseMessage) {
                                status = STATUS_PAY_ORDER_ERROR;
                                G.showToast(baseMessage);
                                showPayFailed();
                                failedReason = baseMessage.getMsg();
                            }
                        });
                break;
            case STATUS_PAY_ORDER_SUCCESS:
            case STATUS_PAY_ORDER_ERROR://返回商家
                setStatusResult();
                finish();
                break;
        }
    }
    private String failedReason;
    //点击查看失败原因
    public void onClickFailedReason(View view) {
        G.showToast(failedReason);
    }

    @Override
    public void onBackPressed() {
        onClickCancel(null);
    }
    private int status = STATUS_INIT;//状态 正常状态大于0 错误状态小于0
    public static final int STATUS_INIT = 0;//初始状态
    public static final int STATUS_GET_ORDER_SUCCESS = 1;//获取order成功
    public static final int STATUS_PAY_ORDER_SUCCESS = 2;//支付order成功
    public static final int STATUS_GET_ORDER_ERROR = -1;//获取order错误
    public static final int STATUS_PAY_ORDER_ERROR = -2;//支付order错误
    public static final int STATUS_INIT_ERROR_ORDER_NO = -3;//初始化时获取到的order_no为空
    public static final int STATUS_INIT_ERROR_TOKEN = -4;//初始化时获取到的token为空
    public static final int STATUS_GET_ORDER_SUCCESS_ERROR = -5;//获取order接口成功，但是无数据
    //点击返回
    public void onClickBackImg(View view) {
        onClickCancel(null);
    }

    //取消订单
    public void onClickCancel(View view) {
        if(status == STATUS_PAY_ORDER_SUCCESS || status < STATUS_INIT){//支付成功或者各种失败的情况下直接退出界面
            setStatusResult();
            finish();
            return;
        }
        ViewUtil.showMsgDialog(this, new DialogConfig().setTitle("提示").setMsg("您要取消订单吗？")
                .setBtnRightText("取消").setBtnLeftText("确认").setBtnLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        setStatusResult();
                        finish();
                    }
                }));
    }
    public static final int RESULT_CODE = 666;
    public static final String EXTRA_NAME_STATUS = "status";
    //返回结果给sdk
    private void setStatusResult(){
        setResult(RESULT_CODE, new Intent().putExtra(EXTRA_NAME_STATUS, status));
    }
    //展示支付失败界面
    private void showPayFailed() {
        setViewListVisible(payOrderViewList, View.INVISIBLE);
        setViewListVisible(failedViewList, View.VISIBLE);
        pay_commit.setText("返回商家");
    }
    //展示支付成功界面
    private void showPaySuccess() {
        setViewListVisible(payOrderViewList, View.INVISIBLE);
        setViewListVisible(successViewList, View.VISIBLE);
        pay_commit.setText("返回商家");
    }
}
