package com.sheep.gamegroup.view.dialog;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.GamePayList;
import com.sheep.gamegroup.model.entity.GridViewEntity;
import com.sheep.gamegroup.model.entity.PayEntity;
import com.sheep.gamegroup.model.entity.RechargeEntity;
import com.sheep.gamegroup.model.entity.WithdrawalList;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.MyGridview;
import com.sheep.gamegroup.util.MyListview;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.WithdrawalAdapter;
import com.sheep.gamegroup.view.adapter.expandadapter.AdpPayGameDialog;
import com.sheep.gamegroup.view.customview.RefreshLayout;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;

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

import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import io.reactivex.schedulers.Schedulers;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.GAME_INSTEAD_OF_RECHARGE_PAY;

/**
 * Created by ljy on 2018/6/13.
 */

public class DialogPayGame {
    private Activity activity;
    private String game_account_etStr;
    private int gao;
    private int maxShowCount;
    private RefreshLayout swipe_container;
    private MyListview pay_listview;
    private EditText money_et;
    private AdpPayGameDialog adpPayGameDialog;
    private List<RechargeEntity> list = new ArrayList<>();

    private String balance;//金额

    private String goods;
    private String pwd;
    private String role_id;
    private String role_name;
    private String service;

    private String gameId;
    private AlertDialog dialog;

    private PayEntity payEntity;

    private MyGridview myGridview;
    private List<WithdrawalList> wlLists = new ArrayList<>();
    private WithdrawalAdapter adapter;
    private int select = -1;//默认不选中
    private int lastSelect = -1;
    private String amount;

    private GamePayList gameVoucherAndRatio;

    public DialogPayGame(Activity activity, PayEntity payEntity) {
        this.activity = activity;
        this.game_account_etStr = game_account_etStr;
        this.gameId = payEntity.getGame_id();
        this.payEntity = payEntity;
        gao = SheepApp.getInstance().getResources().getDimensionPixelSize(R.dimen.content_padding_10)*5;
        maxShowCount = Math.max(6, G.HEIGHT*3/4/gao);
        balance = "";
    }

