package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kfzs.duanduan.event.BigEvent;
import com.kfzs.duanduan.event.EventTypes;
import com.kfzs.duanduan.utils.dlg.FormatAny;
import com.sheep.gamegroup.di.components.DaggerWithdrawalComponent;
import com.sheep.gamegroup.di.modules.WithdrawalModule;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.GridViewEntity;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.entity.WithdrawalList;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.presenter.WithdrawalContract;
import com.sheep.gamegroup.presenter.WithdrawalPresenter;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.MyDbManager;
import com.sheep.gamegroup.view.adapter.WithdrawalAdapter;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

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

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

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 提现
 * Created by ljy on 2018/3/18.
 */

public class WithdrawalAct extends BaseActivity implements WithdrawalContract.View {
    @BindView(R.id.withdrawal_greidview)
    GridView withdrawalGreidview;
    @BindView(R.id.withdrawal_sure)
    TextView withdrawalSure;
    @BindView(R.id.weixin_name_tv)
    TextView weixin_name_tv;
    @BindView(R.id.withdrawal_click_bindname_tv)
    TextView withdrawal_click_bindname_tv;

    Activity activity;
    @Inject
    WithdrawalPresenter presenter;

    private List<WithdrawalList> wlLists = new ArrayList<>();

    private WithdrawalAdapter adapter;
    private ArrayList<Object> listData = new ArrayList<>();
    private int select;
    private String amount;
    private String balanceAmount = "0";//余额

    private  UserEntity userEntity;
    @Override
    protected int getLayoutId() {
        return R.layout.withdrawal_layout;
    }

    @Override
    public void initView() {
        activity = this;
        EventBus.getDefault().register(this);
        TitleBarUtils
                .getInstance()
                .setTitle(activity, "提现")
                .setTitleFinish(activity);
        DaggerWithdrawalComponent.builder()
                .netComponent(SheepApp.get(this).getNetComponent())
                .withdrawalModule(new WithdrawalModule(this))
                .build()
                .inject(this);
        adapter = new WithdrawalAdapter(activity, wlLists);
        withdrawalGreidview.setVerticalSpacing(25);
        withdrawalGreidview.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        withdrawalGreidview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                select = position;
                for(int i=0;i<wlLists.size();i++){
                    if(position == i){
                        wlLists.get(i).getGridViewEntity().setSelectState(true);
                    }else {
                        wlLists.get(i).getGridViewEntity().setSelectState(false);

                    }
                    adapter.notifyDataSetChanged();
                }
            }
        });
        showProgress();
        presenter.getCanWithdrawAmount();
        presenter.getWithdrawAmountOption();
    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {

        try {
            if (userEntity == null)
                userEntity = MyDbManager.getInstance().dbFindUser();
            if(userEntity != null){
                weixin_name_tv.setText(userEntity.getWx_nickname() +"");
            }else {
                weixin_name_tv.setText(SpUtils.getWeixin(activity)+"");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        setBalanceAmount();
    }


    @OnClick({R.id.withdrawal_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.withdrawal_sure:
                doWithdrawal();
                break;
        }
    }

    private void doWithdrawal() {
//        String price1 = ((GridViewEntity)withdrawalGreidview.getSelectedItem()).getValue();
        amount = wlLists.get(select).getGridViewEntity().getValue();
        if(TextUtils.isEmpty(amount)){
            G.showToast("请选择金额");
            return;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("amount", Float.valueOf(amount));
        jsonObject.put("type", 1);
        showProgress();
        presenter.goWithdrawal(jsonObject);
    }

    /**
     * 组装 adapter 数据
     */
    private ArrayList<Object> assemblyData(){
        listData.clear();
        listData.add(new GridViewEntity(true,10+""));
        listData.add(new GridViewEntity(false,30+""));
        listData.add(new GridViewEntity(false,50+""));
        listData.add(new GridViewEntity(false,100+""));
        listData.add(new GridViewEntity(false,500+""));
        listData.add(new GridViewEntity(false,1000+""));
        return listData;
    }

    /**
     *40001 //没有绑定真实姓名
     *40002 //没有绑定真实省份证
     *40003 //没有绑定真实银行卡
     * @param o
     */
    @Override
    public void failData(Object o) {
        hideProgress();
        try {
            BaseMessage baseMessage = (BaseMessage) o;
            switch (baseMessage.getCode()){
                case 40001:
                case 40002:
                case 40003:
                    Jump2View.getInstance().goBindDataView(activity, baseMessage.getCode());
                    break;
                default:
                    G.showToast(baseMessage.getMsg()+"");
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
            G.showToast(" 网络错误！");
        }
    }

    @Override
    public void updateView(Object o) {
        hideProgress();
        EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.ONFRESH_FGT_FAMLLSHEEP));
//        BaseMessage baseMessage = (BaseMessage) o;
        SpUtils.saveWithdral(activity, amount);
        EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.INTENT_AMOUNT_VALUE));
        Jump2View.getInstance().goWithdrawalResultview(activity, amount);
    }

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

    @Override
    public void updateBalanceView(BaseMessage o) {

        hideProgress();
        String balanceA =  o.getData() +"";
        balanceAmount = TextUtils.isEmpty(balanceA)?"0":balanceA;
        setBalanceAmount();
    }

    private void setBalanceAmount(){

        String sr = "可提现金额 <font color='#ff2d4b'><big>" + FormatAny.getInstance().formatString(balanceAmount) + "</big></font> 元";
        withdrawal_click_bindname_tv.setText(Html.fromHtml(sr));
    }

    @Override
    public void failWithdrawAmountOptionData(BaseMessage o) {
        G.showToast(o.getMsg()+"");
    }

    @Override
    public void updateWithdrawAmountOptionView(BaseMessage o) {
        try{
            List<WithdrawalList> withdrawalLists = JSONArray.parseArray(JSONArray.toJSONString(o.getData()), WithdrawalList.class);
            wlLists.clear();
            for(int i=0;i< withdrawalLists.size(); i++){
                WithdrawalList withdrawalList = withdrawalLists.get(i);
                if(withdrawalList.getType() != 2){
                    GridViewEntity gridViewEntity = new GridViewEntity();
                    if(i == 0){
                        gridViewEntity.setSelectState(true);
                    }else {
                        gridViewEntity.setSelectState(false);
                    }
                    gridViewEntity.setValue(withdrawalList.getAmount()+"");
                    withdrawalList.setGridViewEntity(gridViewEntity);

                    wlLists.add(withdrawalList);
                }

            }

            adapter.notifyDataSetChanged();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Subscribe
    public void onEventMainThread(BigEvent event){
        switch (event.getEventTypes()){
            case REFRESH_DATA_PHONE:
                refreshData();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    //Todo 刷新用户信息,可以写一个公用的
    /**
     * 刷新用户信息
     */
    private void refreshData(){
        showProgress(false);
        SheepApp.get(this)
                .getNetComponent()
                .getApiService()
                .getInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(this) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        hideProgress();
                        G.showToast(""+baseMessage.getMsg());
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        hideProgress();
                        userEntity = JSON.parseObject(JSONObject.toJSONString(baseMessage.getData()), UserEntity.class);
                        try {
                            MyDbManager.getInstance().saveOrUpdateUser(userEntity);
                            initData();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

}
