package com.idrv.coach.wxapi;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.idrv.coach.R;
import com.idrv.coach.bean.event.EventConstant;
import com.idrv.coach.bean.event.WeiXinEvent;
import com.idrv.coach.bean.share.IShareProvider;
import com.idrv.coach.data.manager.RxBusManager;
import com.idrv.coach.data.manager.WChatManager;
import com.idrv.coach.data.model.ShareModel;
import com.idrv.coach.ui.BaseActivity;
import com.idrv.coach.ui.adapter.AnimationAdapter;
import com.idrv.coach.utils.Logger;
import com.idrv.coach.utils.StatisticsUtil;
import com.idrv.coach.utils.handler.WeakHandler;
import com.idrv.coach.utils.helper.ResHelper;
import com.idrv.coach.utils.helper.UIHelper;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 分享的界面
 */
public class WXEntryActivity extends BaseActivity<ShareModel> implements IWXAPIEventHandler,
        IWeiboHandler.Response,
        IUiListener {
    private static final String TAG = "share";
    private String channel = "wechat";

    @InjectView(R.id.share_layout)
    public LinearLayout mLayout;
    @InjectView(R.id.share_title)
    public TextView mShareTitle;
    @InjectView(R.id.share_subject)
    TextView mShareSubjectTv;

    private IShareProvider mShareProvider;
    private boolean mIsInitialize;
    private int mTitleRes;
    private int mSubjectRes;

    //----------------微信对应的回调---------------------
    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        //1.登陆成功
        String transaction = baseResp.transaction;
        if (!TextUtils.isEmpty(transaction) && transaction.equals(WChatManager.getInstance().getTransaction())) {
            WeiXinEvent.LoginEvent event = new WeiXinEvent.LoginEvent();
            event.setData((SendAuth.Resp) baseResp);
            event.setExtra(transaction);
            WChatManager.getInstance().setIsWxCallBack(true);
            RxBusManager.post(EventConstant.KEY_WX_OAUTH_CODE, event);
            finish();
            return;
        }
        //2.分享
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                Logger.e(TAG, ResHelper.getString(R.string.weixin_share_success));
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Logger.e(TAG, ResHelper.getString(R.string.weixin_share_cancel));
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Logger.e(TAG, ResHelper.getString(R.string.weixin_share_fail));
                break;
            default:
                break;
        }
        onShareFinish();
    }
    //----------------------微博对应的回调---------------------

    @Override
    public void onResponse(BaseResponse baseResponse) {
        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Logger.e(TAG, ResHelper.getString(R.string.weibo_share_success));
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Logger.e(TAG, ResHelper.getString(R.string.weibo_share_cancel));
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Logger.e(TAG, ResHelper.getString(R.string.weibo_share_fail));
                break;
        }
        onShareFinish();
    }

    //------------------QQ对应的回调----------------------
    @Override
    public void onComplete(Object o) {
        Logger.e(TAG, ResHelper.getString(R.string.qq_share_success));
        onShareFinish();
    }

    @Override
    public void onError(UiError uiError) {
        Logger.e(TAG, ResHelper.getString(R.string.qq_share_success));
        onShareFinish();
    }

    @Override
    public void onCancel() {
        Logger.e(TAG, ResHelper.getString(R.string.qq_share_success));
        onShareFinish();
    }

    public static void launch(Context context, IShareProvider provider, @StringRes int resId) {
        Intent intent = new Intent(context, WXEntryActivity.class);
        intent.putExtra("share", provider);
        intent.putExtra("title", resId);
        context.startActivity(intent);
    }

    public static void launch(Context context, IShareProvider provider, @StringRes int resId, @StringRes int subjectResId) {
        Intent intent = new Intent(context, WXEntryActivity.class);
        intent.putExtra("share", provider);
        intent.putExtra("title", resId);
        intent.putExtra("subject", subjectResId);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_share);
        //1.初始化界面
        ButterKnife.inject(this);
        Intent intent = getIntent();
        parseIntent(intent);
        //2.初始化微信的回调
        WChatManager.getInstance().handleIntent(intent, this);
        //3.初始化微博分享的内容、回调
        mViewModel = new ShareModel();
        mViewModel.initPlatforms(this, getIntent(), savedInstanceState != null);
        if (0 != mTitleRes) {
            mShareTitle.setText(mTitleRes);
        }
        if (0 != mSubjectRes) {
            mShareSubjectTv.setText(mSubjectRes);
        } else {
            mShareSubjectTv.setText("");
        }
        //3.执行动画
        mHandler = new WeakHandler();
        mHandler.postDelayed(() -> {
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.tranlate_y_100_0);
            animation.setAnimationListener(new AnimationAdapter() {
                @Override
                public void onAnimationStart(Animation animation) {
                    mLayout.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    mLayout.clearAnimation();
                }
            });
            animation.setFillAfter(true);
            mLayout.startAnimation(animation);
        }, 200);
    }

    /**
     * 得到分享的内容
     *
     * @param intent
     */
    private void parseIntent(Intent intent) {
        if (intent != null) {
            mShareProvider = intent.getParcelableExtra("share");
            mTitleRes = intent.getIntExtra("title", 0);
            mSubjectRes = intent.getIntExtra("subject", 0);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        //1.微信的回调
        WChatManager.getInstance().handleIntent(intent, this);
        //2.微博的回调
        mViewModel.handleWeiboResponse(intent, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHandler.postDelayed(() -> {
            UIHelper.hideSoftInput(mLayout);
            if (mIsInitialize) {
                onShareFinish();
            }
        }, 100);

    }

    @OnClick({R.id.share_weixin,
            R.id.share_timeline, R.id.share_qzone, R.id.cancel})
    public void onClick(View view) {
        mIsInitialize = true;
        switch (view.getId()) {
//            case R.id.share_sina:
//                mViewModel.share2Weibo(mShareProvider);
//                break;
            case R.id.share_weixin:
                mViewModel.share2Weixin(SendMessageToWX.Req.WXSceneSession, mShareProvider);
                channel = "wechat";
                break;
            case R.id.share_timeline:
                mViewModel.share2Weixin(SendMessageToWX.Req.WXSceneTimeline, mShareProvider);
                channel = "timeline";
                break;
            case R.id.share_qzone:
                //点击qq分享的统计
                StatisticsUtil.onEvent(R.string.click_qq);
                mViewModel.share2QQ(this, mShareProvider);
                channel = "qq";
                break;
            case R.id.cancel:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        // 微博分享界面返回的请求码
//        if (765 == requestCode) {
//            finish();
//        }
    }

    public void onShareFinish() {
        if (!isDestroyed()) {
            mLayout.setVisibility(View.INVISIBLE);
            mLayout.setEnabled(false);
            RxBusManager.post(EventConstant.KEY_SHARE_COMPLETE, channel);
            finish();
        }
    }

    @Override
    protected boolean isToolbarEnable() {
        return false;
    }

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