package com.danding.yang800.Presenter;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.android.volley.RequestQueue;
import com.danding.yang800.BuildConfig;
import com.danding.yang800.General.HttpCallBack;
import com.danding.yang800.General.SingleRequestQueue;
import com.danding.yang800.General.Yang800App;
import com.danding.yang800.LoginActivity;
import com.danding.yang800.Util.GeneralUtil;
import com.danding.yang800.Util.LogUtil;
import com.danding.yang800.Util.StringUtil;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.Util.VolleyUtil;
import com.danding.yang800.Vo.BuyGiftFlagVO;
import com.danding.yang800.Vo.GiftInfoVO;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by Administrator on 2017/1/12.
 */
public class LoginActivityPresenter {
    private LoginActivity context;
    SharedPreferences sp;
    RequestQueue requestQueue;
    public static final String APP_ID = "wx8cba515fdff29f38";// 微信开放平台申请到的app_id
    private static final String WEIXIN_SCOPE = "snsapi_userinfo";// 用于请求用户信息的作用域
    IWXAPI api;

    public LoginActivityPresenter(LoginActivity context) {
        sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
        this.context = context;
        requestQueue = SingleRequestQueue.getRequestQueue(context);
    }

    public void wxLogin() {
        if (!GeneralUtil.isWXAppInstalledAndSupported(context)) {
            ToastUtil.show(context, "未安装微信客户端");
            return;
        }
        api = Yang800App.getApi(context);
        SendAuth.Req req = new SendAuth.Req();
        req.scope = WEIXIN_SCOPE;
        api.sendReq(req);
        sp.edit().putBoolean("WXlogin", true).commit();
    }

