package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kfzs.appstore.utils.adapter.recyclerview.RecyclerViewAdapter;
import com.kfzs.appstore.utils.adapter.recyclerview.ViewHolder;
import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.CMCCExchange;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.ActivityManager;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.RefreshUtil;
import com.sheep.gamegroup.util.SelfCountDownTimer;
import com.sheep.gamegroup.util.StringUtils;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;
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/12.
 * realicing@sina.com
 * 移动积分兑换页面
 */
public class FgtExchangeCMCC extends BaseFragment implements View.OnClickListener {
    private SmartRefreshLayout refresh;
    /**
     * 我的积分
     */
    private TextView exchange_cmcc_my_core;
    /**
     * 查询积分
     */
    private TextView exchange_cmcc_look;
    /**
     * 积分数
     */
    private TextView exchange_cmcc_num;
    /**
     * 积分兑换的商品列表
     */
    private RecyclerView exchange_cmcc_list;
    /**
     * 兑换说明详情
     */
    private TextView exchange_cmcc_info;
    /**
     * 积分兑换结果
     */
    private TextView exchange_cmcc_result;
    /**
     * 兑换说明
     */
    private TextView exchange_cmcc_tip;

    @Override
    public boolean userButterKnife() {
        return false;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fgt_exchange_cmcc;
    }

    private Activity activity;

    @Override
    public void onViewCreated() {
        activity = getActivity();
        initView(getView());
        initListener();
    }

