package cn.yyxx.commsdk.core.common;

import static cn.yyxx.commsdk.base.constants.Constants.UPLOAD_TYPE_LEVEL_UPGRADE;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

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

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import cn.yyxx.commsdk.base.entity.ResultInfo;
import cn.yyxx.commsdk.base.entity.SdkChargeInfo;
import cn.yyxx.commsdk.base.entity.SdkRoleInfo;
import cn.yyxx.commsdk.base.internal.ICallback;
import cn.yyxx.commsdk.base.internal.IMsaDeviceCallback;
import cn.yyxx.commsdk.base.internal.IRequestCallback;
import cn.yyxx.commsdk.base.utils.Logger;
import cn.yyxx.commsdk.core.SdkDrive;

import cn.yyxx.commsdk.base.entity.bean.InitBean;
import cn.yyxx.commsdk.core.entity.SdkLoginInfo;
import cn.yyxx.commsdk.core.network.SdkRequest;
import cn.yyxx.commsdk.core.ui.dialog.LoadingDialogUtils;
import cn.yyxx.commsdk.core.ui.dialog.PrivacyPolicyDialog;
import cn.yyxx.commsdk.core.ui.dialog.SingleButtonDialog;
import cn.yyxx.commsdk.core.utils.MMKVUtils;
import cn.yyxx.commsdk.core.utils.ManifestUtils;
import cn.yyxx.commsdk.core.utils.ParamsUtils;
import cn.yyxx.commsdk.core.utils.ResourceUtil;
import cn.yyxx.support.JsonUtils;

import cn.yyxx.support.hawkeye.ToastUtils;
import cn.yyxx.support.permission.IPermissionCallback;
import cn.yyxx.support.permission.Permission;
import cn.yyxx.support.permission.PermissionKit;

public class CommonOperationManager {
    public static CommonOperationManager commonOperationManager = null;

    private boolean hasIdsRead = false;
    private String oaid = "";


    public static InitBean initBean = null;

