package com.efounder.chat.zxing.qrcode;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.efounder.chat.R;
import com.efounder.chat.activity.ChatWebViewActivity;
import com.efounder.chat.activity.NeiKongUploadImageActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.Group;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.Constants;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.JFStringUtil;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ReflectUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Tian Yu on 2016/9/7.
 */

public class QRManager {
    public static boolean closeActivity = false;

    //处理扫码结果
    public static void handleresult(Context context, String result) {
        handleresult(context, result, true);
    }

    /**
     * 管理不同的处理二维码内容类
     * 保存key和相应的处理类，key放在二维码的type字段
     * 如果二维码里包含这个key，就取出这个处理类对二维码处理
     */
    private static HashMap<String, String> qrHandleClassMap = new HashMap<>();

    /**
     * 向qrHandleClassMap中添加二维码处理类的类名
     *
     * @param key       key ，key表示二维码json 的type字段
     * @param className name 需要实现 IHandleQrContent
     */
    public static void addQrHandleClass(String key, String className) {
        qrHandleClassMap.put(key, className);
    }

    /**
     * 处理扫码结果
     *
     * @param context
     * @param result  扫码结果
     * @param close   扫码结束是否关闭当前activity
     */
    public static void handleresult(Context context, String result, boolean close) {
        closeActivity = close;
        try {
            //山大扫描的正则表达式
            String patterString = "^((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s].*data.*\\{.*type.*.*QRLogin.*\\}";

            if (result.matches(patterString)) {
                //https://mobile.solarsource.cn/ospstore/sduzx.html?data={"type":"QRLogin","url":"","authId":""}
                if (result.contains("{") && result.contains("}") && result.contains("QRLogin")) {
                    result = result.substring(result.indexOf("{"), result.indexOf("}") + 1);
                }
            }
            //第二种方式处理山大智信url
            try {
                String decodeResult = URLDecoder.decode(result, "utf-8");
                if (decodeResult.matches(patterString)) {
                    //https://mobile.solarsource.cn/ospstore/sduzx.html?data={"type":"QRLogin","url":"","authId":""}
                    if (decodeResult.contains("{") && decodeResult.contains("}") && decodeResult.contains("QRLogin")) {
                        result = decodeResult.substring(decodeResult.indexOf("{"), decodeResult.indexOf("}") + 1);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //1.判断如果是url 直接打开
            if (JFStringUtil.isHttpUrl(result)) {
                Intent intent = new Intent(context, ChatWebViewActivity.class);
                intent.putExtra("url", result);
                context.startActivity(intent);
                closeActivity(context);
                return;
            }

            //2.字符串转json
            JSONObject jsonObject = new JSONObject(result);
            String type = jsonObject.optString("type", "");
            //如果classMap中包含这个type，交给这个特别实现的二维码处理类处理
            if (qrHandleClassMap.containsKey(type)) {
                try {
                    IHandleQrContent iHandleQrContent = ReflectUtils.reflect(Class.forName(qrHandleClassMap.get(type))).newInstance().get();
                    iHandleQrContent.handleQrContent(context, result);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(), "IHandleQrContent出现异常！！！");
                }
                closeActivity(context);
            } else if (type.equals("weblogin")) {
                try {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    intent.setClass(context, Class.forName("com.efounder.chat.activity.LoginWebActivity"));
                    bundle.putString("result", result);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (type.equals("addFriend") || type.equals("addPublicNum")) {
                String userID = "";
                userID = jsonObject.getString("userID");
                startActivity(context, type, userID);
            } else if (type.equals("addGroup")) {
                String userID = "";
                userID = jsonObject.getString("userID");
                startActivity(context, type, userID);
            } else if (type.equals("cnpcBill") || type.equals("safp")) {//todo 共享用
                startActivity(context, type, result);
            } else if (type.equals("qrlogin")) {//中建扫码登陆
                try {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    intent.setClass(context, Class.forName("com.efounder.chat.activity.LoginThirdWebActivity"));
                    bundle.putString("result", result);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                    // ((Activity) context).finish();
                    closeActivity(context);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (type.equals("QRLogin")) {//山大cas用
                try {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    intent.setClass(context, Class.forName("com.efounder.chat.activity.LoginThirdWebActivity"));
                    bundle.putString("result", result);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
//                    ((Activity) context).finish();
                    closeActivity(context);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (type.equals("opLogin")) {//星际通讯用
                try {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    intent.setClass(context, Class.forName("com.efounder.chat.activity.LoginThirdWebActivity"));
                    bundle.putString("result", result);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                    // ((Activity) context).finish();
                    closeActivity(context);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (type.equals("gathering")) {//星际通讯收款用
                try {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    //TODO  添加跳转的类名
                    intent.setClass(context, Class.forName(context.getResources().getString(R.string.activity_energy_exchage_transfer)));

                    String ethAddress = jsonObject.optString("ethAddress", "");
                    if ("".equals(ethAddress)) {
                        ethAddress = jsonObject.optString("walletAddress", "");
                    }
                    bundle.putString("result", result);
                    bundle.putString("toAccount", jsonObject.optString("userId", ""));
                    bundle.putString("toAddress", ethAddress);
                    bundle.putString("count", jsonObject.optString("money", ""));
                    intent.putExtras(bundle);
                    context.startActivity(intent);
//                    ((Activity) context).finish();
                    closeActivity(context);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (type.equals("observeWallet")) {//星际资产观察钱包
                handlerObserveWallet(context, jsonObject);
            } else if (type.equals("tokenTrade")) {//星际资产代币交易
                handlerTokenTrade(context, jsonObject);
            } else if (type.equals("createEosAccount")) {//帮助创建eos账户
                try {
                    Bundle bundle = new Bundle();
                    bundle.putString("eosActivePublicKey", jsonObject.optString("eosActivePublicKey"));
                    bundle.putString("eosOwnerPublicKey", jsonObject.optString("eosOwnerPublicKey"));
                    bundle.putString("eosAccountName", jsonObject.optString("eosAccountName"));
                    bundle.putBoolean(EFTransformFragmentActivity.EXTRA_HIDE_TITLE_BAR, true);
                    EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class
                            .forName("com.pansoft.openplanet.activity.child.HelpCreateEosFragment"), bundle);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (type.equals("neikong") || jsonObject.optString("d", "").equals("neikong")) {//内控上传影像
                NeiKongUploadImageActivity.start(context, result);
                closeActivity(context);
                //网页
            } else if ("web".equals(type)) {
                String url = jsonObject.optString("url");
                String param = jsonObject.optString("param");
                String value = jsonObject.optString("value");
                Intent intent = new Intent(context, ChatWebViewActivity.class);
                intent.putExtra("url", url);
                intent.putExtra("param", param);
                intent.putExtra("value", value);
                context.startActivity(intent);
                closeActivity(context);
                //如果classMap中包含这个type，交给这个特别实现的二维码处理类处理
            } else if (qrHandleClassMap.containsKey(type)) {
                try {
                    IHandleQrContent iHandleQrContent = ReflectUtils.reflect(Class.forName(qrHandleClassMap.get(type))).newInstance().get();
                    iHandleQrContent.handleQrContent(context, result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                closeActivity(context);
            } else {
                dealOtherResult(context, result);

            }
        } catch (Exception e) {
            LogUtils.e("二维码识别 Exception：", e);
            dealOtherResult(context, result);
        }
    }

    /**
     * 处理没有type 的扫码结果
     *
     * @param context
     * @param result
     */
    private static void dealOtherResult(Context context, String result) {
        if (result.contains("ScanLogin")) {
            // TODO: 17-8-11  为了演示临时用扫描的url
            login(result, context);
        } else {
            //没有匹配的type  跳转展示字符串界面
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            intent.setClass(context, OtherResultActivity.class);
            bundle.putString("result", result);
            intent.putExtras(bundle);
            context.startActivity(intent);
        }
    }


    //todo 处理星际资产相关信息
    private static void handlerObserveWallet(Context context, JSONObject jsonObject) {
        try {
            Intent intent = new Intent();
            intent.setClass(context, Class.forName("com.pansoft.openplanet.activity.child.ChildAcceptSignDetailActivity"));
            intent.putExtra("scanResult", jsonObject.toString());
            context.startActivity(intent);
            //((Activity) context).finish();
            closeActivity(context);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            // ((Activity) context).finish();
            closeActivity(context);
        }
    }

    //todo 处理星际资产代币交易
    private static void handlerTokenTrade(Context context, JSONObject jsonObject) {
        try {
            Intent intent = new Intent();
            intent.setClass(context, Class.forName("com.pansoft.openplanet.activity.NewTransferActivity"));
            intent.putExtra("tokenTrade", jsonObject.toString());
            context.startActivity(intent);
//            ((Activity) context).finish();
            closeActivity(context);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
//            ((Activity) context).finish();
            closeActivity(context);
        }
    }

    private static void startActivity(final Context context, String type, final String userID) {
        if (!type.equals("") && !userID.equals("")) {
            final Intent intent = new Intent();
            Bundle bundle = new Bundle();
            if (type.equals("addFriend")) {
                try {
                    List<User> friends = WeChatDBManager.getInstance().getallFriends();
                    List<Integer> ids = new ArrayList<Integer>();// 数据库中存在的用户id
                    if (friends != null) {
                        for (User user : friends) {
                            ids.add(user.getId());
                        }
                    }
                    if (ids.contains(Integer.valueOf(userID))) {
                        intent.setClass(context, Class.forName(context.getResources().getString(R.string.userinfo_actiivity_class)));
                        bundle.putInt("id", Integer.valueOf(userID));
                        intent.putExtras(bundle);
                    } else {
//                        intent.setClass(context, Class.forName("com.efounder.chat.activity.AddFriendUserDetailActivity"));
//                        bundle.putString("userID", userID);
//                        intent.putExtras(bundle);
                        //fixme yqs 20180521 修改 都跳转userinfoactivity类
                        intent.setClass(context, Class.forName(context.getResources().getString(R.string.userinfo_actiivity_class)));
                        bundle.putInt("id", Integer.valueOf(userID));
                        intent.putExtras(bundle);
                    }

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                context.startActivity(intent);
//                ((MipcaActivityCapture) context).finish();
                closeActivity(context);
            } else if (type.equals("addPublicNum")) {
                try {
                    intent.setClass(context, Class.forName("com.efounder.chat.activity.AddPublicFriendInfoActivity"));
                    bundle.putString("userID", userID);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
//                    ((MipcaActivityCapture) context).finish();
                    closeActivity(context);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            } else if (type.equals("addGroup")) {
                Group tempGroup = WeChatDBManager.getInstance().getGroup(Integer.valueOf(userID), false);
                bundle.putInt("id", Integer.valueOf(userID));
                //进入群信息页，处理加群操作
                //如果数据库没有，则没有加入群，在新界面中处理
                if (String.valueOf(tempGroup.getGroupId()).equals(tempGroup.getGroupName())) {
                    bundle.putBoolean("added", false);//是否加群
                } else {
                    bundle.putBoolean("added", true);//是否加群
                }
                intent.putExtras(bundle);
                try {
                    intent.setClass(context, Class.forName("com.efounder.chat.activity.AddGroupUserInfoActivity"));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                context.startActivity(intent);
//                ((MipcaActivityCapture) context).finish();
                closeActivity(context);
            } else if (type.equals("cnpcBill")) {//进入RN票据扫描，传递整个json//// TODO: 17-8-3 共享用
                //中建进入内控上传页面
                if (EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("OSPMobileCSCES")) {
                    try {
                        intent.setClass(context, Class.forName("com.pansoft.invoiceocrlib.activity.InvoiceListScanActivity"));
                        //userID={"type":"cnpcBill","GUID":"GAD47173C0FF410A8F8D4025BBCDBB5E","BM":""}
                        intent.putExtra("qrResult", userID);
                        context.startActivity(intent);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    closeActivity(context);
                    return;
                }

                DisplayMetrics metric = new DisplayMetrics();
                ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metric);
                int width = metric.widthPixels;     // 屏幕宽度（像素）
                int height = metric.heightPixels;

//                int  invoiceWidth= 675;
//                int invoiceHeight =  1181;
                int invoiceWidth = 210;
                int invoiceHeight = 297;
                try {
                    intent.putExtra("result", userID);
                    intent.putExtra("invoiceWidth", invoiceWidth);
                    intent.putExtra("invoiceHeight", invoiceHeight);
                    intent.setClass(context, Class.forName("io.card.payment.CardIOActivity"));
                    intent.putExtra("io.card.payment.suppressManual", true)//// TODO: 17-8-1
                            .putExtra("io.card.payment.hideLogo", true)//// TODO: 17-8-1
                            .putExtra("io.card.payment.languageOrLocale", "zh-Hans")
                            .putExtra("io.card.payment.keepApplicationTheme", true)
                            .putExtra("io.card.payment.guideColor", Color.GREEN)
                            .putExtra("io.card.payment.suppressScan", true)
                            .putExtra("io.card.payment.returnCardImage", true);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    context.startActivity(intent);
//                    ((MipcaActivityCapture) context).finish();
                    closeActivity(context);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (type.equals("safp")) {//进入RN票据扫描，传递整个json//// TODO: 17-8-3 共享用

                DisplayMetrics metric = new DisplayMetrics();
                ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metric);
                int width = metric.widthPixels;     // 屏幕宽度（像素）
                int height = metric.heightPixels;

                int invoiceWidth = 675;
                int invoiceHeight = 1181;

                try {
                    intent.putExtra("result", userID);
                    intent.putExtra("invoiceWidth", invoiceWidth);
                    intent.putExtra("invoiceHeight", invoiceHeight);
                    intent.setClass(context, Class.forName("io.card.payment.CardIOActivity"));
                    intent.putExtra("io.card.payment.suppressManual", true)//// TODO: 17-8-1
                            .putExtra("io.card.payment.hideLogo", true)//// TODO: 17-8-1
                            .putExtra("io.card.payment.languageOrLocale", "zh-Hans")
                            .putExtra("io.card.payment.keepApplicationTheme", true)
                            .putExtra("io.card.payment.guideColor", Color.GREEN)
                            .putExtra("io.card.payment.suppressScan", true)
                            .putExtra("io.card.payment.returnCardImage", true)
                            .putExtra("intentType", "OCR");

                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                context.startActivity(intent);
//                ((MipcaActivityCapture) context).finish();
                closeActivity(context);
            }
        }
    }

//    private static void solveAddGroupOpertaion(final Context context, String type, final String userID) {
//        final Intent intent = new Intent();
//        WeChatDBManager weChatDBManager = WeChatDBManager.getInstance();
//        Group tempGroup = weChatDBManager.getGroupWithUsers(Integer.valueOf(userID));
//        //如果本地数据库不存在该群组，也就是没有加入该群组，进入群信息页，处理加群操作
//        if (String.valueOf(tempGroup.getGroupId()).equals(tempGroup.getGroupName())) {
//            AlertDialog dialog = new AlertDialog.Builder(context).setTitle("提示").setMessage("您确定要申请加入该群组吗？")
//                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            try {
//                                GetHttpUtil.applyToGroup(context, Integer.valueOf(userID), new GetHttpUtil.ApplyToGroupCallBack() {
//                                    @Override
//                                    public void applyToGroupResult(boolean isSuccess) {
//                                        if (!isSuccess) {
//                                            ToastUtil.showToast(context, "申请加入群组失败");
//                                            return;
//                                        } else {
//                                            ToastUtil.showToast(context, "发送申请成功，请等待群主或者管理员审核");
//                                        }
//
//
//                                    }
//                                });
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//
//                    }).setNegativeButton("取消", null).show();
//
//        } else {//直接进入群聊
//            try {
//
//                intent.setClass(context, Class.forName(context.getResources().getString(R.string.chat_actiivity_class)));
//            } catch (ClassNotFoundException e) {
//                e.printStackTrace();
//            }
//            intent.putExtra("id", Integer.valueOf(userID));
//            intent.putExtra("chattype", StructFactory.TO_USER_TYPE_GROUP);
//            context.startActivity(intent);
//        }
//    }

    private static void login(final String url, final Context context) {
        new AsyncTask<String, Integer, String>() {
            private ProgressDialog dialog;

            @Override
            protected void onPreExecute() {
                dialog = new ProgressDialog(context);
                dialog.setMessage("正在解析请求...");
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.show();
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(String... params) {
                int code = 0;
                String urlString = params[0];
                try {
                    URL url = new URL(urlString + "&type=1&UserName=" + EnvironmentVariable.getUserName());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(3 * 1000);
                    conn.setRequestMethod("GET");
                    code = conn.getResponseCode();
                    if (code == 200) {
                        return "success";
                    } else {
                        return "fail";
                    }
                } catch (ProtocolException e) {
                    e.printStackTrace();
                    return "fail";
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    return "fail";
                } catch (IOException e) {
                    e.printStackTrace();
                    return "fail";
                }
            }

            @Override
            protected void onPostExecute(String result) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                if (result.equals("success")) {
                    try {
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        intent.setClass(context, Class.forName("com.efounder.chat.activity.LoginWebActivity"));
                        bundle.putString("url", url + "&type=2");
                        intent.putExtras(bundle);
                        context.startActivity(intent);
//                        ((MipcaActivityCapture) context).finish();
                        closeActivity(context);
                    } catch (ClassNotFoundException ce) {
                        ce.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(context, ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                    ((MipcaActivityCapture) context).restartDecode();
                }
            }
        }.execute(url);
    }


    private static void closeActivity(Context context) {
        if (closeActivity == true) {
            ((Activity) context).finish();
        }
    }
}