    private void initData() {
        SheepApp.getInstance().getNetComponent().getApiService().getCMCCGoods()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        List<CMCCExchange> newList = baseMessage.getDataList(CMCCExchange.class);
                        list.clear();
                        ListUtil.addAllItem(list, newList);
                        exchange_cmcc_list.getAdapter().notifyDataSetChanged();
                        refresh.finishRefresh();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                        refresh.finishRefresh();
                    }
                });
    }

    private List<CMCCExchange> list = ListUtil.emptyList();

    private void initListener() {
        setLayoutParamsTop(exchange_cmcc_my_core, 160 / 375.0F);
        setLayoutParamsTop(exchange_cmcc_look, 170 / 375.0F);
        setLayoutParamsTop(exchange_cmcc_num, 180 / 375.0F);
        exchange_cmcc_result.setOnClickListener(this);
        exchange_cmcc_look.setOnClickListener(this);
        GridLayoutManager layoutManager = new GridLayoutManager(activity, 2);
        exchange_cmcc_list.setLayoutManager(layoutManager);
        exchange_cmcc_list.setNestedScrollingEnabled(false);
        exchange_cmcc_list.setAdapter(new RecyclerViewAdapter<CMCCExchange>(activity, R.layout.item_exchange_cmcc, list) {
            @Override
            public void convert(ViewHolder viewHolder, CMCCExchange item, final int position) {
                TextView item_exchange_cmcc_score = viewHolder.itemView.findViewById(R.id.item_exchange_cmcc_score);
                TextView item_exchange_cmcc_amout = viewHolder.itemView.findViewById(R.id.item_exchange_cmcc_amout);
                TextView item_exchange_cmcc_commit = viewHolder.itemView.findViewById(R.id.item_exchange_cmcc_commit);
                if (item == null) {
                    ViewUtil.setDefaultText(item_exchange_cmcc_score);
                    ViewUtil.setDefaultText(item_exchange_cmcc_amout);
                } else {
                    ViewUtil.setText(item_exchange_cmcc_score, String.format(Locale.CHINA, "%d积分兑换", item.getScore()));
                    ViewUtil.setText(item_exchange_cmcc_score, String.format(Locale.CHINA, "%s绵羊币", NumberFormatUtils.retainMost2(item.getAmount())));
                    item_exchange_cmcc_commit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            G.showToast(R.string.coming_soon);
                        }
                    });
                }
            }
        });
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initData();
            }
        });
        RefreshUtil.newInstance().publicParameter(refresh, activity);
        initData();
    }

    private void setLayoutParamsTop(View view, float ratio) {
        ViewGroup.LayoutParams viewLayoutParams = view.getLayoutParams();
        if (viewLayoutParams instanceof RelativeLayout.LayoutParams) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) viewLayoutParams;
            layoutParams.topMargin = (int) (G.WIDTH * ratio);
            view.setLayoutParams(layoutParams);
        }
    }

    public void initView(View view) {
        refresh = view.findViewById(R.id.refresh);
        exchange_cmcc_my_core = (TextView) view.findViewById(R.id.exchange_cmcc_my_core);
        exchange_cmcc_look = (TextView) view.findViewById(R.id.exchange_cmcc_look);
        exchange_cmcc_num = (TextView) view.findViewById(R.id.exchange_cmcc_num);
        exchange_cmcc_list = view.findViewById(R.id.exchange_cmcc_list);
        exchange_cmcc_info = (TextView) view.findViewById(R.id.exchange_cmcc_info);
        exchange_cmcc_tip = (TextView) view.findViewById(R.id.exchange_cmcc_tip);
        exchange_cmcc_result = (TextView) view.findViewById(R.id.exchange_cmcc_result);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.exchange_cmcc_look:
                showCMCCLookDialog(activity, new DialogConfig().setParentLayoutId(R.layout.dialog_parent_cmcc).setLayoutId(R.layout.x_msg_dialog_cmcc_look)
                        .setTitle("查询积分"));
                break;
            case R.id.exchange_cmcc_result://查询积分兑换结果
                ViewUtil.showMsgDialog(activity, new DialogConfig().setParentLayoutId(R.layout.dialog_parent_cmcc).setLayoutId(R.layout.x_msg_dialog_cmcc)
                        .setTitle("确认兑换").setMsg("\n确认是进行兑换吗\n").setBtnLeftText("取消").setBtnRightText("兑换")
                        .setBtnRightOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //TODO 兑换积分操作
                            }
                        }));
                break;
        }
    }

    private SelfCountDownTimer selfCountDownTimer;

    public AlertDialog showCMCCLookDialog(Context context, final DialogConfig dialogConfig) {
        final Context mContext = context == null ? ActivityManager.getInstance().currentActivity() : context;
        String title = dialogConfig.getTitle();
        final View.OnClickListener btnCloseOnClickListener = dialogConfig.getBtnCloseOnClickListener();
        View dialog_parent = View.inflate(mContext, dialogConfig.getParentLayoutId(), null);
        final AlertDialog dialog = new AlertDialog.Builder(mContext, mContext instanceof Activity ? R.style.MyDialogActivityTheme : R.style.AppTheme_Dialog_Alert).setView(dialog_parent).create();
        TextView dialog_title = dialog_parent.findViewById(R.id.dialog_title);
        switch (dialogConfig.getTheme()) {//设置按钮风格
            case DialogConfig.THEME_PURPLE:
                dialog_title.setBackgroundResource(R.drawable.shape_purple_solid_rectangle_top);
                break;
        }
        View dialog_close = dialog_parent.findViewById(R.id.dialog_close);
        LinearLayout dialog_center_ll = dialog_parent.findViewById(R.id.dialog_center_ll);
        final View view = LayoutInflater.from(mContext).inflate(dialogConfig.getLayoutId(), dialog_center_ll, true);
        if (!TextUtils.isEmpty(title))
            dialog_title.setText(title);

        final EditText dialog_cmcc_look_phone = (EditText) view.findViewById(R.id.dialog_cmcc_look_phone);
        final EditText dialog_cmcc_look_code = (EditText) view.findViewById(R.id.dialog_cmcc_look_code);
        final TextView dialog_cmcc_look_code_send = (TextView) view.findViewById(R.id.dialog_cmcc_look_code_send);
        TextView dialog_cmcc_look_commit = (TextView) view.findViewById(R.id.dialog_cmcc_look_commit);
        if (selfCountDownTimer == null) {
            selfCountDownTimer = new SelfCountDownTimer(60 * 1000, 1000, SelfCountDownTimer.FULL_SECOND) {
                @Override
                public void onTimerRest() {
                    dialog_cmcc_look_code_send.setEnabled(true);
                    dialog_cmcc_look_code_send.setText(getString(R.string.send_sms));
                }

                @Override
                public void onTimerTick(long millisUntilFinished, int countTime) {
                    dialog_cmcc_look_code_send.setText(String.format(Locale.CHINA, "%d s", countTime));
                }

                @Override
                public void onTimerFinish() {
                    dialog_cmcc_look_code_send.setEnabled(true);
                    dialog_cmcc_look_code_send.setText(getString(R.string.send_sms));
                }
            };
        }
        String mobile = DataUtil.getInstance().getUserMobile();
        if (StringUtils.isMobile(mobile)) {
            dialog_cmcc_look_phone.setEnabled(false);
            dialog_cmcc_look_phone.setText(mobile);
        }
        dialog_cmcc_look_code_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendSms(dialog_cmcc_look_phone.getText().toString(), dialog_cmcc_look_code_send);
            }
        });
        dialog_cmcc_look_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                lookScore(dialog_cmcc_look_phone.getText().toString(), dialog_cmcc_look_code.getText().toString());
            }
        });

        if (dialog_close != null) {
            if (dialogConfig.isCancelable())//
                dialog_close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (btnCloseOnClickListener != null) {
                            btnCloseOnClickListener.onClick(v);
                        }
                        dialog.dismiss();
                    }
                });
            else
                dialog_close.setVisibility(View.GONE);
        }
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                try {
                    if (dialogConfig.isFinish()) {
                        if (mContext instanceof Activity) {
                            ((Activity) mContext).finish();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        if (!(mContext instanceof Activity) && dialog.getWindow() != null) {
            dialog.getWindow().setType(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? WindowManager.LayoutParams.TYPE_PHONE : WindowManager.LayoutParams.TYPE_TOAST);
        }
        if (!dialogConfig.isCancelable())
            dialog.setCancelable(false);
        try {
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dialog;
    }

    private String phone;

    //查询积分前发送手机验证码
    private void sendSms(String phone, final View send) {
        selfCountDownTimer.reset(SelfCountDownTimer.FULL_SECOND);
        if (StringUtils.isMobile(phone)) {
            send.setEnabled(false);
            this.phone = phone;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mobile", phone);
            SheepApp.getInstance().getNetComponent().getApiService().smsCMCC(jsonObject)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                        @Override
                        public void onNext(BaseMessage baseMessage) {
                            selfCountDownTimer.start();
                            G.showToast("发送验证码成功");
                        }

                        @Override
                        public void onError(BaseMessage baseMessage) {
                            send.setEnabled(true);
                            G.showToast(baseMessage);
                        }
                    });
        } else {
            G.showToast("请填写正确的手机号!");
        }
    }

    //查询积分
    private void lookScore(String phone, String code) {
        if (TextUtils.isEmpty(code)) {
            G.showToast("验证码不能为空!");
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mobile", this.phone);
            jsonObject.put("code", code);
            SheepApp.getInstance().getNetComponent().getApiService().getCMCCScore(jsonObject)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                        @Override
                        public void onNext(BaseMessage baseMessage) {
                        }

                        @Override
                        public void onError(BaseMessage baseMessage) {
                            G.showToast(baseMessage);
                        }
                    });
        }
    }
}