    public void login(final String mobile, final String code, final String epCode) {
        if (mobile.equals("") || code.equals("")) {
            ToastUtil.show(context, "手机号或验证码不能为空！");
            return;
        }
        context.initDialog();
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("mobile", mobile);
        map.put("code", code);
        map.put("epCode", epCode);
        new VolleyUtil(context).request(context, "login.mobileLogin", true, map, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject json) {
                LogUtil.d(json.toString());
                try {
                    JSONObject jsonData = json.getJSONObject("result");
                    boolean login;
                    boolean referral;
                    boolean shopGiftBagFlag = true;
                    try {
                        referral = jsonData.getBoolean("referral");
                        login = jsonData.getBoolean("login");
                    } catch (Exception e) {
                        referral = false;
                        login = true;
                    }

                    if (login) {
                        JSONObject jsonUser = jsonData.getJSONObject("user");
//                    String status = jsonUser.getString("status");
                        int userId = jsonUser.getInt("userId");
                        sp.edit().putInt("userId", userId).commit();
                        String token = jsonUser.getString("token");
                        sp.edit().putString("token", token).commit();
                        JSONObject jsonStore = jsonData.getJSONObject("store");
                        String storeId = jsonStore.getString("id");
                        String referralCode = "";
                        try {
                            referralCode = StringUtil.toString(jsonStore.getString("referralCode"));
                            shopGiftBagFlag = jsonUser.getBoolean("shopGiftBagFlag");

                        } catch (Exception e) {
                        }
                        sp.edit().putString("storeId", storeId).commit();
                        sp.edit().putString("referralCode", referralCode).commit();
                    }
                    LogUtil.d(shopGiftBagFlag + "shopGiftBagFlag");
                    if (!shopGiftBagFlag) {
                        buyCheck();
                    } else {
                        context.loginSuccess(login, referral);
                    }
                    context.dismissDialog();
                } catch (Exception e) {
                    e.printStackTrace();
                    onCatch();
                }
            }


            @Override
            public void onerrSuccess() {
                context.dismissDialog();
            }

            @Override
            public void onCatch() {
                context.dismissDialog();
            }

            @Override
            public void onFail() {
                context.dismissDialog();
            }
        });

    }

    public void smsSend(final String mobile) {
        if (mobile.equals("")) {
            ToastUtil.show(context, "手机号不能为空！");
            return;
        }
        context.initDialog();
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("mobile", mobile);
        map.put("type", "loginPhone");
        new VolleyUtil(context).request(context, "sms.send", true, map, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject json) {
                LogUtil.d(json.toString());
                try {
                    context.sendSuccess();
                    context.dismissDialog();
                } catch (Exception e) {
                    e.printStackTrace();
                    onCatch();
                }
            }

            @Override
            public void onerrSuccess() {
                context.dismissDialog();
            }

            @Override
            public void onCatch() {
                context.dismissDialog();
            }

            @Override
            public void onFail() {
                context.dismissDialog();
            }
        });
    }

    public void weixinLogin(final String code, final String epCode) {
        // ToastUtil.show(loginActivity, code);
        //	Log.i("TAG", "result  url=" + url + "\t code =: " + code);、
        context.initDialog();
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("wxCode", code);
        map.put("epCode", epCode);
        new VolleyUtil(context).request(context, "login.wx", true, map, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject json) {
                LogUtil.d(json.toString());
                try {
                    JSONObject jsonData = json.getJSONObject("result");
                    String nickName = jsonData.getString("nickName");
                    boolean login = jsonData.getBoolean("login");
                    boolean referral;
                    try {
                        referral = jsonData.getBoolean("referral");
                    } catch (Exception e) {
                        referral = false;
                    }
                    boolean shopGiftBagFlag = true;
                    String status = "";
                    if (login) {
                        JSONObject jsonUser = jsonData.getJSONObject("user");
//                        status = jsonUser.getString("status");
                        int userId = jsonUser.getInt("userId");
                        sp.edit().putInt("userId", userId).commit();
                        String token = jsonUser.getString("token");
                        sp.edit().putString("token", token).commit();
                        JSONObject jsonStore = jsonData.getJSONObject("store");
                        String storeId = jsonStore.getString("id");
                        String referralCode = "";
                        try {
                            referralCode = StringUtil.toString(jsonStore.getString("referralCode"));
                            shopGiftBagFlag = jsonUser.getBoolean("shopGiftBagFlag");
                        } catch (Exception e) {

                        }
                        sp.edit().putString("storeId", storeId).commit();
                        sp.edit().putString("referralCode", referralCode).commit();
                    }
                    if (!shopGiftBagFlag) {
                        buyCheck();
                    } else {
                        context.wxSuccess(login, nickName, referral);
                    }
                    context.dismissDialog();
                } catch (Exception e) {
                    e.printStackTrace();
                    onCatch();
                }
            }

            @Override
            public void onerrSuccess() {
                context.dismissDialog();
            }

            @Override
            public void onCatch() {
                context.dismissDialog();
            }

            @Override
            public void onFail() {
                context.dismissDialog();
            }
        });

    }

    public void getUploadImgUrl() {
        // ToastUtil.show(loginActivity, code);
        //	Log.i("TAG", "result  url=" + url + "\t code =: " + code);、
        HashMap<String, String> map = new HashMap<>();
        new VolleyUtil(context).request(context, "store.getUploadImgUrl", true, map, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject json) {
                LogUtil.d(json.toString());
                try {
                    JSONObject jsonData = json.getJSONObject("result");
                    String uploadImgUrl = jsonData.getString("uploadImgUrl");
                    sp.edit().putString("uploadImgUrl", uploadImgUrl).commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    onCatch();

                }

            }


            @Override
            public void onerrSuccess() {
            }

            @Override
            public void onCatch() {
            }

            @Override
            public void onFail() {
            }
        });

    }

    public void buyCheck() {
        HashMap<String, String> map = new HashMap<>();
        new VolleyUtil(context).request(context, "goods.giftBag.buyCheck", true, map, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject json) {
                try {
                    Gson gson = new Gson();
                    BuyGiftFlagVO bean = gson.fromJson(json.toString(), BuyGiftFlagVO.class);
                    BuyGiftFlagVO.ResultBean result = bean.getResult();
                    String buyGiftBagFlag = result.getBuyGiftBagFlag();
                    boolean singleFlag = result.isSingleFlag();
                    String storeSkuSn = result.getStoreSkuSn();
                    if (buyGiftBagFlag.equals("false")) {
                        context.toMain();
                    } else if (singleFlag) {
                        context.toGifitInfo(storeSkuSn);
                    } else {
                        context.toGiftList();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onCatch();
                }
            }

            @Override
            public void onerrSuccess() {

            }

            @Override
            public void onCatch() {
            }

            @Override
            public void onFail() {
            }
        });

    }
}