    public void showPayGame(){
        if(activity == null){
            return;
        }
        View dialog_parent = View.inflate(activity, R.layout.dialog_parent, null);
        dialog = new AlertDialog.Builder(activity, R.style.MyDialogActivityTheme)
                .setView(dialog_parent)
                .create();
        TextView dialog_title = dialog_parent.findViewById(R.id.dialog_title);
        final View dialog_close = dialog_parent.findViewById(R.id.dialog_close);
        LinearLayout dialog_center_ll = dialog_parent.findViewById(R.id.dialog_center_ll);
        View view = LayoutInflater.from(activity).inflate(R.layout.dialog_pa_game_center, dialog_center_ll, true);
        dialog_title.setText("支付中心");

        TextView sureTv = view.findViewById(R.id.pay_sure_tv);
        //你需要支付1110元
        TextView pay_game_show_price_tv = view.findViewById(R.id.pay_game_show_price_tv);
        pay_game_show_price_tv.setText("你需要支付"+ 0 +"元");
        money_et = view.findViewById(R.id.money_et);
        pay_listview = view.findViewById(R.id.pay_listview);
        adpPayGameDialog = new AdpPayGameDialog(list);
        pay_listview.setAdapter(adpPayGameDialog);

        pay_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RechargeEntity rechargeEntity = adpPayGameDialog.getItem(position);
                rechargeEntity.setSelect(!rechargeEntity.isSelect());
                adpPayGameDialog.notifyDataSetChanged();
            }
        });
        makeGridview(view);

        sureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                surePay();
            }
        });

        dialog_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
            }
        });
        try {
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
        gameId = payEntity.getGame_id();
//        initData();
        getVoucherAndRatio();
    }

    public void initData(){
        balance = "";
        ViewUtil.newInstance()
                .showProgress(activity, false);
        gameId = payEntity.getGame_id();
        SheepApp.getInstance().getNetComponent().getApiService().can_user_sheep_amount(Integer.valueOf(0), gameId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ViewUtil.newInstance()
                                .hideProgress(activity);
                        try{
                            String balances = baseMessage.getData() +"";
                            balance = TextUtils.isEmpty(balances) ? "0" : balances;


                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        getNetComponent();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        ViewUtil.newInstance()
                                .hideProgress(activity);
                        G.showToast(baseMessage);
                    }
                });

    }

    /**\
     * if(Double.valueOf(balance) > 0){
     ;
     if(Float.valueOf(game_pay_etStr) > Float.valueOf(balance)){
     balanceStr = balance;
     }else {
     balanceStr = game_pay_etStr;
     }
     RechargeEntity rechargeEntity = new RechargeEntity();
     rechargeEntity.setSelect(true);
     rechargeEntity.setId(3);
     rechargeEntity.setName("绵羊币 (可用"+ 0 +") 指非定向货币+定向货币");
     list.add(rechargeEntity);
     }
     */
    private void getNetComponent(){
        ViewUtil.newInstance()
                .showProgress(activity, false);
        // 参数 1：没有绵羊币的，2：是全部
        SheepApp.getInstance().getNetComponent().getApiService().getRechargePayway("1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(activity) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ViewUtil.newInstance()
                                .hideProgress(activity);
                        List<RechargeEntity> lists = baseMessage.getDatas(RechargeEntity.class);
                        list.clear();
                        try{
                            RechargeEntity rechargeEntity = new RechargeEntity();
                            rechargeEntity.setSelect(true);
                            rechargeEntity.setId(3);
                            rechargeEntity.setName("绵羊币 (可用"+ 0 +") 指非定向货币+定向货币");
                            list.add(rechargeEntity);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        if(!lists.isEmpty()){
                            list.addAll(lists);

                            int size = Math.min(maxShowCount, ListUtil.size(list));
                            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, size * gao);
                            pay_listview.setLayoutParams(layoutParams);
                            adpPayGameDialog.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        ViewUtil.newInstance()
                                .hideProgress(activity);
                        G.showToast(baseMessage.getMsg() + "");
                    }
                });
    }
    /**
     * 支付提交
     * account	string
     账号

     amount	number($double)
     充值金额

     game_id	string
     游戏id

     goods	string
     商品

     pay_type	integer($int64)
     支付方式：1支付宝 2微信 3绵羊币

     pwd	string
     密码

     role_id	string
     角色Id

     role_name	string
     角色名称

     service	string
     区服

     use_voucher	boolean
     是否用绵羊币 true：用 false：不用
     */
    private void surePay(){

        if(ListUtil.hasIndex(wlLists, select)) {
            amount = wlLists.get(select).getGridViewEntity().getValue();
            if (TextUtils.isEmpty(amount)) {
                G.showToast("请选择金额");
                return;
            }

        }
        if(!TextUtils.isEmpty(money_et.getText()) && !TextUtils.isEmpty(money_et.getText().toString().trim())){
            amount = money_et.getText().toString().trim();
        }
        GAME_INSTEAD_OF_RECHARGE_PAY.onEvent();
        if(list.isEmpty()){
            return;
        }
        boolean use_voucher = false;
        boolean use_voucher_alipay = false;
        int pay_type = 3;
        for(RechargeEntity r: list){
            if(r.getId() == 3){
                if(r.isSelect()){
                    use_voucher = true;
                }else {
                    use_voucher = false;
                }
            }else {
                if(r.isSelect()){
                    pay_type = r.getId();
                    use_voucher_alipay = true;
                }else {
                    use_voucher_alipay = false;
                }
            }
        }
        if(!use_voucher && !use_voucher_alipay){
            G.showToast("请选择支付方式");
            return;
        }
        if(TextUtils.isEmpty(amount)){
            G.showToast("请输入正确的金额!");
            return;
        }
        ViewUtil.newInstance()
                .showProgress(activity, false);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", payEntity.getAccount());
        jsonObject.put("amount", Float.valueOf(amount));//todo
        jsonObject.put("game_id", payEntity.getGame_id()+"");
        jsonObject.put("pay_type", pay_type);
        jsonObject.put("use_voucher", use_voucher);

        jsonObject.put("goods", payEntity.getGoods());
        jsonObject.put("pwd", payEntity.getPwd());
        jsonObject.put("role_id", payEntity.getRole_id());
        jsonObject.put("role_name", payEntity.getRole_name());
        jsonObject.put("service", payEntity.getService());
        jsonObject.put("tencent_platform", payEntity.getTencent_platform());
        final int finalPay_type = pay_type;
        SheepApp.getInstance().getNetComponent().getApiService().game_consumption(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(activity) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ViewUtil.newInstance()
                                .hideProgress(activity);
                        if(finalPay_type == 1){
                            CommonUtil.getInstance()
                                    .pay(baseMessage.getData().toString(),
                                            activity,
                                            dialog);
                        }else {
                            G.showToast("充值成功!");
                            if(dialog != null)
                                dialog.dismiss();
                        }

                    }

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

    /**
     * gridview
     */
    private void makeGridview(View view){

        wlLists.clear();
        for(int i=0;i<3;i++){
            WithdrawalList withdrawalList = new WithdrawalList();
            GridViewEntity g;
            switch (i){
                case 0:
                default:
                    g = new GridViewEntity(false, "10");
                    break;
                case 1:
                    g = new GridViewEntity(false, "50");

                    break;
                case 2:
                    g = new GridViewEntity(false, "100");

                    break;
            }
            withdrawalList.setGridViewEntity(g);
            wlLists.add(withdrawalList);
        }

        myGridview = view.findViewById(R.id.withdrawal_greidview);
        adapter = new WithdrawalAdapter(activity, wlLists);
        myGridview.setVerticalSpacing(25);
        myGridview.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        myGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                wlLists.get(position).getGridViewEntity().setSelectState(true);
                if(ListUtil.hasIndex(wlLists, select) && select != position){
                    wlLists.get(select).getGridViewEntity().setSelectState(false);
                }
                if(ListUtil.hasIndex(wlLists, lastSelect) && lastSelect != position){
                    wlLists.get(lastSelect).getGridViewEntity().setSelectState(false);
                    lastSelect = -1;
                }
                select = position;
                adapter.notifyDataSetChanged();
                makePriceShow(wlLists.get(position).getGridViewEntity().getValue());
                money_et.setText("");
            }
        });

        money_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s)) {//输入有金额，清除上面选中的金额,并重新一份计价
                    cleanClick();
                    makePriceShow(s.toString());
                } else if(ListUtil.hasIndex(wlLists, lastSelect)) {//没有输入金额，默认选中之前的金额
                    wlLists.get(lastSelect).getGridViewEntity().setSelectState(true);
                    adapter.notifyDataSetChanged();
                    select = lastSelect;
                }
            }
        });
    }


    /**
     * 获取可用金额和比率
     */
    private void getVoucherAndRatio(){

        CommonUtil.getInstance()
                .getVoucherAndRatio(activity, gameId, new Action1<BaseMessage>() {
                    @Override
                    public void call(BaseMessage baseMessage) {
                        if(baseMessage != null){
                            gameVoucherAndRatio = baseMessage.getData(GamePayList.class);
                        }
                        getNetComponent();
                    }
                });
    }

    /**
     * 计算金额显示
     */
    private void makePriceShow(String price){
        if(ListUtil.isEmpty(list) || gameVoucherAndRatio == null || TextUtils.isEmpty(price))
            return;
        double showPrice = gameVoucherAndRatio.getGift_ratio() * Long.valueOf(price) /100;
        double priceDouble = NumberFormatUtils.decimal(showPrice > gameVoucherAndRatio.getVoucher() ? gameVoucherAndRatio.getVoucher() + gameVoucherAndRatio.getUser_balance(): showPrice + gameVoucherAndRatio.getUser_balance(), 2);
        String p = "绵羊币 (可用"+ priceDouble +") 指非定向货币+定向货币";
        TextView textView = pay_listview.getChildAt(0).findViewById(R.id.pay_game_dialog_item_tv);
        textView.setText(p);
        list.get(0).setName(p);
        adpPayGameDialog.notifyDataSetChanged();
    }

    /**
     * 清除gridview 选中
     */
    private void cleanClick(){
        if(ListUtil.hasIndex(wlLists, select)) {
            wlLists.get(select).getGridViewEntity().setSelectState(false);
            adapter.notifyDataSetChanged();
            lastSelect = select;
        }
    }
}
