package com.sheep.gamegroup.view.dialog;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
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.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
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.GameAccountEntity;
import com.sheep.gamegroup.model.entity.GridViewEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ViewUtil;
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.model.entity.TaskEty.TASK_TYPE_GAME_TECENT;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_GAME_XIAO_MI;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.USER_GAME_ACCOUNT_ADD_COMMIT;

/**
 * Created by ljy on 2018/7/10.
 */

public class DialogAddAccount {
    private Activity activity;

    private List<GameAccountEntity> gameAccountEntity = new ArrayList<>();
    private ArrayList<GridViewEntity> gamePlatorEntity = new ArrayList<>();
    private ArrayList<GameAccountEntity> gameAccountListEntity = new ArrayList<>();

    private int game_type;
    private int task_id;
    private String account;
    private String password;
    private TextView game_account_game_list_tv_spinner;
    private EditText game_account_et;
    private TextView game_account_plator_spinner_tv;
    private RadioGroup radio_group_tencent;

    //qq:1 wx:2
    private int tencentType;

    private boolean isSelectRadio;

    public DialogAddAccount(Activity activity) {
        this.activity = activity;
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                switch (msg.what) {
                    case 0:
                        if (game_account_game_list_tv_spinner == null)
                            return;

                        game_account_game_list_tv_spinner.setVisibility((Integer) msg.obj);
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public void showAddAccount(final Action1<Integer> action1) {
        if (activity == null)
            return;
        platformData();
        View dialog_parent = View.inflate(activity, R.layout.dialog_parent, null);
        final AlertDialog 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_add_account, dialog_center_ll, true);
        dialog_title.setText("添加账号");

        /**
         * radio_group_tencent
         */
        radio_group_tencent = view.findViewById(R.id.radio_group_tencent);

        TextView sureTv = view.findViewById(R.id.add_sure_tv);
        game_account_et = view.findViewById(R.id.game_account_et);
        final EditText game_pwd_et = view.findViewById(R.id.game_pwd_et);

        game_account_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) {
                if (!TextUtils.isEmpty(s) && s.length() > 0&& CommonUtil.getInstance().clickTime(500)) {
                    intitDataAccountList(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        /**
         * 平台列表
         * gamePlatorEntity
         * R.layout.dialog_item_game_list
         */
        game_account_plator_spinner_tv = view.findViewById(R.id.game_account_plator_spinner_tv);
        game_account_plator_spinner_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPlotFormList();
            }
        });
        selectPlatform(0);

        /**
         * 游戏列表
         * gameAccountEntity
         * if(game_type < 1) {
         G.showToast("请选择游戏平台!");
         return;
         }
         intitDataGameList(game_type);
         */
        game_account_game_list_tv_spinner = view.findViewById(R.id.game_account_game_list_tv_spinner);
        game_account_game_list_tv_spinner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intitDataGameList(game_type);
            }
        });

        final RadioButton conmon_id = view.findViewById(R.id.conmon_id);
        final RadioButton fixation_id = view.findViewById(R.id.fixation_id);
        RadioGroup radio_group = view.findViewById(R.id.radio_group);
        radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // 获取选中的RadioButton的id
                int id = group.getCheckedRadioButtonId();
                // 通过id实例化选中的这个RadioButton
                RadioButton choise = (RadioButton) activity.findViewById(id);

                Message message = new Message();
                message.what = 0;
                if (id == R.id.conmon_id) {
                    message.obj = View.GONE;
                    isSelectRadio = false;
                }
                if (id == R.id.fixation_id) {
                    message.obj = View.VISIBLE;
                    isSelectRadio = true;
                }
                mHandler.sendMessage(message);
            }
        });

        radio_group_tencent.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                // 获取选中的RadioButton的id
                int id = group.getCheckedRadioButtonId();
                // 通过id实例化选中的这个RadioButton
                RadioButton choise = (RadioButton) activity.findViewById(id);
                switch (id){
                    case R.id.conmon_id_tencent:
                        tencentType = 1;
                        break;
                    case R.id.fixation_id_tencent:
                        tencentType = 2;
                        break;
                }
            }
        });


        /**
         * 添加账号提交
         */
        sureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                USER_GAME_ACCOUNT_ADD_COMMIT.onEvent();
                account = game_account_et.getText().toString().trim();
                password = game_pwd_et.getText().toString().trim();
                if (TextUtils.isEmpty(account)) {
                    G.showToast("请选择或输入游戏账号");
                    return;
                }
                if (game_type < 1) {
                    G.showToast("请选择游戏平台");
                    return;
                }

                if(radio_group_tencent.isShown() &&tencentType < 1){
                    G.showToast("请选择QQ或微信");
                    return;
                }
                if(task_id < 1 && isSelectRadio){
                    G.showToast("请选择游戏");
                    return;
                }

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("account", account);
                jsonObject.put("password", password);
                jsonObject.put("task_id", task_id);
                jsonObject.put("game_type", game_type);//Todo
                jsonObject.put("tencent_platform", tencentType);//Todo

                ViewUtil.newInstance().showProgress(activity);
                SheepApp.getInstance()
                        .getNetComponent()
                        .getApiService()
                        .addGameAccount(jsonObject)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                            @Override
                            public void onError(BaseMessage baseMessage) {

                                ViewUtil.newInstance().hideProgress(activity);
                                G.showToast(baseMessage);
                            }

                            @Override
                            public void onNext(BaseMessage baseMessage) {
                                ViewUtil.newInstance().hideProgress(activity);
                                G.showToast("添加成功");
                                if(action1 != null)
                                    action1.call(1);
                                dialog.dismiss();
                            }
                        });

            }
        });

        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();
        }
    }

    /**
     * 平台数据
     */
    private void platformData() {
        gamePlatorEntity.clear();
        gamePlatorEntity.add(new GridViewEntity(false, "平台游戏", 1002 + ""));
        gamePlatorEntity.add(new GridViewEntity(false, "小米游戏", TASK_TYPE_GAME_XIAO_MI + ""));
        gamePlatorEntity.add(new GridViewEntity(false, "腾讯游戏", 1003 + ""));
    }

    /**
     * 游戏任务列表
     *
     * @param game_type
     */
    private void intitDataGameList(int game_type) {

        ViewUtil.newInstance().showProgress(activity);
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .getGameList(game_type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {

                        ViewUtil.newInstance().hideProgress(activity);
                        G.showToast(baseMessage.getMsg() + "");
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress(activity);
                        List<GameAccountEntity> gameAccountEntitys = baseMessage.getDatas(GameAccountEntity.class);
                        if (!ListUtil.isEmpty(gameAccountEntitys)) {
                            gameAccountEntity.clear();
                            gameAccountEntity.addAll(gameAccountEntitys);
                            showListGame();
                        }
                    }
                });
    }

    private void intitDataAccountList(String account) {

        if (game_type < 1) {
            G.showToast("请选择游戏平台!");
            return;
        }
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .getGameAccountList(game_type, account, task_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {

                        G.showToast(baseMessage.getMsg() + "");
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        List<GameAccountEntity> gameAccountEntitys = baseMessage.getDatas(GameAccountEntity.class);
                        if (!ListUtil.isEmpty(gameAccountEntitys)) {
                            gameAccountListEntity.clear();
                            gameAccountListEntity.addAll(gameAccountEntitys);
                            showListAccount();
                        }
                    }
                });
    }

    /**
     * 游戏列表显示
     */
    private void showListGame(){
        SelfPopupWindow.newInstance()
                .SelfPopupWindow(activity, game_account_game_list_tv_spinner, new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                selectGame(position);
                                SelfPopupWindow.newInstance().hidePop();
                            }
                        },
                        new com.sheep.gamegroup.view.adapter.ArrayAdapter<GameAccountEntity>(activity, R.layout.dialog_item_game_list, gameAccountEntity) {
                            @Override
                            public boolean convert(int position, View convertView, ViewGroup parent, GameAccountEntity item) {
                                final TextView name_tv = convertView.findViewById(R.id.name_tv);
                                ViewUtil.setText(name_tv, item.getTask_name());
                                return true;
                            }
                        })
                .initPopup()
                .showPop();
    }


    /**
     * 账号列表显示
     */
    private void showListAccount(){
        SelfPopupWindow.newInstance()
                .SelfPopupWindow(activity, game_account_et, new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                selectAccount(position);
                                SelfPopupWindow.newInstance().hidePop();
                            }
                        },
                        new com.sheep.gamegroup.view.adapter.ArrayAdapter<GameAccountEntity>(activity, R.layout.dialog_item_game_list, gameAccountListEntity) {
                            @Override
                            public boolean convert(int position, View convertView, ViewGroup parent, GameAccountEntity item) {
                                final TextView name_tv = convertView.findViewById(R.id.name_tv);
                                ViewUtil.setText(name_tv, item.getTask_name());
                                return true;
                            }
                        })
                .initPopup()
                .showPop();
    }

    private void selectAccount(int position) {
        GameAccountEntity item = ListUtil.getItem(gameAccountListEntity, position);
        if(item == null)
            return;
        ViewUtil.setText(game_account_et, item.getTask_name());
//                                task_id = entity.getTask_id();
    }

    /**
     * 平台显示
     */
    private void showPlotFormList() {
        SelfPopupWindow.newInstance()
                .SelfPopupWindow(activity, game_account_plator_spinner_tv, new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                selectPlatform(position);
                                SelfPopupWindow.newInstance().hidePop();
                            }
                        },
                        new com.sheep.gamegroup.view.adapter.ArrayAdapter<GridViewEntity>(activity, R.layout.dialog_item_game_list, gamePlatorEntity) {
                            @Override
                            public boolean convert(int position, View convertView, ViewGroup parent, GridViewEntity item) {
                                final TextView name_tv = convertView.findViewById(R.id.name_tv);
                                ViewUtil.setText(name_tv, item.getName());
                                return true;
                            }
                        })
                .initPopup()
                .showPop();
    }

    private void selectPlatform(int position) {
        GridViewEntity item = ListUtil.getItem(gamePlatorEntity, position);
        if(item == null)
            return;
        ViewUtil.setText(game_account_plator_spinner_tv, item.getName());
        int new_game_type = NumberFormatUtils.parseInteger(item.getTask_type());
        if(new_game_type != game_type) {//选择不同平台时，游戏重置
            ViewUtil.setText(game_account_game_list_tv_spinner);
            task_id = 0;
        }
        game_type = new_game_type;
        if(game_type == TASK_TYPE_GAME_TECENT && radio_group_tencent != null){//腾讯游戏
            radio_group_tencent.setVisibility(View.VISIBLE);
        }else {
            radio_group_tencent.setVisibility(View.GONE);
        }

    }

    private void selectGame(int position) {
        GameAccountEntity item = ListUtil.getItem(gameAccountEntity, position);
        if(item == null)
            return;
        ViewUtil.setText(game_account_game_list_tv_spinner, item.getTask_name());
        task_id = item.getTask_id();
    }
}
