package com.sheep.gamegroup.view.activity;

import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.alipay.PayResult;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.RechargeEntity;
import com.sheep.gamegroup.model.entity.RechargePriceEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.MyGridview;
import com.sheep.gamegroup.view.adapter.RechargeAdapter;
import com.sheep.gamegroup.view.adapter.RechargePriceAdapter;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

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

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

/**
 * Created by Administrator on 2018/3/19.
 * 充值界面
 */

public class SignRechargeAct extends BaseActivity {

    int mPayType = -1;//选择支付方式的id
    String mAmount = null;//支付的金额

    @BindView(R.id.rechargeprice_greidview)
    MyGridview rechargeprice_greidview;
    @BindView(R.id.recharge_greidview)
    MyGridview rechargeGreidview;

    RechargeAdapter rechargeAdapter;
    @BindView(R.id.et_recharge_price)
    EditText etRechargePrice;

    RechargePriceAdapter rechargePriceAdapter;
    List<RechargePriceEntity> mPriceEntityList = new ArrayList<>();
    int select = -1;

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

    @Override
    public void initView() {
        TitleBarUtils.getInstance()
                .setTitle(this, "充值")
                .setShowOrHide(this, true)
                .setTitleFinish(this);
    }

    @Override
    public void initListener() {
    }

    @Override
    public void initData() {

        addDatas();
        /*
          支付金额选择
         */
        rechargePriceAdapter = new RechargePriceAdapter(SignRechargeAct.this, mPriceEntityList);
        rechargeprice_greidview.setVerticalSpacing(20);
        rechargeprice_greidview.setAdapter(rechargePriceAdapter);
        rechargeprice_greidview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                select = position;
                rechargePriceAdapter.setInPut(false);
                RechargePriceEntity rechargePriceEntity = (RechargePriceEntity) parent.getItemAtPosition(position);
                etRechargePrice.setText("" + rechargePriceEntity.getPrice());
                for (int i = 0; i < mPriceEntityList.size(); i++) {
                    if (position == i) {
                        mPriceEntityList.get(i).setSelectState(true);
                    } else {
                        mPriceEntityList.get(i).setSelectState(false);
                    }
                }
                rechargePriceAdapter.notifyDataSetChanged();

            }
        });

        /*
          支付方式选择
         */
        rechargeAdapter = new RechargeAdapter(SignRechargeAct.this);
        rechargeGreidview.setVerticalSpacing(40);
        rechargeGreidview.setAdapter(rechargeAdapter);
        rechargeGreidview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RechargeEntity rechargeEntity = (RechargeEntity) parent.getItemAtPosition(position);
                mPayType = rechargeEntity.getId();
                rechargeAdapter.setSelect(position);
                rechargeAdapter.notifyDataSetChanged();
            }
        });


        showProgress();
        getRechargePayway();
    }

    private void getRechargePayway() {
        // 参数 1：没有绵羊币的，2：是全部
        SheepApp.getInstance().getNetComponent().getApiService().getRechargePayway("1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SignRechargeAct.this) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        hideProgress();
                        List<RechargeEntity> list = baseMessage.getDatas(RechargeEntity.class);
                        if(list != null && list.size() > 0){
                            mPayType = list.get(0).getId();
                            rechargeAdapter.setSelect(0);
                        }
                        rechargeAdapter.addAll(list);
                        if(!list.isEmpty()) {
                            mPayType = list.get(0).getId();
                            rechargeAdapter.setSelect(0);
                            rechargeAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        hideProgress();
                        G.showToast(baseMessage.getMsg() + "");
                    }
                });
    }

    private void getRechargeBalance() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Amount", Float.valueOf(mAmount));
        jsonObject.put("PayType", mPayType);
        SheepApp.getInstance().getNetComponent().getApiService().getRechargeBalance(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SignRechargeAct.this) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        hideProgress();
                        pay(baseMessage.getData().toString());
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        hideProgress();
                        G.showToast(baseMessage.getMsg() + "");
                    }
                });
    }

    @OnClick({R.id.tv_recharge_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.tv_recharge_pay:
                if (mPayType == -1) {
                    G.showToast("请选择支付方式");
                    return;
                }

                mAmount = etRechargePrice.getText().toString().trim();
                if(android.text.TextUtils.isEmpty(mAmount)){
                    G.showToast("请输入充值金额");
                    return;
                }


                showProgress();
                getRechargeBalance();
                break;
        }
    }

    private void pay(final String payInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(SignRechargeAct.this);
                // 调用支付接口，获取支付结果
                final String result = alipay.pay(payInfo, true);

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {

                        PayResult payResult = new PayResult(result);
                        /*
                          同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                          detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                          docType=1) 建议商户依赖异步通知
                         */
//						String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                        String resultStatus = payResult.getResultStatus();
                        Jump2View.getInstance().goRechargeResultAct(SignRechargeAct.this, resultStatus);
                        finish();
                    }
                });
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    private void addDatas() {
        mPriceEntityList.add(new RechargePriceEntity(false,"10元", 10));
        mPriceEntityList.add(new RechargePriceEntity(false,"20元", 20));
        mPriceEntityList.add(new RechargePriceEntity(false,"50元", 50));
        mPriceEntityList.add(new RechargePriceEntity(false,"100元", 100));
        mPriceEntityList.add(new RechargePriceEntity(false,"200元", 200));
        mPriceEntityList.add(new RechargePriceEntity(false,"500元", 500));
    }
}
