package com.ym.zxhcsdk;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.webkit.WebSettings;

import androidx.core.app.ActivityCompat;

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

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

public class PhoneUtils {


    private static PhoneUtils instance = new PhoneUtils();

    public static PhoneUtils getInstance() {
        return instance;
    }

    /**
     * 获取设备AndroidID
     *
     * @return AndroidID
     */
    public String getAndroidID(Context context) {
        try {
            String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            if (androidId != null) {
                return androidId;
            } else {
                return "";
            }
        } catch (Exception e) {
            return UUID.randomUUID().toString();
        }
    }


    /**
     * 获取当前的运营商
     *
     * @param context
     * @return 运营商名字
     */
    public String getOperator(Context context) {
        String ProvidersName = "";
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String IMSI = "";
        try {
            IMSI = telephonyManager.getSubscriberId();
        } catch (SecurityException e) {
//                Toast.makeText(context, "请开启读取手机权限", Toast.LENGTH_SHORT).show()
            return "0";
        }

        if (IMSI != null) {
            if (IMSI.startsWith("46000") || IMSI.startsWith("46002") || IMSI.startsWith("46007")) {
                //                ProvidersName = "移动";
                ProvidersName = "1";
            } else if (IMSI.startsWith("46001") || IMSI.startsWith("46006")) {
                ProvidersName = "2";
                //                ProvidersName = "联通";
            } else if (IMSI.startsWith("46003")) {
                ProvidersName = "3";
                //                ProvidersName = "电信";
            }
            return ProvidersName;
        } else {
            return "0";
            //            return "没有获取到sim卡信息";
        }
    }

    public String getRealFilePath(Context context, Uri uri) {
        return "方法未实现";
    }


    /**
     * @Description: 获取屏幕的宽度
     * @param: context
     * @return: int
     */
    public int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 获取屏幕高度
     *
     * @param context
     * @return int
     */
    public int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 获取屏幕高度
     *
     * @param context
     * @return int
     */
    public int getScreenDpi(Context context) {
        return context.getResources().getDisplayMetrics().densityDpi;
    }

