package com.ym.library.utils;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.ym.xynt.UserInfoEntity;
import com.ym.library.MyConstant;
import com.ym.library.R;
import com.ym.library.module.WxBindEntity;
import com.ym.library.net.ApiClient;
import com.ym.library.net.BaseObserver;
import com.ym.library.net.RxSchedulers;
import com.ym.library.widget.LoadingDialog;
import com.ym.modulecommon.AppliContext;
import com.ym.modulecommon.utils.AdPreference;

import java.util.Map;

/**
 * Created by gaoleichao on 2018/6/20.
 */
public class WxImplUtils implements UMAuthListener {

    private UMShareAPI mShareAPI;
    private LoadingDialog mLoading;
    private IWxLoginCallback mCallback;
    private Context mContext = AppliContext.get();
    private static final String TAG = "WxImplUtils";
    private Activity activity;

    public void init(IWxLoginCallback mCallback, Activity activity) {
        this.mCallback = mCallback;
        this.activity = activity;
        mShareAPI = UMShareAPI.get(activity);
        mLoading = LoadingDialog.getLoadingDialog(activity, mContext.getString(R.string.wait_ing), true, true);
        mLoading.dismiss();
    }

    public void onWxLogin(Activity activity, IWxLoginCallback mCallback) {
        init(mCallback, activity);

        mLoading.setLoading(mContext.getString(R.string.login_ing));
        mLoading.show();
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        mShareAPI.setShareConfig(config);
        mShareAPI.getPlatformInfo(activity, SHARE_MEDIA.WEIXIN, this);

    }

    public void onAuth(Activity activity, IWxLoginCallback mCallback) {
        init(mCallback, activity);
        mLoading.setLoading(mContext.getString(R.string.auth_ing));
        mLoading.show();
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        mShareAPI.getPlatformInfo(activity, SHARE_MEDIA.WEIXIN, this);
    }


    @Override
    public void onStart(SHARE_MEDIA share_media) {
        Log.i(TAG, "onStart: ");
    }

    @Override
    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> data) {
        Log.i(TAG, "onComplete: ");
        dismissDialog();

        ApiClient.INSTANCE.getUserApi().bindWx(data.get("openid"), data.get("accessToken")).
                compose(RxSchedulers.observableIO2Main(mContext))
                .subscribe(new BaseObserver<WxBindEntity>() {
                    @Override
                    public void onSuccess(WxBindEntity result) {
                        Log.i(TAG, "onSuccess: " + result.getFlushToken());
                        if (result.getFlushToken() != null && !"".equals(result.getFlushToken())) {
                            AdPreference.setToken(result.getFlushToken());

                            UserInfoEntity user = SettingPreference.getUserInfoData();
                            if (user != null) {
                                user.setBind(true);
                                user.setHeadimgurl(data.get("iconurl"));
                                user.setNickname(data.get("screen_name"));
                            }
                            SettingPreference.saveUserInfo(user);
                            SettingPreference.saveUserInfoName(data.get("screen_name"));
                            mCallback.onWxSuccess(data.get("access_token"), data.get("openid"));
                        } else {
                            mCallback.onWxFail("绑定失败");
                        }


                    }

                    @Override
                    public void onFailure(Throwable e, String code, String errorMsg) {
                        String str = "绑定失败";
                        if (TextUtils.equals("105", code)) {
                            str = errorMsg;
                            mLoading.setResult(false, str, 1000);
                            mLoading.dismiss();
//                            mCallback.onWxFail(errorMsg);
                        } else if (TextUtils.equals("106", code)) {
                            str = errorMsg;
                            MyConstant.Param.uid = "";
                            MyConstant.Param.token = "";
                            AdPreference.setToken("");
                            SettingPreference.saveUserInfo(null);
                            mLoading.setResult(false, str, 1000);
                            mLoading.dismiss();
//                            mCallback.onWxFail(errorMsg);
                        }
                        mCallback.onWxFail(errorMsg);
                    }
                });
    }

    @Override
    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
        Log.i(TAG, "onError: ");
        EventUtils.INSTANCE.onEvent("login_fail", "onError:" + "没有安装微信:" + i);
        mLoading.setResult(false, "没有安装微信", 1000);
        mCallback.onWxFail("没有安装微信");
    }

    @Override
    public void onCancel(SHARE_MEDIA share_media, int i) {
        Log.i(TAG, "onCancel: ");
        EventUtils.INSTANCE.onEvent("login_fail", "onCancel:" + "授权取消:" + i);
        mLoading.setResult(false, "授权取消", 1000);
        mCallback.onWxFail("授权取消");
    }

    public void dismissDialog() {
        if (mLoading != null && activity != null && !activity.isFinishing()) {
            mLoading.dismiss();
        }
    }

//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        try {
//            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
//        } catch (Exception ex) {
//
//        }
//    }

    public interface IWxLoginCallback {
        void onWxSuccess(String token, String openid);

        void onWxFail(String mes);
    }

}
