package com.aries.qsllx.wxapi;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;



//import org.cocos2dx.javascript.thridSdk.ThirdSdkMgr;

import com.aries.qsllx.BuildConfig;
import com.aries.qsllx.R;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.cocos2dx.javascript.thirdSdk.ThirdSdkMgr;

import java.io.ByteArrayOutputStream;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    //单例模式
    public static WXEntryActivity mInstance = null;

    public static WXEntryActivity getInstance() {
        if (null == mInstance) {
            mInstance = new WXEntryActivity();
        }
        return mInstance;
    }

    //AppId(这边统一调用 BuildConfig)
    private String AppId_WX = "wx28356dc7c541ea76";

    //日志Tag
    private  String _tag = "[WXEntryActivity] :";

    private IWXAPI iwxapi;
    private String unionid;
    private String openid;
    private WXEntryActivity mContext;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d(this._tag, "onCreate");
        //可以注释，因为不会自动进入这边的 onCreate() 方法 只不过需要打开该Activty才会进入
        String APP_ID = BuildConfig.WX_APP_ID;
        iwxapi = WXAPIFactory.createWXAPI(this, APP_ID, true);
        handleIntent(getIntent());
    }

    /** 注册微信
     *  @param context 调用注册的Activity 一般是AppActivity
     */
    public void regToWx(Context context)
    {
        String APP_ID = BuildConfig.WX_APP_ID;
        Log.d(this._tag, "regToWx APP_ID: " + APP_ID);
        iwxapi = WXAPIFactory.createWXAPI(context, APP_ID, true);
        iwxapi.registerApp(APP_ID);
    }

    /** 开始微信授权
     *  @param context 一般是主Activity 比如 AppActivity
     */
    public void startWxAuth(Context context) {
        Log.d(this._tag, "startWxAuth ");
        if (!iwxapi.isWXAppInstalled()) {
            //Toast 是一个 View 视图，快速的为用户显示少量的信息。Toast 在应用程序上浮动显示信息给用户，它永远不会获得焦点，不影响用户的输入等操作，主要用于 一些帮助 / 提示。
            Toast.makeText(context, "您的设备未安装微信客户端", Toast.LENGTH_SHORT).show();
        } else {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            //req.state = "wechat_sdk_demo_test";
            req.state = String.valueOf(System.currentTimeMillis());
            iwxapi.sendReq(req);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(this._tag, "onNewIntent");
        this.handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        setIntent(intent);
        iwxapi.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

        Log.d(this._tag, "onReq");
    }

    //请求回调结果处理
    @Override
    public void onResp(BaseResp baseResp) {
        //登录微信返回回调
        Log.d(this._tag, "onResp baseResp.errCode: "+baseResp.errCode + "");
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (baseResp instanceof SendAuth.Resp) {
                    String code = ((SendAuth.Resp) baseResp).code;
                    ThirdSdkMgr.wxAccessToken(code);
                    finish();
                } else {
                    finish();
                }
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
                finish();
                break;
            default:
                finish();
                break;
        }
    }


//    //新写法 分返回code 可以后续借鉴
//    public void onResp(BaseResp resp) {
//        if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
//            if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
//                //授权登录成功
//                String code = ((SendAuth.Resp) resp).code;
//                String state = ((SendAuth.Resp) resp).state;
//                Log.d(TAG, "code:===" + code + "state:===" + state);
//                EventBus.getDefault().post(new ThirdLoginModel(code, state));
//            } else if (resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
//                //分享微信回调
//                Log.d(TAG, "====返回了====");
//                String _type = MyWxManager.getInstance().getShareOrigin();
//                String _target = MyWxManager.getInstance().getShareType();
//                String _page = MyWxManager.getInstance().getSharePage();
//                if (!TextUtils.isEmpty(_type) && !TextUtils.isEmpty(_target) && !TextUtils.isEmpty(_page)) {
//                    MobclickUtil.Share(FrameApplication.getContext(), _type, _target, _page);
//                }
//            }
//            finish();
//        } else {
//            finish();
//        }
//    }

    //分享相关---------------------------------------------------------------------------------------
    /** 分享图 */
    public void sharePic(Context context){
        //如果这段代码放置在AppActivity中则不需要context 直接getResources()
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.send_img);
        WXImageObject imgObj = new WXImageObject(bmp);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 90, 200, true);
        bmp.recycle();
        msg.thumbData = bmpToByteArray(thumbBmp, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        iwxapi.sendReq(req);

        Log.d("PPPPP", "sharePic  end  ");
    }

    //该方法不局限于微信，可视为工具类的通用方法。目前暂时放在这，有必要可以新建一个Utils类，参考炮火
    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
}