    /**
     * 获取屏幕尺寸
     *
     * @param context
     * @return int
     */
    public double getScreenSize(Activity context) {
        double mInch = 0;

        try {
            int realWidth = 0, realHeight = 0;
            Display display = context.getWindowManager().getDefaultDisplay();
            DisplayMetrics metrics = new DisplayMetrics();
            display.getMetrics(metrics);
            if (android.os.Build.VERSION.SDK_INT >= 17) {
                Point size = new Point();
                display.getRealSize(size);
                realWidth = size.x;
                realHeight = size.y;
            } else if (android.os.Build.VERSION.SDK_INT < 17
                    && android.os.Build.VERSION.SDK_INT >= 14) {
                Method mGetRawH = Display.class.getMethod("getRawHeight");
                Method mGetRawW = Display.class.getMethod("getRawWidth");
                realWidth = (Integer) mGetRawW.invoke(display);
                realHeight = (Integer) mGetRawH.invoke(display);
            } else {
                realWidth = metrics.widthPixels;
                realHeight = metrics.heightPixels;
            }
            mInch = formatDouble(Math.sqrt((realWidth / metrics.xdpi) * (realWidth / metrics.xdpi) + (realHeight / metrics.ydpi) * (realHeight / metrics.ydpi)), 1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mInch;
    }

    /**
     * Double类型保留指定位数的小数，返回double类型（四舍五入）
     * newScale 为指定的位数
     */
    private static double formatDouble(double d, int newScale) {
        BigDecimal bd = new BigDecimal(d);
        return bd.setScale(newScale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 获取屏幕分辨率
     *
     * @param context
     * @return int
     */
    public float getScreenDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }


    /**
     * 获取设备型号
     *
     * @return 设备型号
     */
    public String getModel() {
        String model = Build.MODEL;
        return model;
    }

    /**
     * 获取App版本码
     *
     * @return App版本码
     */
    public int getAppVersionCode(Context context) {
        PackageManager manager = context.getPackageManager();
        int code = 0;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            code = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 获取App版本号
     *
     * @return App版本号
     */
    public String getAppVersionName(Context context) {
        String versionName = null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (Exception e) {
            return "";
        }
        return versionName;
    }


    /**
     * 获取App包名
     *
     * @return App版本码
     */
    public String getAppPackage() {
        return HcAppliContext.get().getPackageName();
    }

    /**
     * 获取应用程序名称
     */
    public String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取IP地址
     * <p>
     * 需添加权限 `<uses-permission android:name="android.permission.INTERNET"/>`
     *
     * @param useIPv4 是否用IPv4
     * @return IP地址
     */
    public String getIPAddress(boolean useIPv4) {
        try {
            Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                if (ni.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress inetAddress = addresses.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String hostAddress = inetAddress.getHostAddress();
                        boolean isIPv4 = hostAddress.indexOf(':') < 0;
                        if (useIPv4) {
                            if (isIPv4) return hostAddress;
                        } else {
                            if (!isIPv4) {
                                int index = hostAddress.indexOf('%');
                                if (index < 0) {
                                    return hostAddress.toUpperCase();
                                } else {
                                    return hostAddress.substring(0, index).toUpperCase();
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public String getDeviceId(Context context) {
        return getMd5Value(getAndroidID(context) + getImei(context));
    }

    public String getMd5Value(String sSecret) {

        try {
            MessageDigest bmd5 = MessageDigest.getInstance("MD5");
            bmd5.update(sSecret.getBytes());
        } catch (NoSuchAlgorithmException e) {

        }

        return "";
    }

    public String getImei(Context context) {
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            return telephonyManager.getDeviceId();
        } catch (SecurityException e) {
//            Toast.makeText(context, "请开启读取手机权限", Toast.LENGTH_SHORT).show()
            // In some devices, we are not able to get device id, and may cause some exception,
            // so catch it.
            return "";
        }
    }

    public String getMac(Context context) {
        String strMac = "";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            strMac = getLocalMacAddressFromWifiInfo(context);
            return strMac;
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            strMac = getMacAddress(context);
            return strMac;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (!TextUtils.isEmpty(getMacAddress(context))) {
                strMac = getMacAddress(context);
                return strMac;
            } else if (!TextUtils.isEmpty(getMachineHardwareAddress())) {
                strMac = getMachineHardwareAddress();
                return strMac;
            } else {
                strMac = getLocalMacAddressFromBusybox();
                return strMac;
            }
        }
        return "";
    }

    public String getLocalMacAddressFromWifiInfo(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        String str = info.getMacAddress();
        if (str == null) {
            str = "";
        }
        return str;
    }

    public String getLocalMacAddressFromBusybox() {
        String result = "";
        String Mac = "";
        result = callCmd("busybox ifconfig", "HWaddr");
        // 如果返回的result == null，则说明网络不可取
        if (TextUtils.isEmpty(result)) {
            //            return "网络异常";
            return "";
        }
        // 对该行数据进行解析
        // 例如：eth0 Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67
        if (result.length() > 0 && result.contains("HWaddr")) {
            Mac = result.substring(result.indexOf("HWaddr") + 6, result.length() - 1);
            result = Mac;
        }
        return result;
    }

    private String callCmd(String cmd, String filter) {
        String result = "";
        String line = "";

        try {
            Process proc = Runtime.getRuntime().exec(cmd);
            InputStreamReader mInputStream = new InputStreamReader(proc.getInputStream());
            BufferedReader br = new BufferedReader(mInputStream);
            while ((line.equals(br.readLine())) && !line.contains(filter)) {
                result += line;
                if (TextUtils.isEmpty(result)) {
                    return "";
                }
            }
            result = line;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * android 7.0及以上 （2）扫描各个网络接口获取mac地址
     *
     */
    /**
     * 获取设备HardwareAddress地址
     *
     * @return
     */
    public String getMachineHardwareAddress() {
        Enumeration<NetworkInterface> interfaces = null;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        String hardWareAddress = "";
        NetworkInterface iF = null;
        if (interfaces == null) {
            return "";
        }

        while (interfaces.hasMoreElements()) {
            iF = interfaces.nextElement();
            try {
                hardWareAddress = bytesToString(iF.getHardwareAddress());
                if (hardWareAddress != null)
                    break;
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
        return hardWareAddress;
    }

    /***
     * byte转为String
     *
     * @param bytes
     * @return
     */
    private String bytesToString(byte[] bytes) {
        if (bytes == null || bytes.length <= 0) {
            return "";
        }
        StringBuilder buf = new StringBuilder();
        for (byte b : bytes) {
            buf.append(String.format("%02X:", b));
        }
        if (buf.length() > 0) {
            buf.deleteCharAt(buf.length() - 1);
        }
        return buf.toString();
    }

    private String getMacAddress(Context context) {
        // 如果是6.0以下，直接通过wifimanager获取
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            String macAddress0 = getMacAddress0(context);
            if (!TextUtils.isEmpty(macAddress0)) {
                return macAddress0;
            }
        }
        String str = "";
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address"
            );
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            while (null != str) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();
                    break;
                }
            }
        } catch (Exception ex) {

        }
        if (macSerial == null || "" == macSerial) {
            try {
                String loadFileAsString = loadFileAsString("/sys/class/net/eth0/address");
                if (!TextUtils.isEmpty(loadFileAsString) && loadFileAsString.length() > 17) {
                    return loadFileAsString.toUpperCase().substring(0, 17);
                } else {
                    return loadFileAsString.toUpperCase();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return macSerial;
    }

    private String getMacAddress0(Context context) {
        if (isAccessWifiStateAuthorized(context)) {
            WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = null;
            try {
                wifiInfo = wifiMgr.getConnectionInfo();
                return wifiInfo.getMacAddress();
            } catch (Exception e) {

            }
        }
        return "";
    }

    /**
     * Check whether accessing wifi state is permitted
     *
     * @param context
     * @return
     */
    private boolean isAccessWifiStateAuthorized(Context context) {
        if (PackageManager.PERMISSION_GRANTED == context
                .checkCallingOrSelfPermission("android.permission.ACCESS_WIFI_STATE")
        ) {
            return true;
        } else
            return false;
    }

    private String loadFileAsString(String fileName) {
        try {
            FileReader reader = new FileReader(fileName);
            String text = loadReaderAsString(reader);
            reader.close();
            return text;
        } catch (Exception e) {
            return "";
        }
    }

    private String loadReaderAsString(Reader reader) throws IOException {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }

    /**
     * 获取当前网络类型
     * <p>
     * 需添加权限 `<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>`
     *
     * @return 网络类型
     */

    private enum NetworkType {
        NETWORK_WIFI,
        NETWORK_4G,
        NETWORK_3G,
        NETWORK_2G,
        NETWORK_UNKNOWN,
        NETWORK_NO
    }

    public String getNetwork(Context context) {
        String s = "";
        switch (getNetworkType(context)) {
            case NETWORK_2G:
                s = "2";
                break;
            case NETWORK_3G:
                s = "3";
                break;
            case NETWORK_4G:
                s = "4";
                break;
            case NETWORK_WIFI:
                s = "1";
                break;
            default:
                s = "5";
                break;
        }
        return s;
    }

    public NetworkType getNetworkType(Context context) {
        NetworkType netType = NetworkType.NETWORK_NO;
        NetworkInfo info = getActiveNetworkInfo(context);
        if (info != null && info.isAvailable()) {
            if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                netType = NetworkType.NETWORK_WIFI;
            } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                switch (info.getSubtype()) {
                    case TelephonyManager.NETWORK_TYPE_GSM:
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN:
                        netType = NetworkType.NETWORK_2G;
                        break;
                    case TelephonyManager.NETWORK_TYPE_TD_SCDMA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    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:
                        netType = NetworkType.NETWORK_3G;
                        break;
                    case TelephonyManager.NETWORK_TYPE_IWLAN:
                    case TelephonyManager.NETWORK_TYPE_LTE:
                        netType = NetworkType.NETWORK_4G;
                        break;
                    default:
                        String subtypeName = info.getSubtypeName();
                        if (subtypeName.equalsIgnoreCase("TD-SCDMA")
                                || subtypeName.equalsIgnoreCase("WCDMA")
                                || subtypeName.equalsIgnoreCase("CDMA2000")
                        ) {
                            netType = NetworkType.NETWORK_3G;
                        } else {
                            netType = NetworkType.NETWORK_UNKNOWN;
                        }
                        break;
                }
            } else {
                netType = NetworkType.NETWORK_UNKNOWN;
            }
        }
        return netType;
    }


    /**
     * 获取活动网络信息
     * <p>
     * 需添加权限 `<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>`
     *
     * @return NetworkInfo
     */
    @SuppressLint("MissingPermission")
    private NetworkInfo getActiveNetworkInfo(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            return manager.getActiveNetworkInfo();
        } catch (Exception e) {
            return null;
        }
    }

    private String buildMap(Map<String, String> map) {
        StringBuffer sb = new StringBuffer();
        if (map.size() > 0) {
            for (String key : map.keySet()) {
                sb.append(key + "=");
                if (TextUtils.isEmpty(map.get(key))) {
                    sb.append("&");
                } else {
                    String value = map.get(key);
                    try {
                        value = URLEncoder.encode(value, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    sb.append(value + "&");
                }
            }
        }
        return sb.toString();
    }

    @SuppressLint("MissingPermission")
    private String getBSSID(Context context) {
        WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
        String s = "";
        if (mWifiInfo != null) {
            s = mWifiInfo.getBSSID();
        }
        return s;
    }

    /**
     * 获取手机IMSI号
     */
    @SuppressLint("MissingPermission")
    public String getIMSI(Context context) {
        try {
            TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            return mTelephonyMgr.getSubscriberId();
        } catch (Exception e) {
            return "";
        }
    }

    public String getUserAgent(Context context) {
        String userAgent = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                userAgent = WebSettings.getDefaultUserAgent(context);
            } catch (Exception e) {
                userAgent = System.getProperty("http.agent");
            }
        } else {
            userAgent = System.getProperty("http.agent");
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public String getLocationInfo(Context context, int type) {
        //type =1 经度  2 纬度  3 城市
        String locationProvider;
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            // 如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            // 如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else {
//            Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
            return "";
        }
        // 获取Location
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return "";
        }
        Location location = locationManager.getLastKnownLocation(locationProvider);
        if (location != null) {
            // 不为空,显示地理位置经纬度
            if (type == 1) {
                return location.getLongitude() + "";
            } else if (type == 2) {
                return location.getLatitude() + "";
            } else if (type == 3) {
                List<Address> result = null;
                try {
                    if (location != null) {
                        Geocoder gc = new Geocoder(context, Locale.getDefault());
                        result = gc.getFromLocation(location.getLatitude(),
                                location.getLongitude(), 1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (result != null && result.size() > 0) {
                    return result.get(0).getLocality();
                } else {
                    return "";
                }
            }
        } else {
            //ToastUtils.showToast(this, "GPS未定位到位置");
        }
        return "";
    }

    public void setOaid(String oaid) {
        ZXHCConstant.device_oaid = oaid;
    }

    public String getoaid() {
        return ZXHCConstant.device_oaid;
    }

    public boolean IsInstallApp(Context context, String pkgName) {
        if (pkgName == null || pkgName.isEmpty()) {
            return false;
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;//true为安装了，false为未安装
        }
    }


    public HcAdBean jsonToObj(String jsonString) {
        HcAdBean adBean = null;
        try {
            JSONObject root = new JSONObject(jsonString);
            adBean = new HcAdBean();
            adBean.setHeight(root.optInt("height"));
            adBean.setWidth(root.optInt("width"));
            //曝光
            JSONArray monitorUrl = root.optJSONArray("monitorUrl");
            List<String> monitorList = new ArrayList<String>();
            if (monitorUrl != null) {
                for (int i = 0; i < monitorUrl.length(); i++) {
                    monitorList.add(monitorUrl.optString(i));
                }
            }
            adBean.setMonitorUrl(monitorList);

            //点击
            JSONArray clickUrl = root.optJSONArray("clickUrl");
            List<String> clickList = new ArrayList<String>();
            if (clickUrl != null) {
                for (int i = 0; i < clickUrl.length(); i++) {
                    clickList.add(clickUrl.optString(i));
                }
            }
            adBean.setClickUrl(clickList);
            //图片
            JSONArray srcUrl = root.optJSONArray("srcUrls");
            List<String> srcList = new ArrayList<String>();
            if (srcUrl != null) {
                for (int i = 0; i < srcUrl.length(); i++) {
                    srcList.add(srcUrl.optString(i));
                }
            }
            adBean.setSrcUrls(srcList);
            //落地页
            JSONArray dUrl = root.optJSONArray("dUrl");
            List<String> dList = new ArrayList<String>();
            if (dUrl != null) {
                for (int i = 0; i < dUrl.length(); i++) {
                    dList.add(dUrl.optString(i));
                }
            }
            adBean.setDUrl(dList);

            adBean.setPid(root.optString("pid"));
            adBean.setCid(root.optInt("cid"));
            adBean.setPlan_id(root.optInt("plan_id"));
            adBean.setTarget_type(root.optString("target_type"));
            adBean.setAd_show_type(root.optInt("ad_show_type"));
            adBean.setFrom(root.optString("from"));
            adBean.setReq_id(root.optString("req_id"));

            adBean.setApp_name(root.optString("app_name"));
            adBean.setPackage_name(root.optString("package_name"));
            adBean.setDown_url(root.optString("down_url"));
            adBean.setTitle(root.optString("title"));
            adBean.setContent(root.optString("content"));
            adBean.setDeeplink(root.optString("deeplink"));


            JSONArray startInstallmonitorUrl = root.optJSONArray("startInstallmonitorUrls");
            List<String> startInstallmonitorUrlList = new ArrayList<String>();
            if (startInstallmonitorUrl != null) {
                for (int i = 0; i < startInstallmonitorUrl.length(); i++) {
                    startInstallmonitorUrlList.add(startInstallmonitorUrl.optString(i));
                }
            }
            adBean.setStartInstallmonitorUrls(startInstallmonitorUrlList);

            JSONArray finishInstallmonitorUrl = root.optJSONArray("finishInstallmonitorUrls");
            List<String> finishInstallmonitorList = new ArrayList<String>();
            if (finishInstallmonitorUrl != null) {
                for (int i = 0; i < finishInstallmonitorUrl.length(); i++) {
                    finishInstallmonitorList.add(finishInstallmonitorUrl.optString(i));
                }
            }
            adBean.setFinishInstallmonitorUrls(finishInstallmonitorList);


            JSONArray startdownloadmonitorUrl = root.optJSONArray("startdownloadmonitorUrls");
            List<String> startInstallmonitorList = new ArrayList<String>();
            if (startdownloadmonitorUrl != null) {
                for (int i = 0; i < startdownloadmonitorUrl.length(); i++) {
                    startInstallmonitorList.add(startdownloadmonitorUrl.optString(i));
                }
            }
            adBean.setStartdownloadmonitorUrls(startInstallmonitorList);

            JSONArray finishdownloadmonitorUrl = root.optJSONArray("finishdownloadmonitorUrls");
            List<String> finishdownloadmonitorlList = new ArrayList<String>();
            if (finishdownloadmonitorUrl != null) {
                for (int i = 0; i < finishdownloadmonitorUrl.length(); i++) {
                    finishdownloadmonitorlList.add(finishdownloadmonitorUrl.optString(i));
                }
            }
            adBean.setFinishdownloadmonitorUrls(finishdownloadmonitorlList);

            JSONArray activemonitorUrl = root.optJSONArray("activemonitorUrls");
            List<String> activemonitorList = new ArrayList<String>();
            if (activemonitorUrl != null) {
                for (int i = 0; i < activemonitorUrl.length(); i++) {
                    activemonitorList.add(activemonitorUrl.optString(i));
                }
            }
            adBean.setActivemonitorUrls(activemonitorList);

            JSONArray dpSuccmonitorUrl = root.optJSONArray("dpSuccmonitorUrls");
            List<String> dpSuccmonitorList = new ArrayList<String>();
            if (dpSuccmonitorUrl != null) {
                for (int i = 0; i < dpSuccmonitorUrl.length(); i++) {
                    dpSuccmonitorList.add(dpSuccmonitorUrl.optString(i));
                }
            }
            adBean.setDpSuccmonitorUrls(dpSuccmonitorList);

            JSONArray dpFailmonitorUrl = root.optJSONArray("dpFailmonitorUrls");
            List<String> dpFailmonitorList = new ArrayList<String>();
            if (dpFailmonitorUrl != null) {
                for (int i = 0; i < dpFailmonitorUrl.length(); i++) {
                    dpFailmonitorList.add(dpFailmonitorUrl.optString(i));
                }
            }
            adBean.setDpFailmonitorUrls(dpFailmonitorList);

            //Video
            adBean.setVideo_duration(root.optInt("video_duration"));
            adBean.setVideo_url(root.optString("video_url"));
            adBean.setVideo_cover_image(root.optString("video_cover_image"));
            adBean.setVideo_end_image(root.optString("video_end_image"));
            adBean.setVideo_endpage_html(root.optString("video_endpage_html"));
            adBean.setVideo_endbuttonurl(root.optString("video_endbuttonurl"));
            adBean.setVideo_icon_url(root.optString("video_icon_url"));
            adBean.setVideo_title(root.optString("video_title"));
            adBean.setVideo_desc(root.optString("video_desc"));
            adBean.setVideo_iconbuttontext(root.optString("video_iconbuttontext"));

            JSONArray video_start = root.optJSONArray("video_start");
            List<String> video_startList = new ArrayList<String>();
            if (video_start != null) {
                for (int i = 0; i < video_start.length(); i++) {
                    video_startList.add(video_start.optString(i));
                }
            }
            adBean.setVideo_start(video_startList);

            JSONArray video_one_quarter = root.optJSONArray("video_one_quarter");
            List<String> video_one_quarterList = new ArrayList<String>();
            if (video_one_quarter != null) {
                for (int i = 0; i < video_one_quarter.length(); i++) {
                    video_one_quarterList.add(video_one_quarter.optString(i));
                }
            }
            adBean.setVideo_one_quarter(video_one_quarterList);

            JSONArray video_one_half = root.optJSONArray("video_one_half");
            List<String> video_one_halfList = new ArrayList<String>();
            if (video_one_half != null) {
                for (int i = 0; i < video_one_half.length(); i++) {
                    video_one_quarterList.add(video_one_half.optString(i));
                }
            }
            adBean.setVideo_one_half(video_one_halfList);

            JSONArray video_three_quarter = root.optJSONArray("video_three_quarter");
            List<String> video_three_quarterList = new ArrayList<String>();
            if (video_three_quarter != null) {
                for (int i = 0; i < video_three_quarter.length(); i++) {
                    video_three_quarterList.add(video_three_quarter.optString(i));
                }
            }
            adBean.setVideo_three_quarter(video_three_quarterList);

            JSONArray video_complete = root.optJSONArray("video_complete");
            List<String> video_completeList = new ArrayList<String>();
            if (video_complete != null) {
                for (int i = 0; i < video_complete.length(); i++) {
                    video_completeList.add(video_complete.optString(i));
                }
            }
            adBean.setVideo_complete(video_completeList);

            JSONArray video_pause = root.optJSONArray("video_pause");
            List<String> video_pauseList = new ArrayList<String>();
            if (video_pause != null) {
                for (int i = 0; i < video_pause.length(); i++) {
                    video_pauseList.add(video_pause.optString(i));
                }
            }
            adBean.setVideo_pause(video_pauseList);

            JSONArray video_resume = root.optJSONArray("video_resume");
            List<String> video_resumeList = new ArrayList<String>();
            if (video_resume != null) {
                for (int i = 0; i < video_resume.length(); i++) {
                    video_resumeList.add(video_resume.optString(i));
                }
            }
            adBean.setVideo_resume(video_resumeList);

            JSONArray video_skip = root.optJSONArray("video_skip");
            List<String> video_skipList = new ArrayList<String>();
            if (video_skip != null) {
                for (int i = 0; i < video_skip.length(); i++) {
                    video_skipList.add(video_skip.optString(i));
                }
            }
            adBean.setVideo_skip(video_skipList);

            JSONArray video_close = root.optJSONArray("video_close");
            List<String> video_closeList = new ArrayList<String>();
            if (video_close != null) {
                for (int i = 0; i < video_close.length(); i++) {
                    video_closeList.add(video_close.optString(i));
                }
            }
            adBean.setVideo_close(video_closeList);


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

        return adBean;
    }


}
