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.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.util.HashMap;

/**
 * 二维码识别后的解析处理
 *
 * @author YQS
 * @date 2019/07/23
 */

public class QRParseManager {

    private static final String TAG = "QRParseManager";
    //识别完成是否结束当前界面
    private boolean closeActivity;
    private Context mContext;
    //二维码字符串
    private String qrString;

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

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

    public QRParseManager(Context context, String qrString) {
        this(context, qrString, false);
    }

    public QRParseManager(Context context, String qrString, boolean closeActivity) {
        mContext = context;
        this.closeActivity = closeActivity;
        this.qrString = qrString;
    }


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

    /**
     * 处理扫码结果
     *
     * @param context
     * @param qrString 扫码结果
     * @param close    扫码结束是否关闭当前activity
     */
    @Deprecated
    public static void handleresult(Context context, String qrString, boolean close) {
        QRParseManager qrParseManager = new QRParseManager(context, qrString, close);
        qrParseManager.startParse();
    }

    /**
     * 开始解析处理二维码数据
     */
    public void startParse() {

        try {
            //山大扫描的正则表达式
            String patterString = "^((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s].*data.*\\{.*type.*.*QRLogin.*\\}";

            if (qrString.matches(patterString)) {
                //https://mobile.solarsource.cn/ospstore/sduzx.html?data={"type":"QRLogin","url":"","authId":""}
                if (qrString.contains("{") && qrString.contains("}") && qrString.contains("QRLogin")) {
                    qrString = qrString.substring(qrString.indexOf("{"), qrString.indexOf("}") + 1);
                }
            }

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

            //2.字符串转json
            JSONObject jsonObject = new JSONObject(qrString);
            String type = jsonObject.optString("type", "");


            if (type.equals("weblogin")) {
                try {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    intent.setClass(mContext, Class.forName("com.efounder.chat.activity.LoginWebActivity"));
                    bundle.putString("result", qrString);
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (type.equals("addFriend") || type.equals("addPublicNum") || type.equals("addGroup")) {

                String userID = jsonObject.optString("userID", "");
                startActivity(type, userID);
            }

//            else if (type.equals("addGroup")) {
//                String userID = jsonObject.optString("userID","");
//                startActivity(type, userID);
//            }
//
            else if (type.equals("cnpcBill") || type.equals("safp")) {//todo 共享用
                startActivity(type, qrString);
            } else if (type.equals("qrlogin")) {//中建扫码登陆
                try {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    intent.setClass(mContext, Class.forName("com.efounder.chat.activity.LoginThirdWebActivity"));
                    bundle.putString("result", qrString);
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);
                    closeActivity();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (type.equals("QRLogin")) {//山大cas用
                try {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    intent.setClass(mContext, Class.forName("com.efounder.chat.activity.LoginThirdWebActivity"));
                    bundle.putString("result", qrString);
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);
                    closeActivity();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (type.equals("opLogin")) {//星际通讯用
                try {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    intent.setClass(mContext, Class.forName("com.efounder.chat.activity.LoginThirdWebActivity"));
                    bundle.putString("result", qrString);
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);
                    closeActivity();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (type.equals("gathering")) {//星际通讯收款用
                try {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    //TODO  添加跳转的类名
                    intent.setClass(mContext, Class.forName(mContext.getResources().getString(R.string.activity_energy_exchage_transfer)));

                    String ethAddress = jsonObject.optString("ethAddress", "");
                    if ("".equals(ethAddress)) {
                        ethAddress = jsonObject.optString("walletAddress", "");
                    }
                    bundle.putString("result", qrString);
                    bundle.putString("toAccount", jsonObject.optString("userId", ""));
                    bundle.putString("toAddress", ethAddress);
                    bundle.putString("count", jsonObject.optString("money", ""));
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);
                    closeActivity();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (type.equals("observeWallet")) {//星际资产观察钱包
                handlerObserveWallet(mContext, jsonObject);
            } else if (type.equals("tokenTrade")) {//星际资产代币交易
                handlerTokenTrade(mContext, 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(mContext, qrString);
                closeActivity();
                //网页
            } else if ("web".equals(type)) {
                String url = jsonObject.optString("url");
                String param = jsonObject.optString("param");
                String value = jsonObject.optString("value");
                Intent intent = new Intent(mContext, ChatWebViewActivity.class);
                intent.putExtra("url", url);
                intent.putExtra("param", param);
                intent.putExtra("value", value);
                mContext.startActivity(intent);
                closeActivity();
                //如果classMap中包含这个type，交给这个特别实现的二维码处理类处理
            } else if (qrHandleClassMap.containsKey(type)) {
                try {
                    IHandleQrContent iHandleQrContent = ReflectUtils.reflect(Class.forName(qrHandleClassMap.get(type))).newInstance().get();
                    iHandleQrContent.handleQrContent(mContext,qrString);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                dealOtherResult();
            }
        } catch (Exception e) {
            LogUtils.e("二维码识别 Exception：", e);
            dealOtherResult();
        }
    }

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


    //todo 处理星际资产相关信息
    private 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);
            closeActivity();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            closeActivity();
        }
    }

    //todo 处理星际资产代币交易
    private 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);
            closeActivity();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            closeActivity();
        }
    }

    private void startActivity(String type, final String userID) {
        if (!type.equals("") && !userID.equals("")) {
            final Intent intent = new Intent();
            Bundle bundle = new Bundle();
            if (type.equals("addFriend")) {
                try {
                    intent.setClass(mContext, Class.forName(mContext.getResources().getString(R.string.userinfo_actiivity_class)));
                    bundle.putInt("id", Integer.valueOf(userID));
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);
                    closeActivity();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else if (type.equals("addPublicNum")) {
                try {
                    intent.setClass(mContext, Class.forName("com.efounder.chat.activity.AddPublicFriendInfoActivity"));
                    bundle.putString("userID", userID);
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);
                    closeActivity();
                } catch (Exception 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(mContext, Class.forName("com.efounder.chat.activity.AddGroupUserInfoActivity"));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                mContext.startActivity(intent);
                closeActivity();
            } else if (type.equals("cnpcBill")) {//进入RN票据扫描，传递整个json//// TODO: 17-8-3 共享用
                //中建进入内控上传页面
                if (EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("OSPMobileCSCES")) {
                    try {
                        intent.setClass(mContext, Class.forName("com.pansoft.invoiceocrlib.activity.InvoiceListScanActivity"));
                        //userID={"type":"cnpcBill","GUID":"GAD47173C0FF410A8F8D4025BBCDBB5E","BM":""}
                        intent.putExtra("qrResult", userID);
                        mContext.startActivity(intent);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    closeActivity();
                    return;
                }

                DisplayMetrics metric = new DisplayMetrics();
                ((WindowManager) mContext.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(mContext, 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);
                    mContext.startActivity(intent);
//                    ((MipcaActivityCapture) context).finish();
                    closeActivity();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (type.equals("safp")) {//进入RN票据扫描，传递整个json//// TODO: 17-8-3 共享用

                DisplayMetrics metric = new DisplayMetrics();
                ((WindowManager) mContext.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(mContext, 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();
                }
                mContext.startActivity(intent);
                closeActivity();
            }
        }
    }


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

            @Override
            protected void onPreExecute() {
                dialog = new ProgressDialog(mContext);
                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(mContext, Class.forName("com.efounder.chat.activity.LoginWebActivity"));
                        bundle.putString("url", url + "&type=2");
                        intent.putExtras(bundle);
                        mContext.startActivity(intent);
//                        ((MipcaActivityCapture) context).finish();
                        closeActivity();
                    } catch (ClassNotFoundException ce) {
                        ce.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(mContext.getApplicationContext(), ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                    ((MipcaActivityCapture) mContext).restartDecode();
                }
            }
        }.execute(url);
    }


    private void closeActivity() {
        if (closeActivity == true) {
            ((Activity) mContext).finish();
        }
    }
}
