package com.xypower.mpmaster.sms;


import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.Base64;

import androidx.core.app.ActivityCompat;

import com.dev.devapi.api.SysApi;
import com.xypower.common.FilesUtils;
import com.xypower.common.JSONUtils;
import com.xypower.common.MicroPhotoContext;
import com.xypower.common.NetworkUtils;
import com.xypower.common.RegexUtil;
import com.xypower.mpmaster.MpMasterService;

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

import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;


/*
 * 短信接收类
 *
 * */
public class SimUtil {
    public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
    public static final String SMS_DELIVER_ACTION = "android.provider.Telephony.SMS_DELIVER";

    // 自定义ACTION常数 作为广播的IntentFilter识别常数
    public static String SMS_SEND_ACTION = "com.xypower.mpmaster.SMS_SEND_ACTION";

    public static String SMSRESTARTTYPE = "restartType";

    private static int mRequestCode = 1;
    private static String sendmessage = null;//要回复的短信

    private static int restartType = -1;//重启类型

    //短信解析
    public static void analysisSMSInfo(final Context context, final Intent intent, final SmsMessage smsMessage) {
        sendmessage = null;
        restartType = -1;
        SmsMessageModel smsInfo = getSMSInfo(intent, smsMessage);
        if (smsInfo != null) {
            String content = smsInfo.getContent();
            int pos = content.lastIndexOf("##");
            if (pos != -1) {
                content = content.substring(0, pos);
            }
            int slot = smsInfo.getSlot();//那张卡收到的短信
            String sender = smsInfo.getSender();//收到的短信的手机号
            String sendmessage = "ERROR";//要回复的短信
            List<Integer> abslist = new ArrayList<>();//收到的短信内容拆分包装成数组
            boolean ifmessageCorrect = false;//用来判断收到的短信内容是否正确
            if (StringUtils.isEmpty(content)) {
                return;
            }
            if (content.toLowerCase().contains(SmsTypeEnum.UPD_CFG_FILE.value().toLowerCase())) { //修改配置文件中参数
                updateConfig(content);
            } else if (content.toLowerCase().contains(SmsTypeEnum.GET_CFG_FILE.value().toLowerCase())) {//获取配置文件中参数
                queryConfig(content);
            } else if (content.toLowerCase().contains(SmsTypeEnum.UPD_FILE.value().toLowerCase())) {//替换配置文件
                updateFile(content);
            } else if (content.toLowerCase().contains(SmsTypeEnum.GET_FILE.value().toLowerCase())) {//获取整个配置文件
                queryFile(content);
            } else if (content.contains(SmsTypeEnum.REBOOT1.value())) {
                ifmessageCorrect = true;
                restartType = 0;
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.REBOOT2.value()) || content.contains(SmsTypeEnum.REBOOT3.value())) {
                ifmessageCorrect = true;
                restartType = 0;
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.RESTART_MP.value()) || content.contains(SmsTypeEnum.RESTART_MP2.value())) {
                ifmessageCorrect = true;
                restartType = 1;
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.RESTART_MPMST.value()) || content.contains(SmsTypeEnum.RESTART_MPMST2.value())) {
                ifmessageCorrect = true;
                restartType = 2;
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.RESTART_BOTH_APPS.value()) || content.contains(SmsTypeEnum.RESTART_BOTH_APPS2.value())) {
                ifmessageCorrect = true;
                restartType = 3;
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.SET_YW_SCHEDULE.value())) {
                ifmessageCorrect = true;
                String[] split1 = StringUtils.splitString1(content);
                if (split1 != null && split1.length == 2) {
                    String s = split1[1];
                    String[] split2 = StringUtils.splitString2(s);
                    int spilt2len = split2.length;
                    if (split2 != null && spilt2len > 1 && spilt2len % 2 == 1) {
                        String num = split2[0];
                        Integer integer = StringUtils.convert2Int(num);
                        if (integer != null) {
                            if (integer == 0) {//删除所有运维
                                ifmessageCorrect = true;
                            } else {
                                if (spilt2len == integer * 2 + 1) {
                                    int times = 0;
                                    for (int i = 0; i < spilt2len; i++) {
                                        if (i == 0) {
                                            continue;
                                        }
                                        String ts = split2[i];
                                        Integer time = StringUtils.convert2Int(ts);
                                        if (i % 2 == 1) {
                                            if (time > 23) {
                                                ifmessageCorrect = false;
                                                break;
                                            }
                                            times = time * 3600;
                                        } else {
                                            if (time > 59) {
                                                ifmessageCorrect = false;
                                                break;
                                            }
                                            times += time * 60;
                                            abslist.add(times);
                                        }
                                    }
                                }
                            }
                            if (ifmessageCorrect) {
                                UpdateSysConfigUtil.setAbsHeartbeats(context, abslist);
                            }
                        }
                    }
                }
                restartType = 2;
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.GET_YW_SCHEDULE.value())) {
                List<Integer> absHeartbeats = UpdateSysConfigUtil.getAbsHeartbeats(context);
                if (absHeartbeats == null || absHeartbeats.size() == 0) {
                    sendmessage = SmsTypeEnum.GET_YW_SCHEDULE.value() + "=0";
                } else {
                    int length = absHeartbeats.size();
                    sendmessage = SmsTypeEnum.GET_YW_SCHEDULE.value() + "=" + length;
                    for (int i = 0; i < length; i++) {
                        int mAbsHeartbeatTime = 0;
                        mAbsHeartbeatTime = absHeartbeats.get(i);
                        int hour = mAbsHeartbeatTime / 3600;
                        int minute = (mAbsHeartbeatTime % 3600) / 60;
                        sendmessage += "," + hour + "," + minute;
                    }
                }
            } else if (content.contains(SmsTypeEnum.SET_OPERATE.value())) {
                String[] split1 = StringUtils.splitString1(content);
                if (split1 != null && split1.length > 1) {
                    String s = split1[1];
                    Integer integer = StringUtils.convert2Int(s);
                    if (integer != null) {
                        if (integer == 0 || integer == 1) {
                            ifmessageCorrect = true;
                            UpdateSysConfigUtil.setMntnMode(context, integer);
                        }
                    }
                }
                restartType = 2;
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.GET_OPERATE.value())) {
                int mntnMode = UpdateSysConfigUtil.getMntnMode(context);
                sendmessage = SmsTypeEnum.GET_OPERATE.value() + "=" + mntnMode;
            } else if (content.contains(SmsTypeEnum.SET_OPERATE_URL.value())) {
                restartType = 2;
                String[] split1 = StringUtils.splitString1(content);
                if (split1 != null && split1.length > 1) {
                    String s = split1[1];
                    String[] split2 = StringUtils.splitString2(s);
                    if (split2 != null && split2.length >= 2) {
                        String ipAddress = split2[0];
                        String port = split2[1];
                        boolean b = RegexUtil.checkIpAddress(ipAddress);
                        if (b) {
                            Integer integer = StringUtils.convert2Int(port);
                            if (integer != null) {
                                ifmessageCorrect = true;
                                UpdateSysConfigUtil.setMntnServer(context, ipAddress, integer);
                            }
                        }
                    }
                }
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.GET_OPERATE_URL.value())) {
                String mntnServer = UpdateSysConfigUtil.getMntnServer(context);
                sendmessage = SmsTypeEnum.GET_OPERATE_URL.value() + "=" + mntnServer;
            } else if (content.contains(SmsTypeEnum.UPDATE.value())) {
                String[] split1 = StringUtils.splitString1(content);
                if (split1 != null && split1.length == 2) {
                    ifmessageCorrect = true;
                    String s = split1[1];
                    DownloadUtils downloadUtils = new DownloadUtils(context.getApplicationContext(), s, "test.app");
                }
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.SET_CMDID.value())) {
                restartType = 1;
                String[] split1 = StringUtils.splitString1(content);
                if (split1 != null && split1.length > 1) {
                    ifmessageCorrect = true;
                    String cmdid = split1[1];
                    UpdateSysConfigUtil.setCmdid(context, cmdid);
                }
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.GET_CMDID.value())) {
                String cmdid = UpdateSysConfigUtil.getCmdid(context);
                String serialNo = UpdateSysConfigUtil.getSerialNo();
                sendmessage = SmsTypeEnum.GET_CMDID.value() + "=" + serialNo + "," + cmdid;
            } else if (content.contains(SmsTypeEnum.SET_IP.value())) {
                restartType = 1;
                String[] split1 = StringUtils.splitString1(content);
                if (split1 != null && split1.length > 1) {
                    String s = split1[1];
                    String[] split2 = StringUtils.splitString2(s);
                    if (split2 != null && (split2.length == 2 || split2.length == 4)) {
                        String server;
                        Integer integer;
                        server = split2[0];
                        String port = split2[1];
                        integer = StringUtils.convert2Int(port);
                        Integer utcp = -1;
                        Integer encrypto = -1;
                        if (integer != null) {
                            ifmessageCorrect = true;
                            if (split2.length == 4) {
                                String s1 = split2[2];
                                utcp = StringUtils.convert2Int(s1);
                                utcp = getUtcp(utcp);
                                String s2 = split2[3];
                                encrypto = StringUtils.convert2Int(s2);
                                encrypto = getEncrypto(encrypto);
                                if (utcp == -1 || encrypto == -1) {
                                    ifmessageCorrect = false;
                                }
                            }
                        }
                        if (ifmessageCorrect) {
                            UpdateSysConfigUtil.setIP(context, server, integer, utcp, encrypto);
                        }
                    }
                }
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.GET_IP.value())) {
                String ip = UpdateSysConfigUtil.getIP(context);
                sendmessage = SmsTypeEnum.GET_IP.value() + "=" + ip;
            } else if (content.contains(SmsTypeEnum.SET_OSD.value())) {
                restartType = 1;
                String[] split1 = StringUtils.splitString1(content);
                sendmessage = getSendString(content, ifmessageCorrect);
                if (split1 != null && split1.length == 2) {
                    ifmessageCorrect = true;
                    JSONObject osdmap = new JSONObject();
                    String s = split1[1];
                    String[] split2 = StringUtils.splitString2(s);
                    int spilt2len = split2.length;
                    if (split2 != null && spilt2len > 1 && spilt2len % 2 == 1) {
                        String num = split2[0];
                        Integer integer = StringUtils.convert2Int(num);
                        if (integer != null) {
                            for (int i = 0; i < spilt2len; i++) {
                                if (i == 0) {
                                    continue;
                                }
                                if (i % 2 == 1) {
                                    if ((i + 1) <= spilt2len) {
                                        String s1 = split2[i];
                                        Integer position = StringUtils.convert2Int(s1);
                                        if (position != null) {
                                            try {
                                                if (position == 1) {
                                                    osdmap.put(UpdateSysConfigUtil.leftTop, split2[i + 1]);
                                                } else if (position == 2) {
                                                    osdmap.put(UpdateSysConfigUtil.rightTop, split2[i + 1]);
                                                } else if (position == 3) {
                                                    osdmap.put(UpdateSysConfigUtil.leftBottom, split2[i + 1]);
                                                } else if (position == 4) {
                                                    osdmap.put(UpdateSysConfigUtil.rightBottom, split2[i + 1]);
                                                } else {
                                                    ifmessageCorrect = false;
                                                }
                                            } catch (JSONException e) {
                                                throw new RuntimeException(e);
                                            }
                                        } else {
                                            ifmessageCorrect = false;
                                        }
                                    } else {
                                        ifmessageCorrect = false;
                                    }
                                }
                            }
                            if (integer == 0) {//所有通道
                                ifmessageCorrect = true;
                                MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
                                int channelnum = mpAppConfig.channels;
                                if (channelnum != 0) {
                                    if (ifmessageCorrect) {
                                        for (int i = 1; i <= channelnum; i++) {
                                            UpdateSysConfigUtil.setChannelOSD(i, osdmap);
                                        }
                                    }
                                }
                            } else {
                                if (ifmessageCorrect) {
                                    UpdateSysConfigUtil.setChannelOSD(integer, osdmap);
                                }
                            }

                        }
                    }
                }
            } else if (content.contains(SmsTypeEnum.GET_OSD.value())) {
                String[] split = StringUtils.splitString1(content);
                if (split != null && split.length == 2) {
                    sendmessage = SmsTypeEnum.GET_OSD.value() + "=";
                    ifmessageCorrect = true;
                    Integer channel = StringUtils.convert2Int(split[1]);
                    if (channel != null) {
                        if (channel == 0) {
                            MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
                            int channelnum = mpAppConfig.channels;
                            if (channelnum != 0) {
                                if (ifmessageCorrect) {
                                    for (int i = 1; i <= channelnum; i++) {
                                        sendmessage += channel + ":{";
                                        JSONObject channelOSD = UpdateSysConfigUtil.getChannelOSD(channel);
                                        if (channelOSD != null) {
                                            String leftTop = channelOSD.optString(UpdateSysConfigUtil.leftTop);
                                            String rightTop = channelOSD.optString(UpdateSysConfigUtil.rightTop);
                                            String leftBottom = channelOSD.optString(UpdateSysConfigUtil.leftBottom);
                                            String rightBottom = channelOSD.optString(UpdateSysConfigUtil.rightBottom);
                                            if (leftTop != null && StringUtils.isNotEmpty(leftTop)) {
                                                sendmessage += "左上:" + leftTop;
                                            }
                                            if (rightTop != null && StringUtils.isNotEmpty(rightTop)) {
                                                sendmessage += ",右上:" + rightTop;
                                            }
                                            if (leftBottom != null && StringUtils.isNotEmpty(leftBottom)) {
                                                sendmessage += ",左下:" + leftBottom;
                                            }
                                            if (rightBottom != null && StringUtils.isNotEmpty(rightBottom)) {
                                                sendmessage += ",右下:" + rightBottom;
                                            }
                                        } else {
                                            sendmessage += "无水印";
                                        }
                                        if (i == channelnum) {
                                            sendmessage += channel + "}";
                                        } else {
                                            sendmessage += channel + "},";
                                        }
                                    }
                                }
                            }
                        } else {
                            JSONObject channelOSD = UpdateSysConfigUtil.getChannelOSD(channel);
                            if (channelOSD != null) {
                                String leftTop = channelOSD.optString(UpdateSysConfigUtil.leftTop);
                                String rightTop = channelOSD.optString(UpdateSysConfigUtil.rightTop);
                                String leftBottom = channelOSD.optString(UpdateSysConfigUtil.leftBottom);
                                String rightBottom = channelOSD.optString(UpdateSysConfigUtil.rightBottom);
                                if (leftTop != null && StringUtils.isNotEmpty(leftTop)) {
                                    sendmessage += "左上:" + leftTop;
                                }
                                if (rightTop != null && StringUtils.isNotEmpty(rightTop)) {
                                    sendmessage += ",右上:" + rightTop;
                                }
                                if (leftBottom != null && StringUtils.isNotEmpty(leftBottom)) {
                                    sendmessage += ",左下:" + leftBottom;
                                }
                                if (rightBottom != null && StringUtils.isNotEmpty(rightBottom)) {
                                    sendmessage += ",右下:" + rightBottom;
                                }
                            } else {
                                sendmessage += "无水印";
                            }
                        }
                    } else {
                        ifmessageCorrect = false;
                    }
                }
            } else if (content.contains(SmsTypeEnum.SET_PHOTO_SCHEDULE_LIST.value())) {
                restartType = 1;
                String[] split1 = StringUtils.splitString1(content);
                if (split1 != null && split1.length > 1) {
                    String s = split1[1];
                    String[] split2 = StringUtils.splitString2(s);
                    if (split2 != null && split2.length == 2) {
                        Integer channel = StringUtils.convert2Int(split2[0]);
                        if (channel != null) {
                            ifmessageCorrect = true;
                            String msg = split2[1];
                            UpdateSysConfigUtil.setPhotoSchedules(channel, msg);
                        }
                    }
                }
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.GET_PHOTO_SCHEDULE_LIST.value())) {
                String[] split1 = StringUtils.splitString1(content);
                if (split1 != null && split1.length == 2) {
                    Integer channel = StringUtils.convert2Int(split1[1]);
                    String photoSchedules = UpdateSysConfigUtil.getPhotoSchedules(channel);
                    sendmessage = SmsTypeEnum.GET_PHOTO_SCHEDULE_LIST.value() + "=" + photoSchedules;
                }
            } else if (content.contains(SmsTypeEnum.SET_RESOLUTION.value())) {
                restartType = 1;
                String[] split1 = StringUtils.splitString1(content);
                if (split1 != null && split1.length > 1) {
                    String s = split1[1];
                    String[] split2 = StringUtils.splitString1(s);
                    if (split2 != null && split2.length == 5) {
                        Integer channel = StringUtils.convert2Int(split2[0]);
                        Integer resolutionCX = StringUtils.convert2Int(split2[1]);
                        Integer resolutionCY = StringUtils.convert2Int(split2[2]);
                        Integer videoCX = StringUtils.convert2Int(split2[3]);
                        Integer videoCY = StringUtils.convert2Int(split2[4]);
                        if (channel != null && resolutionCX != null && resolutionCY != null && videoCX != null && videoCY != null) {
                            ifmessageCorrect = true;
                            UpdateSysConfigUtil.setChannelResolution(channel, resolutionCX, resolutionCY, videoCX, videoCY);
                            UpdateSysConfigUtil.restartApp(context);
                        }
                    }
                }
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.GET_RESOLUTION.value())) {
                String[] split = StringUtils.splitString1(content);
                Integer channel = StringUtils.convert2Int(split[0]);
                HashMap<String, Integer> hashMap = UpdateSysConfigUtil.getChannelResolution(channel);
                Integer resolutionCX = hashMap.get("resolutionCX");
                Integer resolutionCY = hashMap.get("resolutionCY");
                Integer videoCX = hashMap.get("videoCX");
                Integer videoCY = hashMap.get("videoCY");
                sendmessage = SmsTypeEnum.GET_RESOLUTION.value() + "=" + resolutionCX + "," + resolutionCY + "," + videoCX + "," + videoCY;
            } else if (content.contains(SmsTypeEnum.TAKE_PHOTO.value())) {
                String[] split = StringUtils.splitString1(content);
                if (split != null && split.length == 3) {
                    ifmessageCorrect = true;
                    Integer channel = StringUtils.convert2Int(split[0]);
                    Integer preset = StringUtils.convert2Int(split[1]);
                    Integer type = StringUtils.convert2Int(split[2]);
                    if (channel != null) {
                        boolean photoOrVideo;
                        if (type == 0) {
                            photoOrVideo = true;
                        } else {
                            photoOrVideo = false;
                        }
                        UpdateSysConfigUtil.takePhotoOrVideo(context, channel, preset, photoOrVideo);
                    }
                    sendmessage = getSendString(content, ifmessageCorrect);
                }
            } else if (content.contains(SmsTypeEnum.SET_HEART.value())) {
                restartType = 1;
                String[] split1 = StringUtils.splitString1(content);
                if (split1 != null && split1.length == 2) {
                    ifmessageCorrect = true;
                    String s = split1[1];
                    Integer integer = StringUtils.convert2Int(s);
                    UpdateSysConfigUtil.setHB(context, integer);
                }
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.GET_HEART.value())) {
                int hb = UpdateSysConfigUtil.getHB(context);
                sendmessage = SmsTypeEnum.GET_HEART.value() + "=" + hb;
            } else if (content.contains(SmsTypeEnum.SIMCARD.value())) {
                sendmessage = getSimcardInfo(context);
            } else if (content.contains(SmsTypeEnum.SET_AUTO_TIME.value())) {
                restartType = 1;
                sendmessage = setAutoTime(context, content);
            } else if (content.contains(SmsTypeEnum.SET_TP.value())) {
                restartType = 1;
                String[] split1 = StringUtils.splitString1(content);
                if (split1 != null && split1.length == 2) {
                    ifmessageCorrect = true;
                    String s = split1[1];
                    Integer integer = StringUtils.convert2Int(s);
                    UpdateSysConfigUtil.setTB(context, integer);
                }
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.GET_TP.value())) {
                int tb = UpdateSysConfigUtil.getTB(context);
                sendmessage = SmsTypeEnum.GET_TP.value() + "=" + tb;
            } else if (content.contains(SmsTypeEnum.SET_PACKAGE.value())) {
                restartType = 1;
                String[] split1 = StringUtils.splitString1(content);
                if (split1 != null && split1.length == 2) {
                    ifmessageCorrect = true;
                    String s = split1[1];
                    Integer integer = StringUtils.convert2Int(s);
                    UpdateSysConfigUtil.setPackage(context, integer);
                }
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.GET_PACKAGE.value())) {
                int aPackage = UpdateSysConfigUtil.getPackage(context);
                sendmessage = SmsTypeEnum.GET_PACKAGE.value() + "=" + aPackage;
            } else if (content.contains(SmsTypeEnum.CLEAR_PHOTO.value())) {
                ifmessageCorrect = true;
                UpdateSysConfigUtil.clearHistoryPic(context);
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.CLEAR_LOG.value())) {
                ifmessageCorrect = true;
                UpdateSysConfigUtil.clearHistoryLogs(context);
                sendmessage = getSendString(content, ifmessageCorrect);
            } else if (content.contains(SmsTypeEnum.CLEAR_ALL.value())) {
                ifmessageCorrect = true;
                UpdateSysConfigUtil.clearHistoryPic(context);
                UpdateSysConfigUtil.clearHistoryLogs(context);
                sendmessage = getSendString(content, ifmessageCorrect);
            }
            sendSms(context, slot, sender, sendmessage, restartType);
        }

    }

    private static int getUtcp(Integer utcp) {
        int apputcp = -1;
        //短信文档中  0：udp  1:tcp  app应用中  0：tcp 1:udp  所以需要转换一下
        if (utcp != null && (utcp == 0 || utcp == 1)) {
            if (utcp == 0) {
                apputcp = 1;
            } else if (utcp == 1) {
                apputcp = 0;
            }
        }
        return apputcp;
    }

    private static int getEncrypto(Integer encrypto) {
        int appencrypto = -1;
        //短信文档中  1：密文,2：明文 3：不加密  app应用中   0：不加密 1：明文  2：加密  所以需要转换一下
        if (encrypto != null && (encrypto == 1 || encrypto == 2 || encrypto == 3)) {
            if (encrypto == 1) {
                appencrypto = 2;
            } else if (encrypto == 2) {
                appencrypto = 1;
            } else if (encrypto == 3) {
                appencrypto = 0;
            }
        }
        return appencrypto;
    }

    private static String getSendString(String content, boolean ifmessageCorrect) {
        String sendmessage;
        String menssageBack = "";
        if (ifmessageCorrect) {
            menssageBack = " OK";
        } else {
            menssageBack = " ERROR";
        }
        sendmessage = content + menssageBack;
        return sendmessage;
    }

    public static String getSimcardInfo(Context context) {

        StringBuilder result = new StringBuilder();

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {

                SubscriptionManager subscriptionManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

                int activeSubscriptionInfoCount = subscriptionManager.getActiveSubscriptionInfoCountMax();

                int activeSubId = SubscriptionManager.getActiveDataSubscriptionId();

                for (int slotIdx = 0; slotIdx < activeSubscriptionInfoCount; slotIdx++) {

                    // SIM1:网络类型（2G/3G/4G）、信号强度、信号等级、网络状态（开启/关闭）、IP地址
                    // SIM2:网络类型（2G/3G/4G）、信号强度、信号等级、网络状态（开启/关闭）、IP地址

                    result.append("SIM" + Integer.toString(slotIdx + 1) + "=");
                    int subIds[] = subscriptionManager.getSubscriptionIds(slotIdx);
                    if (subIds == null || subIds.length == 0) {
                        result.append("未激活 ");
                        continue;
                    }

                    boolean isActiveSlot = false;
                    for (int subId : subIds) {
                        if (subId == activeSubId) {
                            isActiveSlot = true;
                            break;
                        }
                    }

                    TelephonyManager tm = telephonyManager.createForSubscriptionId(subIds[0]);

                    SubscriptionInfo subscriptionInfo = subscriptionManager.getActiveSubscriptionInfo(subIds[0]);
                    if (subscriptionInfo == null) {
                        continue;
                    }

                    int simState = telephonyManager.getSimState(slotIdx);
                    result.append(subscriptionInfo.getCarrierName());
                    int networkType = tm.getDataNetworkType();
                    result.append("," + getNetworkName(networkType));
                    result.append("," + getSimStateName(simState));

                    String ss = MpMasterService.getSystemProperty("vendor.ril.nw.signalstrength.lte." + Integer.toString(slotIdx + 1));
                    if (!TextUtils.isEmpty(ss)) {
                        int pos = ss.indexOf(',');
                        if (pos != -1) {
                            ss = ss.substring(0, pos);

                            result.append(",SL=" + ss);
                            int ssVal = Integer.parseInt(ss);
                            result.append("/" + Integer.toString(MpMasterService.getSignalLevel(ssVal, 5)));
                        }

                    }

                    result.append(isActiveSlot ? ",默认" : "");

                    if (isActiveSlot) {
                        result.append(",IP=" + NetworkUtils.getMobileNetworkIp(context));
                    }

                    result.append(" ");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return result.toString().trim();
    }

    private static String setAutoTime(Context context, String content) {
        String result = "";
        try {
            String[] parts = TextUtils.split(content.substring(SmsTypeEnum.SET_AUTO_TIME.value().length()), "(\\s|,|，)");
            if (parts != null) {
                int autoTimeType = 0;
                boolean onOff = false;
                for (String part : parts) {
                    if (TextUtils.isEmpty(part)) {
                        continue;
                    }

                    int pos = part.indexOf("=");
                    if (pos == -1) {
                        continue;
                    }

                    String key = part.substring(0, pos);
                    String value = part.substring(pos + 1);
                    if (TextUtils.equals(key, "act")) {
                        if (TextUtils.equals(value, "on")) {
                            onOff = true;
                        }
                    } else if (TextUtils.equals(key, "type")) {
                        if (TextUtils.equals(value, "net")) {
                            autoTimeType = 1;
                        } else if (TextUtils.equals(value, "gps")) {
                            autoTimeType = 2;
                        }
                    }
                }

                if (autoTimeType != 0) {
                    if (autoTimeType == 1) {
                        SysApi.setGlobalInt(context, "auto_time", onOff ? 1 : 0);
                    } else if (autoTimeType == 2) {
                        SysApi.setGlobalInt(context, "auto_time_gps", onOff ? 1 : 0);
                    }
                }
                // query the value
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        try {
            int autoTime = SysApi.getGlobalInt(context, "auto_time");
            int autoTimeGps = SysApi.getGlobalInt(context, "auto_time_gps");

            result = "auto_time=" + Integer.toString(autoTime) + " auto_time_gps" + Integer.toString(autoTimeGps);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return result;
    }


    //修改配置文件中参数
    private static void updateConfig(String content) {
        boolean ifmessageCorrect = true;
        Map<String, String> fields = new HashMap<>();
        try {
            String[] parts = StringUtils.splitStringByDh(content.substring(SmsTypeEnum.UPD_CFG_FILE.value().length()));
            int fileType = 0;
            int numberOfFields = 0;
            String filePath = null;
            String fileName = null;
            if (parts != null) {
                for (String part : parts) {
                    if (TextUtils.isEmpty(part)) {
                        continue;
                    }
                    int pos = part.indexOf("=");
                    if (pos == -1) {
                        continue;
                    }
                    String key = part.substring(0, pos);
                    String value = part.substring(pos + 1);
                    if (value.contains("&&")) {
                        value = value.replace("&&", ",");
                    }
                    if (TextUtils.equals(key, "f")) {
                        fileType = Integer.parseInt(value);
                    } else if (TextUtils.equals(key, "c")) {
                        numberOfFields = Integer.parseInt(value);
                    } else if (TextUtils.equals(key, "r")) {
                        restartType = Integer.parseInt(value);
                    } else {
                        fields.put(key, value);
                    }
                }
                HashMap<String, String> hashMap = ValueTypeUtil.checkFilePathAndName(fileType);
                filePath = hashMap.get(UpdateSysConfigUtil.FILEPATH);
                fileName = hashMap.get(UpdateSysConfigUtil.FILENAME);
                if (!TextUtils.isEmpty(filePath) && !TextUtils.isEmpty(fileName) && numberOfFields > 0) {
                    for (int idx = 0; idx < numberOfFields; idx++) {
                        String idxStr = Integer.toString(idx);
                        String configName = fields.containsKey("n" + idxStr) ? fields.get("n" + idxStr) : null;
                        int configType = fields.containsKey("t" + idxStr) ? Integer.parseInt(fields.get("t" + idxStr)) : 0;
                        String configValue = fields.containsKey("v" + idxStr) ? fields.get("v" + idxStr) : null;
                        if (StringUtils.isNotEmpty(configValue)) {
                            if (configType == 0) { // Number
                                Long val = Long.parseLong(configValue);
                                JSONUtils.updateConfigFile(filePath, fileName, configName, configType, val);
                            } else if (configType == 1) {
                                JSONUtils.updateConfigFile(filePath, fileName, configName, configType, configValue);
                            } else if (configType == 2) { // Float
                                Float val = Float.parseFloat(configValue);
                                JSONUtils.updateConfigFile(filePath, fileName, configName, configType, val);
                            } else if (configType == 3) { //数组
                                JSONArray objects = new JSONArray(configValue);
                                JSONUtils.updateConfigFile(filePath, fileName, configName, configType, objects);
                            }
                        } else {
                            ifmessageCorrect = false;
                        }
                    }
//                    if (rebootMpApp != 0) {
//                        MicroPhotoContext.restartMpApp(context, "Config Updated From SMS");
//                    } else {
//                        Intent intent = new Intent();
//                        intent.setAction(MicroPhotoContext.ACTION_UPDATE_CONFIGS_MP);
//                        intent.setPackage(MicroPhotoContext.PACKAGE_NAME_MPAPP);
//                        context.sendBroadcast(intent);
//                    }
                } else {
                    ifmessageCorrect = false;
                }
            } else {
                ifmessageCorrect = false;
            }
            if (ifmessageCorrect) {
                sendmessage = content + " OK";
            } else {
                sendmessage = content + " ERROR";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    //替换配置文件
    private static void updateFile(String content) {
        boolean ifmessageCorrect = true;
        Map<String, String> fields = new HashMap<>();
        try {
            String[] parts = StringUtils.splitStringByDh(content.substring(SmsTypeEnum.UPD_FILE.value().length()));
            int fileType = 0;
            int numberOfFields = 0;
            String filePath = null;
            String fileName = null;
            String fileStr = null;
            if (parts != null) {
                for (String part : parts) {
                    if (TextUtils.isEmpty(part)) {
                        continue;
                    }
                    int pos = part.indexOf("=");
                    if (pos == -1) {
                        continue;
                    }
                    String key = part.substring(0, pos);
                    String value = part.substring(pos + 1);
                    if (TextUtils.equals(key, "f")) {
                        fileType = Integer.parseInt(value);
                    } else if (TextUtils.equals(key, "v")) {
                        fileStr = value;
                    } else if (TextUtils.equals(key, "r")) {
                        restartType = Integer.parseInt(value);
                    } else if (TextUtils.equals(key, "p")) {
                        filePath = value;
                    }
                }
                if (StringUtils.isNotEmpty(fileStr)) {
                    if (StringUtils.isEmpty(filePath)) {
                        HashMap<String, String> hashMap = ValueTypeUtil.checkFilePathAndName(fileType);
                        filePath = hashMap.get(UpdateSysConfigUtil.FILEPATH);
                        fileName = hashMap.get(UpdateSysConfigUtil.FILENAME);
                        if (StringUtils.isEmpty(filePath) || StringUtils.isEmpty(fileName)) {
                            ifmessageCorrect = false;
                        } else {
                            filePath += fileName;
                        }
                    }
                    if (StringUtils.isNotEmpty(filePath)) {
                        byte[] decode = Base64.decode(fileStr, Base64.NO_WRAP);
                        FilesUtils.writeFile(filePath, decode);
                    } else {
                        ifmessageCorrect = false;
                    }
                } else {
                    ifmessageCorrect = false;
                }
            } else {
                ifmessageCorrect = false;
            }
            if (ifmessageCorrect) {
                sendmessage = content + " OK";
            } else {
                sendmessage = content + " ERROR";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //获取配置文件
    private static void queryFile(String content) {
        boolean ifmessageCorrect = true;
        String result = null;
        try {
            String[] parts = StringUtils.splitStringByDh(content.substring(SmsTypeEnum.GET_FILE.value().length()));
            int fileType = 0;
            String filePath = null;
            String fileName = null;
            String fileStr = null;
            if (parts != null) {
                for (String part : parts) {
                    if (TextUtils.isEmpty(part)) {
                        continue;
                    }
                    int pos = part.indexOf("=");
                    if (pos == -1) {
                        continue;
                    }
                    String key = part.substring(0, pos);
                    String value = part.substring(pos + 1);
                    if (TextUtils.equals(key, "f")) {
                        fileType = Integer.parseInt(value);
                    } else if (TextUtils.equals(key, "r")) {
                        restartType = Integer.parseInt(value);
                    } else if (TextUtils.equals(key, "p")) {
                        filePath = value;
                    }
                }
                HashMap<String, String> hashMap = ValueTypeUtil.checkFilePathAndName(fileType);
                filePath = hashMap.get(UpdateSysConfigUtil.FILEPATH);
                fileName = hashMap.get(UpdateSysConfigUtil.FILENAME);
                if (!TextUtils.isEmpty(filePath + fileName)) {
                    File file = new File(filePath + fileName);
                    if (file.exists()) {
                        try {
                            fileStr = Base64.encodeToString(FilesUtils.readAllBytes(file), Base64.NO_WRAP);
                            if (StringUtils.isEmpty(fileStr)) {
                                ifmessageCorrect = false;
                            }
                        } catch (Exception ex) {
                            ifmessageCorrect = false;
                        }
                    } else {
                        ifmessageCorrect = false;
                    }
                }
            } else {
                ifmessageCorrect = false;
            }
            if (ifmessageCorrect) {
                sendmessage = content + ",v=" + fileStr;
            } else {
                sendmessage = content + " ERROR";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //获取配置文件参数
    private static void queryConfig(String content) {
        boolean ifmessageCorrect = true;
        try {
            String[] parts = StringUtils.splitStringByDh(content.substring(SmsTypeEnum.GET_CFG_FILE.value().length()));
            int fileType = 0;
            String filePath = null;
            String fileName = null;
            int numberOfFields = 0;
            Map<String, String> fields = new HashMap<>();
            if (parts != null) {
                for (String part : parts) {
                    if (TextUtils.isEmpty(part)) {
                        continue;
                    }
                    int pos = part.indexOf("=");
                    if (pos == -1) {
                        continue;
                    }
                    String key = part.substring(0, pos);
                    String value = part.substring(pos + 1);
                    if (TextUtils.equals(key, "f")) {
                        fileType = Integer.parseInt(value);
                    } else if (TextUtils.equals(key, "c")) {
                        numberOfFields = Integer.parseInt(value);
                    } else if (TextUtils.equals(key, "p")) {
                        filePath = value;
                    } else if (TextUtils.equals(key, "r")) {
                        restartType = Integer.parseInt(value);
                    } else {
                        fields.put(key, value);
                    }
                }
                HashMap<String, String> hashMap = ValueTypeUtil.checkFilePathAndName(fileType);
                filePath = hashMap.get(UpdateSysConfigUtil.FILEPATH);
                fileName = hashMap.get(UpdateSysConfigUtil.FILENAME);

                JSONObject jsonObject = JSONUtils.getConfigFile(filePath, fileName);
                if (jsonObject != null) {
                    for (int idx = 0; idx < numberOfFields; idx++) {
                        String idxStr = Integer.toString(idx);
                        String configName = fields.containsKey("n" + idxStr) ? fields.get("n" + idxStr) : null;
                        if (StringUtils.isNotEmpty(configName)) {
                            Object o = jsonObject.get(configName);
                            if (o != null) {
                                int i = ValueTypeUtil.checkType(o);
                                content += (",t" + idxStr + "=" + i + "," + "v" + idxStr + "=" + o.toString());
                            }
                        }
                    }
                }
            } else {
                ifmessageCorrect = false;
            }
            if (ifmessageCorrect) {
                sendmessage = content;
            } else {
                sendmessage = content + " ERROR";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public static String getSimStateName(int simState) {
        switch (simState) {
            case TelephonyManager.SIM_STATE_UNKNOWN:
                return "未知";
            case TelephonyManager.SIM_STATE_ABSENT:
                return "无卡";
            case TelephonyManager.SIM_STATE_PIN_REQUIRED:
                return "PIN解锁";
            case TelephonyManager.SIM_STATE_PUK_REQUIRED:
                return "PUK解锁";
            case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
                return "锁定";
            case TelephonyManager.SIM_STATE_READY:
                return "就绪";
            case TelephonyManager.SIM_STATE_NOT_READY:
                return "未就绪";
            case TelephonyManager.SIM_STATE_PERM_DISABLED:
                return "";
            case TelephonyManager.SIM_STATE_CARD_IO_ERROR:
                return "错误";
            case TelephonyManager.SIM_STATE_CARD_RESTRICTED:
                return "限制";
        }
        return "";
    }

    public static String getNetworkName(int networkType) {
        switch (networkType) {
            case TelephonyManager.NETWORK_TYPE_GPRS:
            case TelephonyManager.NETWORK_TYPE_EDGE:
            case TelephonyManager.NETWORK_TYPE_CDMA:
            case TelephonyManager.NETWORK_TYPE_1xRTT:
            case TelephonyManager.NETWORK_TYPE_IDEN:
                return "2G";
            case TelephonyManager.NETWORK_TYPE_UMTS:
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
            case TelephonyManager.NETWORK_TYPE_HSDPA:
            case TelephonyManager.NETWORK_TYPE_HSUPA:
            case TelephonyManager.NETWORK_TYPE_HSPA:
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
            case TelephonyManager.NETWORK_TYPE_EHRPD:
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                return "3G";
            case TelephonyManager.NETWORK_TYPE_LTE:
                return "4G";
            default:
                return "未知";
        }
    }

    //短信解析
    public static SmsMessageModel getSMSInfo(final Intent intent, final SmsMessage smsMessage) {
        SmsMessageModel smsMessageModel = new SmsMessageModel();
        StringBuilder content = new StringBuilder();
        String sender = "";
        String dateContent = "";

        content.append(smsMessage.getMessageBody());// 得到短信内容
        // 得到发信息的号码
        sender = smsMessage.getOriginatingAddress();
        Date date = new Date(smsMessage.getTimestampMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        format.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        dateContent = format.format(date);

        // smsMessage.getIndexOnSim()
        int smsSlot = getSmsSlot(intent.getExtras());
        smsMessageModel.setContent(content.toString());
        smsMessageModel.setSender(sender);
        smsMessageModel.setDateContent(dateContent);
        smsMessageModel.setSlot(smsSlot);

        return smsMessageModel;
    }

    public static void setSmsMessageRead(Context context, SmsMessage smsMessage) {
        Cursor cursor = null;
        try {
            Uri uri = Uri.parse("content://sms/inbox");
            ContentResolver contentResolver = context.getContentResolver();

            List<Long> smsIds = new ArrayList<>();
            String[] projection = new String[]{"_id", "address", "person", "body", "date", "read",};
            String selection = "date>" + Long.toString(smsMessage.getTimestampMillis() - 5000);
            String sortOrder = null; // "date desc"
            cursor = contentResolver.query(uri, projection, selection, null, sortOrder);
            while (cursor.moveToNext()) {
                String smsBody = cursor.getString(3);
                String smsRead = cursor.getString(5);
                if (TextUtils.equals(smsMessage.getMessageBody(), smsBody) && TextUtils.equals("0", smsRead)) {
                    smsIds.add(Long.valueOf(cursor.getLong(0)));
                }
            }
            if (cursor != null) {
                cursor.close();
            }
            cursor = null;

            if (!smsIds.isEmpty()) {
                uri = Uri.parse("content://sms/");
                ContentValues values = new ContentValues();
                values.put("read", "1");
                for (Long smsId : smsIds) {
                    // int rows = contentResolver.update(uri, values, "_id=?", new String[]{Long.toString(smsId)});
                    int rows = contentResolver.delete(uri, "_id=?", new String[]{Long.toString(smsId)});
                    if (rows == 1) {
                        Log.i("SMS", "Successfully");
                    }
                }

                contentResolver.notifyChange(uri, null);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            FilesUtils.closeFriendly(cursor);
        }
    }

    public static void clearSms(Context context) {
        Cursor cursor = null;
        try {
            Uri uri = Uri.parse("content://sms");
            ContentResolver contentResolver = context.getContentResolver();
            contentResolver.delete(uri, "_id>0", null);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //获取是哪个sim卡收到短信
    private static int getSmsSlot(Bundle bundle) {
        int slot = -1;
        Set<String> keySet = bundle.keySet();
        for (String key : keySet) {
            String lcKey = key.toLowerCase();
            if (lcKey.contains("slot") || lcKey.contains("sim")) {
                Object value = bundle.get(key);
                if (value == null) {
                    continue;
                }

                if (value instanceof Integer) {
                    Integer intVal = (Integer) value;
                    slot = intVal.intValue();
                } else if (value instanceof String) {
                    String str = (String) value;
                    if (str.equals("0") | str.equals("1") | str.equals("2")) {
                        // slot = bundle.getInt(key, -1);
                        slot = Integer.parseInt(str);
                    }
                }

                break;
            }
        }
        return slot;
    }

    //指定sim卡位置发送短信
    public static void sendSms(Context mContext, int slot, String sender, String message, int restartType) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            SubscriptionManager localSubscriptionManager = SubscriptionManager.from(mContext);
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            if (localSubscriptionManager.getActiveSubscriptionInfoCount() > 1) {
                List localList = localSubscriptionManager.getActiveSubscriptionInfoList();
                boolean doubleSim = isDoubleSim(mContext);
                SubscriptionInfo simInfoAnother = null;
                if (doubleSim) {
                    if (localList != null && localList.size() > 1) {
                        if (slot == 0) {
                            simInfoAnother = (SubscriptionInfo) localList.get(0);
                        } else {
                            simInfoAnother = (SubscriptionInfo) localList.get(1);
                        }
                    }
                }
                Intent itSend = new Intent(SMS_SEND_ACTION);
                itSend.putExtra(SMSRESTARTTYPE, restartType);
//                itSend.putExtra(SMSIFCORRECT, true);
//                itSend.putExtra(SMSDATA, (Serializable) jsonArray);
                //sendIntent参数为传送后接受的广播信息PendingIntent
                PendingIntent sendPI = PendingIntent.getBroadcast(mContext, mRequestCode++, itSend, 0);

//                Intent itDeliver = new Intent(SMS_DELIVERED_ACTION);
                //deliveryIntent参数为传送后接受的广播信息PendingIntent
//                PendingIntent deliverPI = PendingIntent.getBroadcast(mContext,0,itDeliver,0);
                if (simInfoAnother != null) {
                    SmsManager smsManager = SmsManager.getSmsManagerForSubscriptionId(simInfoAnother.getSubscriptionId());
                    if (message != null && message.length() > 70) {
                        ArrayList<String> msgs = smsManager.divideMessage(message);
                        ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();

                        for (int i = 0; i < msgs.size(); i++) {
                            sentIntents.add(sendPI);
                        }
                        smsManager.sendMultipartTextMessage(sender, null, msgs, sentIntents, null);
                    } else {
                        smsManager.sendTextMessage(sender, null, message, sendPI, null);
                    }
                }
            }
        }
    }


    //判断是否是双卡
    public static boolean isDoubleSim(Context mContext) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            SubscriptionManager manager = SubscriptionManager.from(mContext);
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
            int count = manager.getActiveSubscriptionInfoCount();
            if (count == 2) {
                return true;
            }
        }
        return false;
    }

    //通过卡槽id获取sim卡的信息0代码卡槽1，1代表卡槽2
    public static String getSlotIdInfo(Context mContext, int slotId) {
        String info = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            SubscriptionManager manager = SubscriptionManager.from(mContext);
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return "";
            }
            SubscriptionInfo subInfo = manager.getActiveSubscriptionInfoForSimSlotIndex(slotId);
            if (subInfo != null) {
                info = subInfo.getCarrierName().toString();
            }
        }
        return info;
    }

    //判断手机中是否装了双卡
    public static boolean isHasDoubleSim(Context mContext) {
        try {
            if (isDoubleSim(mContext)) {
                List<ModelSlotAndSub> slotAndSubs = getModelSlot(mContext);
                if (slotAndSubs != null && slotAndSubs.size() == 2) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    //判断是否拥有该权限
    public static boolean IsHasPermission(Context mContext, String permission) {
        if (mContext != null) {
            if (ActivityCompat.checkSelfPermission(mContext, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        } else {
            return false;
        }
        return true;
    }


    //申请该权限
    public static void requestOnePermission(Activity activity, String permission, int permissionCode) {
        if (activity != null) {
            activity.requestPermissions(new String[]{permission}, permissionCode);
        }
    }


    //获取icc用来判断
    public static int getIcc(String iccid, List<ModelSlotAndSub> slotAndSubs) {
        int icc = 0;
        if (slotAndSubs != null && slotAndSubs.size() >= 2 && !TextUtils.isEmpty(iccid)) {
            if (iccid.startsWith(slotAndSubs.get(0).iccid)) {
                icc = 1;
            } else if (iccid.startsWith(slotAndSubs.get(1).iccid)) {
                icc = 2;
            } else {
                if (iccid.equals(slotAndSubs.get(0).subId)) {
                    icc = 1;
                } else if (iccid.equals(slotAndSubs.get(1).subId)) {
                    icc = 2;
                } else {
                    icc = 0;
                }
            }
        }
        return icc;
    }

    /**
     * 获取来自那张卡 即卡1 还是卡2
     *
     * @param mContext
     * @param subID
     * @return
     */
    public static int getSlot(Context mContext, String subID) {
        return getIcc(subID, getModelSlot(mContext));
    }

//    public static int saveConfig(Context mContext) {
//        JSONObject jsonObject = MicroPhotoContext.getJsonObject(mContext);
//        Field[] fields = masterConfig.getClass().getDeclaredFields();
//        for (Field field : fields) {
//                if (key.equalsIgnoreCase(field.getName()) && !key.equalsIgnoreCase(SmsTypeEnum.CFGFILE.value())) {
//                    if (value != null) {
//                        try {
//                            if (field.getType() == String.class) {
//                                field.set(masterConfig, value);
//                            } else if (field.getType() == int.class) {
//                                Integer num = StringUtils.convert2Int(value);
//                                if (num != null) {
//                                    field.set(masterConfig, num.intValue());
//                                }
//                            }
//                        } catch (IllegalAccessException e) {
//                        }
//                    }
//                }
//        }
//        MicroPhotoContext.saveMasterConfig(mContext, masterConfig);
//    }

    //获取对应的卡槽ID和iccID 关联
    private static List<ModelSlotAndSub> getModelSlot(Context mContext) {
        List<ModelSlotAndSub> data = new ArrayList<>();
        ModelSlotAndSub modelSlotAndSub = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            SubscriptionManager subscriptionManager = SubscriptionManager.from(mContext);
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                List<SubscriptionInfo> mSubcriptionInfos = subscriptionManager.getActiveSubscriptionInfoList();
                if (mSubcriptionInfos != null) {
                    for (int i = 0; i < mSubcriptionInfos.size(); i++) {
                        SubscriptionInfo info = mSubcriptionInfos.get(i);
                        if (info != null) {
                            modelSlotAndSub = new ModelSlotAndSub();
                            modelSlotAndSub.subId = info.getSubscriptionId() + "";
                            modelSlotAndSub.simSlot = info.getSimSlotIndex() + 1 + "";
                            modelSlotAndSub.iccid = info.getIccId();
                            data.add(modelSlotAndSub);
                        }
                    }
                    if (data != null && data.size() == 2) {
                        if (!TextUtils.isEmpty(data.get(0).simSlot) && !TextUtils.isEmpty(data.get(1).simSlot)) {
                            int simSlot1 = Integer.valueOf(data.get(0).simSlot);
                            int simSlot2 = Integer.valueOf(data.get(1).simSlot);
                            if (simSlot1 > simSlot2) {
                                ModelSlotAndSub modelSlotAndSub1 = data.get(1);
                                data.remove(data.get(1));
                                data.add(0, modelSlotAndSub1);
                            }
                        }
                    }
                }
            }
        }
        return data;
    }

}