    private CommonOperationManager(){}
    public static CommonOperationManager getInstance(){
        if (commonOperationManager == null){
            commonOperationManager = new CommonOperationManager();
        }
        return commonOperationManager;
    }
    public void initAgreement(Activity activity, ICallback callback){

        if (TextUtils.isEmpty(ParamsUtils.getGameCode(activity))){
            new SingleButtonDialog.Builder(activity)
                    .setPositiveButton(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            System.exit(0);
                        }
                    })
                    .Create(activity.getString(ResourceUtil.getStringId(activity,"yyxx_comm_params_error_tip")))
                    .show();
            return;
        }



        String isShowPolicy = MMKVUtils.getInstance().commonKV.decodeString("isShowPolicy","");
        if (isShowPolicy.isEmpty()){

            LoadingDialogUtils.getInstance().show(activity);
            SdkRequest.getInstance().initAgreement(activity, new IRequestCallback() {
                @Override
                public void onResponse(ResultInfo resultInfo) {

                    LoadingDialogUtils.getInstance().hide();

                    if (resultInfo.code == 400){
                        showExitDialog(activity);
                    }
                    String policy_url = "";

                    try {
                        if (JsonUtils.hasJsonKey(new JSONObject(resultInfo.data),"agreement_url")){

                            JSONObject jsonObject = new JSONObject(resultInfo.data);
                            policy_url = jsonObject.getString("agreement_url");

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (policy_url.isEmpty()){
                        requestPermission(activity,callback);
                        return;
                    }

                    new PrivacyPolicyDialog(activity, policy_url, new PrivacyPolicyDialog.OnClosePageListener() {
                        @Override
                        public void onUserAgreePolicy() {

                            MMKVUtils.getInstance().commonKV.encode("isShowPolicy","1");
                            requestPermission(activity,callback);
                        }

                        @Override
                        public void onUserDisagreePolicy() {
                            callback.onResult(ResultInfo.CODE_FAIL,"User disagree policy");
                        }
                    }).show();
                }
            });

        }else{
            requestPermission(activity,callback);
        }

    }

    public void initialize(Activity activity, ICallback callback){


        if (!hasIdsRead) {
            Logger.e("还未读取到ids，将延迟初始化");
            AtomicInteger timeCount = new AtomicInteger(0);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!hasIdsRead) {
                        try {
                            Logger.d("还未读取到ids，延迟1s初始化");
                            Thread.sleep(1000);
                            timeCount.getAndIncrement();
                            if (timeCount.get() >= 5) {
                                hasIdsRead = true;
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (TextUtils.isEmpty(oaid)) {
                                Logger.e("读取到ids失败，共延迟" + timeCount + "s初始化接口，将进行初始化...");
                            } else {
                                Logger.e("读取到ids，共延迟" + timeCount + "s初始化接口，将进行初始化...");
                            }

                            startInitSdk(activity, callback);
                        }
                    });
                }
            }).start();
        } else {
            Logger.i("读取到ids，开始初始化");
            startInitSdk(activity, callback);
        }





    }

    private void startInitSdk(Activity activity, ICallback callback) {

        LoadingDialogUtils.getInstance().show(activity,activity.getString(ResourceUtil.getStringId(activity,"yyxx_comm_initing")));

        SdkRequest.getInstance().initSdk(activity, new IRequestCallback() {
            @Override
            public void onResponse(ResultInfo resultInfo) {
                LoadingDialogUtils.getInstance().hide();
                if (resultInfo.code ==ResultInfo.CODE_SUCCESS){
                    initBean = InitBean.toBean(resultInfo.data,activity);
                    SdkDrive.setClientSignature(initBean.access_token);
                    Logger.i(initBean.toString());
                    callback.onResult(resultInfo.CODE_SUCCESS,activity.getString(ResourceUtil.getStringId(activity,"yyxx_comm_init_success")));
                }else if (resultInfo.code ==ResultInfo.CODE_FAIL){
                    callback.onResult(resultInfo.CODE_FAIL,activity.getString(ResourceUtil.getStringId(activity,"yyxx_comm_init_fail")));
                } else if (resultInfo.code ==ResultInfo.CODE_ERROR){
                    showExitDialog(activity);
                }

            }
        });

    }

    void showExitDialog(Activity activity){
        new SingleButtonDialog.Builder(activity)
                .setPositiveButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        System.exit(0);
                    }
                })
                .Create(activity.getString(ResourceUtil.getStringId(activity,"yyxx_comm_network_error_tip")))
                .show();
        return;
    }

    public void initMsaDeviceIds(Application application){


        try {
            Class<?> billingImpl = Class.forName("cn.yyxx.commsdk.impl.channel.msa.MsaDeviceHandler");
            Constructor<?> constructor = billingImpl.getDeclaredConstructor();
            Object impl = constructor.newInstance();
            Method method = billingImpl.getDeclaredMethod("initMsaDeviceIds", Context.class,IMsaDeviceCallback.class);
            method.setAccessible(true);
            method.invoke(impl, application, new IMsaDeviceCallback() {
                @Override
                public void onIdsRead(int code, String msg, Map<String, String> ids) {
                    if (code == 0){
                        Logger.i(ids.toString());
                        oaid = ids.get("oaid");
                    }
                    hasIdsRead = true;

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @SuppressLint("MissingPermission")
    public JSONObject getIfa(Context context){
        String ifa = "";
        String ifa_type= "";

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P){


                ifa = oaid;

                ifa_type =  "2";
        }else{
            if (PermissionKit.isGranted(context,Permission.READ_PHONE_STATE)){
                @SuppressLint("ServiceCast") TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELECOM_SERVICE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    ifa = telephonyManager.getImei();
                }else{
                    ifa = telephonyManager.getDeviceId();
                }
            }
            ifa_type = "1";
        }

        if (ifa.isEmpty()){
            ifa = Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
            ifa_type = "3";
            if (ifa.isEmpty()){
                ifa = userSimulateImei(context);
                ifa_type = "0";
            }
        }

        JSONObject json = new JSONObject();
        try {
            json.put("ifa",ifa);
            json.put("ifa_type",ifa_type);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return json;
    }


    static String userSimulateImei(Context context){


        String simulateImei = MMKVUtils.getInstance().commonKV.decodeString("simulateImei","");
        if (!simulateImei.isEmpty()){
            return simulateImei;
        }else {

            // 用putString的方法保存数据
            String encryptMD5to16 ="YYR" + simulateUniqueId().substring(8, 24);

            MMKVUtils.getInstance().commonKV.encode("simulateImei",encryptMD5to16);

            return encryptMD5to16;
        }
    }



    //获得独一无二的Psuedo ID
    public static String simulateUniqueId() {
        String serial = null;

        String m_szDevIDShort = "" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        String  time = m_szDevIDShort + (System.currentTimeMillis());
        return  getMD5(time);

    }

    public static String getMD5(String content) {
        String s = null;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            md.update(content.getBytes());
            byte tmp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            s = new String(str);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }


    void requestPermission(Activity activity,ICallback callback){

        // 直接跳过，不申请权限
        if (!ManifestUtils.getMetaDataValue(activity,"yyxx.SkipPermission").isEmpty()){
            callback.onResult(ResultInfo.CODE_SUCCESS,"User skip permission required");
        }
        //第二次打开，不再申请权限
        else if (!MMKVUtils.getInstance().commonKV.decodeString("yyxx.StopRequestPermission","").isEmpty()){
            callback.onResult(ResultInfo.CODE_SUCCESS,"No more permissions required");
        }
        //申请权限
        else{
            goRequestPermission(activity, new PermissonCallBack() {
                @Override
                public void onResult(Result code) {
                    if (code == Result.FINISH){
                        SdkDrive.getInstance().initDrive(activity);
                        if(!ManifestUtils.getMetaDataValue(activity,"yyxx.StopRequestPermission").isEmpty()){
                            MMKVUtils.getInstance().commonKV.encode("yyxx.StopRequestPermission","1");
                        }
                        callback.onResult(ResultInfo.CODE_SUCCESS,"The permission application is complete");
                    }
                }
            });
        }

    }


    void goRequestPermission(Activity activity,PermissonCallBack permissonCallBack) {

        PermissionKit.enablePermissionDialog = false;
        PermissionKit.with()
                .permission(Permission.READ_PHONE_STATE)
                .permission(Permission.Group.STORAGE)
                .request(activity, new IPermissionCallback() {
                    @Override
                    public void onGranted(List<String> list, boolean all) {
                        permissonCallBack.onResult(Result.GRANT);
                    }

                    @Override
                    public void onDenied(List<String> list, boolean never) {
                        permissonCallBack.onResult(Result.DENIED);
                    }

                    @Override
                    public void onProxyFinish() {

                        permissonCallBack.onResult(Result.FINISH);


                    }
                });
    }



    public interface PermissonCallBack{
        void onResult(Result code);
    }



    public enum Result{
        /**
         * 授权
         */
        GRANT,
        /**
         * 拒绝
         */
        DENIED,
        /**
         * 跳过
         */
        SKIP,
        /**
         * 首次拒绝，第二次不再申请
         */
        STOP,
        FINISH
    }


    public void uploadRoleInfo(Activity activity, String type, SdkRoleInfo roleInfo) {

        if (TextUtils.isEmpty(SdkLoginInfo.getInstance().uname)) {

            ToastUtils.toastInfo(activity,"请先登录");

            return;
        }

        
        if (TextUtils.isEmpty(roleInfo.getCharge())){
            roleInfo.setCharge("0");
        }

        if (TextUtils.isEmpty(roleInfo.getRoleId()) || TextUtils.isEmpty(roleInfo.getRoleName())
                || TextUtils.isEmpty(roleInfo.getRoleLevel())
                || TextUtils.isEmpty(roleInfo.getGender())
                || TextUtils.isEmpty(roleInfo.getServerId())
                || TextUtils.isEmpty(roleInfo.getServerName())
                || TextUtils.isEmpty(roleInfo.getHasGold())
                || TextUtils.isEmpty(roleInfo.getVipLevel())
                || TextUtils.isEmpty(roleInfo.getRoleCreateTime())
                || TextUtils.isEmpty(roleInfo.getRolePower())
                || TextUtils.isEmpty(roleInfo.getReincarnationCount())) {

            Logger.i("上报参数有空值，请检查: "+ roleInfo.toString());

        }
        
        
        

        if (roleInfo.getRoleCreateTime().length() != 10) {

            ToastUtils.toastInfo(activity,activity.getString(ResourceUtil.getStringId(activity,"yyxx_comm_ctime_format_error")));

            return;
        }




        if (type.equals(UPLOAD_TYPE_LEVEL_UPGRADE)) {
            Logger.i("上报角色成功");
             return;
        }else{
            SdkRequest.getInstance().uploadRoleInfo(activity, type, roleInfo, new IRequestCallback() {
                @Override
                public void onResponse(ResultInfo resultInfo) {
                    if (resultInfo.code == ResultInfo.CODE_SUCCESS){
                        Logger.i("上报角色成功");
                    }else{
                        Logger.i("上报角色失败");
                    }
                }
            });
        }

    }


    public void getOrderInfo(Activity activity, SdkChargeInfo chargeInfo, ICallback callback) {


        if (TextUtils.isEmpty(SdkLoginInfo.getInstance().uname)){

            ToastUtils.toastInfo(activity,"请先登录");

            return;
        }
        if (TextUtils.isEmpty(chargeInfo.getGame_no()) || TextUtils.isEmpty(chargeInfo.getPay_money())
                || TextUtils.isEmpty(chargeInfo.getServer_id())
                || TextUtils.isEmpty(chargeInfo.getServer_name())
                || TextUtils.isEmpty(chargeInfo.getRole_id())
                || TextUtils.isEmpty(chargeInfo.getRole_level())
                || TextUtils.isEmpty(chargeInfo.getRole_name())
                || TextUtils.isEmpty(chargeInfo.getExt())
                || TextUtils.isEmpty(chargeInfo.getOrder_desc())
                || TextUtils.isEmpty(chargeInfo.getProduct_id())) {

            Logger.i("下单参数有空值，请检查: "+ chargeInfo);
        }

        SdkRequest.getInstance().charge(activity, chargeInfo, new IRequestCallback() {
            @Override
            public void onResponse(ResultInfo resultInfo) {

                    callback.onResult(resultInfo.code,resultInfo.data);


            }
        });

    }


}
