package com.fq.channel.sdk.core;

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

import com.fq.channel.sdk.base.config.FqConfig;
import com.fq.channel.sdk.base.config.ResourceCfg;
import com.fq.channel.sdk.base.exception.BaseException;
import com.fq.channel.sdk.base.interfaces.PluginResult;
import com.fq.channel.sdk.base.interfaces.PluginResult.Status;
import com.fq.channel.sdk.base.interfaces.PluginResultHandler;
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;

import static com.fq.channel.sdk.base.constants.ConstSet.*;

/**
 * @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) {
                FqLog.e(TAG, "createOrder onFailure：" + "i=" + msg.getMessage());
                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();
                    String token = data.getToken();
                    //缓存Uid token
                    FqConfig.get().put(FqConfig.KEY_UID, uid);
                    FqConfig.get().put(FqConfig.KEY_TOKEN, token);

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

                    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) {
        String cpOrderId = getMapValus(map, PAY_ORDER_CP);
        String price = getMapValus(map, PAY_PRICE);
        String productName = getMapValus(map, PAY_PRODUCT_NAME);
        String serverId = getMapValus(map, PAY_SERVER_ID);
        String extraInfo = getMapValus(map, PAY_EXTRAL_INFO);
        String remark = getMapValus(map, PAY_REMARK);

        RepOrderBody repOrderBody = new RepOrderBody();
        repOrderBody.setCpBillNo(cpOrderId);
        repOrderBody.setChannelType(FqConfig.get().getString(FqConfig.KEY_CHANNEL_TYPE));
        repOrderBody.setUid(FqConfig.get().getString(FqConfig.KEY_UID));
        repOrderBody.setExtraInfo(extraInfo);
        repOrderBody.setIsTest("0");
        repOrderBody.setOrderAmount(price);
        repOrderBody.setOrderPlatform(ApiPlugin.getInstace().getPayId());
        repOrderBody.setOrderType("6");
        repOrderBody.setRemark(remark);
        repOrderBody.setSubject(productName);
        repOrderBody.setServerId(serverId);

        if (data != null) {
            String roleName = (String) data.get("roleName");
            if (!TextUtils.isEmpty(roleName)) {
                repOrderBody.setRoleName(roleName);
            }
        }
        FqNetRequest.createOrder(repOrderBody, new BaseCallback<ResultPayBody>() {
            @Override
            public void onFailure(BaseException msg) {
                FqLog.e(TAG, "createOrder onFailure：" + "i=" + msg.getMessage());
                cb.onHandlePluginResult(new PluginResult(Status.ERROR, msg.getMessage()));
            }

            @Override
            public void onSuccess(int code, String msg, ResultPayBody data) {
                FqLog.i(TAG, "createOrder : " + data.getOrderId() + " /NotifyUrl : " + data.getNotifyUrl());
                map.put(PAY_ORDER_ID, data.getOrderId());
                map.put(PAY_NOTIFY_URl, FqConfig.BASE_URL + "/" + data.getNotifyUrl());
                ApiPlugin.getInstace().pay(context, map, new PluginResultHandler() {
                    @Override
                    public void onHandlePluginResult(PluginResult result) {
                        if (result.getStatus() == Status.OK) {
                            cb.onHandlePluginResult(new PluginResult(Status.OK, result.getMessage()));
                        } else if (result.getStatus() == Status.CANCEL) {
                            cb.onHandlePluginResult(new PluginResult(Status.CANCEL, result.getMessage()));
                        } else {
                            cb.onHandlePluginResult(new PluginResult(Status.ERROR, result.getMessage()));
                        }
                    }
                });
            }
        });
    }

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

    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");
    }
}
