package com.fq.channel.sdk.core;

import android.content.Context;
import android.os.Bundle;

import com.fq.channel.sdk.base.constants.FqConfig;
import com.fq.channel.sdk.base.exception.BaseException;
import com.fq.channel.sdk.base.interfaces.PluginResult;
import com.fq.channel.sdk.base.interfaces.PluginResultHandler;
import com.fq.channel.sdk.base.constants.ResourceCfg;
import com.fq.channel.sdk.base.interfaces.PluginResult.*;
import com.fq.channel.sdk.base.net.FqNetRequest;
import com.fq.channel.sdk.base.net.callback.BaseCallback;
import com.fq.channel.sdk.base.net.req.RepOrderBody;
import com.fq.channel.sdk.base.net.result.ResultLoginBody;
import com.fq.channel.sdk.base.net.result.ResultPayBody;
import com.fq.channel.sdk.base.utils.FqLog;
import com.fq.channel.sdk.core.invoke.ApiPlugin;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 核心层对外API
 * @Author: FLuty
 * @CreateDate: 2020/3/24 17:59
 */
public class JointManager {
    private static final String TAG = "JointManager";

    private volatile static JointManager uniqueInstance;

    private PluginResultHandler cb;

    private ResourceCfg mCfg;

    Bundle data;

    private JointManager() {
    }

    public static JointManager getInstance() {
        if (uniqueInstance == null) {
            synchronized (JointManager.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new JointManager();
                }
            }
        }
        return uniqueInstance;
    }

    public void initCfgConfigFile(Context mContext) {
        if (null == mCfg) {
            mCfg = new ResourceCfg(mContext);
        }
    }

    public void init(Context context, PluginResultHandler cb) {
        initCfgConfigFile(context);//加载assets/cfg文件
        // 获取对应的ApiPlugin子类实例，并反射初始化SDK操作
        ApiPlugin.getInstace().init(context, cb);
    }

    public void login(Context context, PluginResultHandler cb) {
        this.cb = cb;
        ApiPlugin.getInstace().login(context, onLoginCallBack);
    }

    /**
     * 登录回调处理
     */
    private PluginResultHandler onLoginCallBack = new PluginResultHandler() {
        @Override
        public void onHandlePluginResult(PluginResult result) {
            if (result.getStatus() == Status.OK) {
                final String msg = result.getMessage();
                HashMap<String, String> loginOauthInfo = (HashMap<String, String>) result.getRawMessage();
                FqLog.d(TAG, "msg:" + msg);
                if (null != loginOauthInfo || 0 != loginOauthInfo.size()) {
                    channelLogin(loginOauthInfo);
                } else {
                    cb.onHandlePluginResult(new PluginResult(Status.ERROR, "channel login failss"));
                }
            } else if (result.getStatus() == Status.CANCEL) {
                cb.onHandlePluginResult(new PluginResult(Status.CANCEL));

            } else if (result.getStatus() == Status.ERROR) {
                cb.onHandlePluginResult(new PluginResult(Status.ERROR, "channel login failss"));
            }
        }
    };

    private void channelLogin(HashMap<String, String> channelInfo) {
        FqNetRequest.login(channelInfo, new BaseCallback<ResultLoginBody>() {
            @Override
            public void onFailure(BaseException msg) {
                cb.onHandlePluginResult(new PluginResult(Status.ERROR, msg.getMsg()));
            }

            @Override
            public void onSuccess(int code, String msg, ResultLoginBody data) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    String uid = data.getUid();
                    //缓存Uid
                    FqConfig.get().put(FqConfig.KEY_UID,uid);

                    jsonObject.put("uid", uid);
                    jsonObject.put("token", data.getToken());

                    cb.onHandlePluginResult(new PluginResult(Status.OK, jsonObject));
                } catch (JSONException e) {
                    cb.onHandlePluginResult(new PluginResult(Status.ERROR, "JSONException"));
                }
            }
        });
    }

    public void pay(Context context, Map paymentInfo, PluginResultHandler cb) {
        createOrder(context, paymentInfo, cb);
    }

    private void createOrder(final Context context, final Map map, final PluginResultHandler cb) {
        RepOrderBody repOrderBody = new RepOrderBody();
        repOrderBody.setChannelType( FqConfig.get().getString(FqConfig.KEY_CHANNEL_TYPE));
        repOrderBody.setUid( FqConfig.get().getString(FqConfig.KEY_UID));
        repOrderBody.setExtraInfo(getMapValus(map,"extraInfo"));
        repOrderBody.setIsTest(FqConfig.DEBUG_VERSION?"1":"0");
        repOrderBody.setOrderAmount(getMapValus(map,"orderAmount"));
        repOrderBody.setOrderPlatform(getMapValus(map,"orderPlatform"));
        repOrderBody.setOrderType(getMapValus(map,"orderType"));
        repOrderBody.setRemark(getMapValus(map,"remark"));
        repOrderBody.setSubject(getMapValus(map,"subject"));
        data.getBundle("roleName");
        data.getBundle("serverId");
        repOrderBody.setRoleName(getMapValus(map,"roleName"));
        repOrderBody.setServerId(getMapValus(map,"serverId"));

        FqNetRequest.createOrder(repOrderBody, new BaseCallback<ResultPayBody>() {
            @Override
            public void onFailure(BaseException msg) {
                cb.onHandlePluginResult(new PluginResult(Status.ERROR, msg.getMessage()));
            }

            @Override
            public void onSuccess(int code, String msg, ResultPayBody data) {

//               startPay(context,data,cb);
            }
        });
    }

    private String getMapValus(Map map,String key){
        return String.valueOf(map.get(key));
    }

//    private void startPay(Context context,ResultPayBody data, PluginResultHandler cb) {
//        HashMap<Object, Object> payParams = new HashMap<Object, Object>();
//        payParams.put(ConstSet.PAY_ORDER_ID, unolPay.getOrder_id());
//        payParams.put(ConstSet.PAY_PAYMENT_STATE, 8);
//        payParams.put(ConstSet.PAY_PAYMETHOD, paymethod);
//        payParams.put(ConstSet.PAY_PRODUCT_DES, productDescription);
//        payParams.put(ConstSet.PAY_PRICE, price);
//        payParams.put(ConstSet.PAY_PRODUCT_NAME, productName);
//        payParams.put(ConstSet.PAY_SERVER_ID, serverId);
//        payParams.put(ConstSet.PAY_EXTRAL_INFO, extraInfo);
//        payParams.put(ConstSet.PAY_PRODUCT_ID, id);
//        payParams.put(ConstSet.PAY_AMOUNT, amount);
//        payParams.put(ConstSet.PAY_RATE, rate);
//        payParams.put(ConstSet.PAY_MONETARYUNIT, monetaryunit);
//        payParams.put(ConstSet.PAY_CHARGE_ID, chargeId);
//        payParams.put(ConstSet.PAY_GOODS_ID, goodsId);
//        ApiPlugin.getInstace().pay(context, paymentInfo, cb);
//    }

    public void exit(Context context, PluginResultHandler cb) {
        ApiPlugin.getInstace().exit(context, cb);
    }

    public void setRoleInfo(Bundle data) {
        this.data = data;
        ApiPlugin.getInstace().setRoleInfo(data);
    }

    public String getPluginSdkClassName() {
        return mCfg.getString("plugin_sdk_class_name");
    }

    public String getPluginName() {
        return mCfg.getString("plugin_name");
    }
}
