package com.sunzee.service;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hboxs.serialport.SerialPortSendQueue;
import com.hboxs.serialport.frame.ReadCommandFrame;
import com.hboxs.serialport.frame.ResponseFrame;
import com.hboxs.serialport.message.Message;
import com.hboxs.serialport.util.AsciiUtils;
import com.orhanobut.hawk.Hawk;
import com.sunzee.R;
import com.sunzee.base.BaseApplication;
import com.sunzee.db.WarringBeanDao;
import com.sunzee.model.Heartbeat;
import com.sunzee.model.HttpResult;
import com.sunzee.model.domain.AddAlarmRecordBean;
import com.sunzee.model.domain.ErrorBean;
import com.sunzee.model.domain.GetAdBean;
import com.sunzee.model.domain.HeartbeatBean;
import com.sunzee.model.domain.Name;
import com.sunzee.model.domain.TimeRuleBean;
import com.sunzee.model.domain.WarringBean;
import com.sunzee.model.message.ApiMessageEvent;
import com.sunzee.model.message.DownLoadMessageEvent;
import com.sunzee.receiver.Alarmreceiver;
import com.sunzee.retrofit.ApiCallback;
import com.sunzee.retrofit.ApiClient;
import com.sunzee.retrofit.ApiStores;
import com.sunzee.ui.dialog.WarringDialog;
import com.sunzee.utils.FileUtil;
import com.sunzee.utils.HexadecimalUtil;
import com.sunzee.utils.SharedPreferencesUtils;
import com.sunzee.utils.TimeUtil;
import com.sunzee.utils.ToastUtil;
import com.sunzee.utils.UiUtil;
import com.wuxiaolong.androidutils.library.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
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.Timer;
import java.util.TimerTask;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;

public class MyService extends Service {
    private static final String TAG = "MyService";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "MyServiceonCreate: ");
        EventBus.getDefault().register(this);
        // setError( UiUtil.getStringRes(R.string.warring_lutoujiare), true);

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: 开始心跳3");
        Bundle extras = null;
        if (intent != null) {
            extras = intent.getExtras();
        }

        if (extras != null) {

            int heartbeat = extras.getInt("heartbeat");
            if (heartbeat == 3) {
                stopHeartbeat();
                Log.w(TAG, "onStartCommand: 开始心跳" + heartbeat);
                Log.e(TAG, "onStartCommand: 开始心跳1");
                startHeartbeat();
            }
            int first = extras.getInt("first");
            if (first == 4) {
                //第一次启动心跳
                checkHeartData();
            }
        }
        //进程保活相关
        flags = START_STICKY;

        //启用前台服务，主要是startForeground()
        String ns = Context.NOTIFICATION_SERVICE;

        //获得通知管理器
        NotificationManager manager1 = (NotificationManager) getSystemService(ns);

        Notification.Builder builder = new Notification.Builder(getApplicationContext());
        builder.setSmallIcon(R.drawable.login_logo);
        builder.setTicker("服务正在运行");
        builder.setContentTitle("服务正在运行");
        builder.setContentText("服务正在运行");
        builder.setWhen(System.currentTimeMillis()); //设置时间
        Notification notification = builder.build();

        //定义通知行为
        manager1.notify(0, notification);

        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        //读者可以修改此处的Minutes从而改变提醒间隔时间
        //此处是设置每隔55分钟启动一次
        //这是55分钟的毫秒数
        int Minutes = 55 * 60 * 1000;
        //SystemClock.elapsedRealtime()表示1970年1月1日0点至今所经历的时间
        long triggerAtTime = SystemClock.elapsedRealtime() + Minutes;
        //此处设置开启AlarmReceiver这个Service
        Intent i = new Intent(this, Alarmreceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        //ELAPSED_REALTIME_WAKEUP表示让定时任务的出发时间从系统开机算起，并且会唤醒CPU。
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        if (warringDialog == null) {
            warringBeanDao = BaseApplication.getInstances().getDaoSession().getWarringBeanDao();
        }
        startRead();
        return super.onStartCommand(intent, flags, startId);
        //进程保活相关
        //return START_STICKY ;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //------------------------------------------------------------------------心跳 start---------------------------------
    private Timer timerHeartbeat;
    private TimerTask taskHeartbeat;

    /**
     * 开始心跳
     */
    private void startHeartbeat() {
        Log.e(TAG, "startHeartbeat: 开始心跳");
        timerHeartbeat = new Timer();
        taskHeartbeat = new TimerTask() {
            @Override
            public void run() {
                //经纬度不为0
                //系统管理不为空
                String managerId = (String) SharedPreferencesUtils.getParam(Name.SYSTEM_ID, "");
                if (managerId != null && !TextUtils.isEmpty(managerId)) {
                    sendHeart();
                }
            }
        };
        timerHeartbeat.schedule(taskHeartbeat, 1000, 1000 * 60 * 5);
    }

    /**
     * 发送心跳
     */
    private void sendHeart() {
        Heartbeat.managerId = (String) SharedPreferencesUtils.getParam(Name.SYSTEM_ID, "");
        Heartbeat.lastUpdateTime = TimeUtil.getStrCurTime();
        HeartbeatBean heartbeatBean = new HeartbeatBean();
        heartbeatBean.setCabinetHd(Heartbeat.cabinetHd);
        heartbeatBean.setCabinetTm(Heartbeat.cabinetTm);
        heartbeatBean.setFurnaceSp("0");
        heartbeatBean.setFurnaceTm(Heartbeat.furnaceTm);
        heartbeatBean.setLastUpdateTime(Heartbeat.lastUpdateTime);
        heartbeatBean.setLatitude(Heartbeat.latitude);
        heartbeatBean.setLongitude(Heartbeat.longitude);
        heartbeatBean.setManagerId(Heartbeat.managerId);
        heartbeatBean.setOdorConcentration(Heartbeat.odorConcentration);
        heartbeatBean.setCleaner(Heartbeat.cleaner);
        heartbeatBean.setDisinfectant(Heartbeat.disinfectant);
        heartbeatBean.setPeopleCounting(Heartbeat.peopleCounting);
        int netType = (int) SharedPreferencesUtils.getParam(Name.NET_TYPE, -1);
        if (netType == 0) {
            Heartbeat.netWorkingMode = "4g";
        } else if (netType == 1) {
            Heartbeat.netWorkingMode = "wifi";
        } else {
            Heartbeat.netWorkingMode = "no";
        }
        heartbeatBean.setNetWorkingMode(Heartbeat.netWorkingMode);
        heartbeatBean.setGtClientId(Heartbeat.clientId);
        heartbeatBean.setClientId(Heartbeat.deviceId);
        Gson gson = new Gson();
        String json = gson.toJson(heartbeatBean);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=utf-8"), json);
        addSubscription(apiStores.heart(body), new ApiCallback<HttpResult<String>>() {
            @Override
            public void onSuccess(HttpResult<String> model) {
                Log.d(TAG, "heartonSuccess: " + model);
            }

            @Override
            public void onFailure(String msg) {
                Log.d(TAG, "heartononFailure: " + msg);
            }

            @Override
            public void onFinish() {

            }
        });
    }


    /**
     * 检测心跳数据以及开始心跳
     */
    private void checkHeartData() {
        //系统管理不为空
        Heartbeat.managerId = (String) SharedPreferencesUtils.getParam(Name.SYSTEM_ID, "");
        if (Heartbeat.managerId != null && !TextUtils.isEmpty(Heartbeat.managerId)) {
            Log.e(TAG, "checkHeartData: 开始心跳2");
            startHeartbeat();
            LogUtil.i(TAG + "系统管理id为" + Heartbeat.managerId);
        } else {
            LogUtil.i(TAG + "系统管理id为空");
        }
    }

    /**
     * 停止心跳
     */
    private void stopHeartbeat() {
        if (timerHeartbeat != null) {
            taskHeartbeat.cancel();
            timerHeartbeat.cancel();
            timerHeartbeat = null;
        }
    }
    //------------------------------------------------------------------------心跳 end---------------------------------

    //——-----------------------------------------------------------------------请求 start------------------------------
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(ApiMessageEvent messageEvent) {
        switch (messageEvent.getName()) {
            case "statusType1":
                //同步数据
                //showSyncDialog();
                break;
            case "DOWNKOADADCID":
                //上传设备id,返回该id的的广告资源
                Log.d(TAG, "event: DOWNKOADADCID");
                downAdvertising((String) messageEvent.getData());
                break;
            case "startClean":
                Log.d(TAG, "onReceive:闹钟响了26 " + messageEvent.getData());
                //开始清洗。全蹲位。
                break;
            default:
                break;

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(DownLoadMessageEvent messageEvent) {
        switch (messageEvent.getType()) {
            case success:
                //先下载B屏广告 再下载A屏广告 然后窗口消失
                //下载成功
                ToastUtil.showToast("下载成功");
                Log.e(TAG, "event: 下载成功" + messageEvent.getData() + "index=" + currentIndex + " size-1=" + (getAdBeansBackup.size() - 1) + "  size" + getAdBeansBackup.size());
                //只下载公司宣传视频
                if (messageEvent.getScreenType() == 0) {
                    if (currentIndex == corporationAdBeans.size() - 1) {
                        Log.e(TAG, "event: A屏下载完成");
                        //B屏广告下完
//                        if (syncDialog != null) {
//                            syncDialog.setAdState(R.string.sync_success);
////                            syncDialog.dismiss();
//                        }
//不同的 删除本地文件(旧广告)
                        for (int i = 0; i < allFileA.size(); i++) {
                            File file = allFileA.get(i);
                            if (file != null && file.exists()) {
                                Log.e(TAG, "onNext:删除的A屏广告 " + file.getName());
                                file.delete();

                            }
                        }
                        getAdRuleId("1");
                        Hawk.put("showAdA", getAdBeansA);
                        Log.d(TAG, "GTIntentService:getAdBeansA2 " + getAdBeansA);
                        //推送给购买页和制作页更新
                        EventBus.getDefault().post(new DownLoadMessageEvent(DownLoadMessageEvent.Type.downloadAll, "", -1));
                        return;
                    }


                } else if (messageEvent.getScreenType() == 1) {
                    //B屏最后一个下载完 保存数据
                    if (currentIndex == getAdBeansBackup.size() - 1) {
                        currentIndex = 0;
                        Hawk.put("showAd", getAdBeans);
                        //全部默认显示 添加数据
                        for (int i = 0; i < getAdBeans.size(); i++) {
                            GetAdBean getAdBean = getAdBeans.get(i);
                            if (getAdBean.getLocationType().equals("棉花糖宣传广告")) {
                                showSugar.put(i, getAdBean);
                            }
                            if (getAdBean.getLocationType().equals("外接广告")) {
                                showOut.put(i, getAdBean);
                            }
                        }
                        Log.d(TAG, "event: " + getAdBeans);
                        Hawk.put("show_sugar", showSugar);
                        Hawk.put("show_out", showOut);
                        Log.d(TAG, "synAdSuccess:保存完成广告数据4" + getAdBeans.size());
                        SharedPreferencesUtils.setParam(Name.SYSTEM_ID, Heartbeat.managerId);
                        SharedPreferencesUtils.setParam(Name.CONNECT_STATE, 2);
                        //不同的 删除本地文件(旧广告)
                        for (int i = 0; i < allFile.size(); i++) {
                            File file = allFile.get(i);
                            if (file != null && file.exists()) {
                                Log.e(TAG, "onNext:删除的B屏广告 " + file.getName());
                                file.delete();

                            }
                        }
                        //开始下载公司宣传视频
                        currentIndex = 0;
                        downLoadFile(currentIndex, "", corporationAdBeans);
                        getAdBeansBackup.clear();
                        return;
                    }

                }
                if (messageEvent.getScreenType() == 1) {
                    //开始下载B屏广告
                    Log.e(TAG, "event: 开始下载B屏广告");
                    currentIndex++;//下载成功一个
                    if (currentIndex < getAdBeansBackup.size()) {
                        downLoadFile(currentIndex, getAdBeansBackup.get(currentIndex).getAdType(), getAdBeansBackup);
                    }
                } else if (messageEvent.getScreenType() == 0) {
                    //开始下载A屏广告
                    Log.e(TAG, "event: 开始下载A屏广告");
                    currentIndex++;//下载成功一个
                    if (currentIndex < corporationAdBeans.size()) {
                        downLoadFile(currentIndex, corporationAdBeans.get(currentIndex).getAdType(), corporationAdBeans);
                    }
                }

                break;
            case failed:
                //下载失败
                ToastUtil.showToast("下载失败" + messageEvent.getData());
                Log.d(TAG, "event: 下载失败" + messageEvent.getData());
                String strCurTime = TimeUtil.getStrCurTime();
                Map<String, String> parms = new HashMap();
                parms.put("clientId", Heartbeat.deviceId);
                parms.put("pushUpdateTime", strCurTime);
                addSubscription(apiStores.pushTimeUpdate(parms), new ApiCallback<HttpResult<String>>() {
                    @Override
                    public void onSuccess(HttpResult<String> model) {
                        Log.e(TAG, "onNext: 上传失败成功 ");
                    }

                    @Override
                    public void onFailure(String msg) {

                    }

                    @Override
                    public void onFinish() {

                    }
                });
                break;
            default:
                break;

        }
    }
    //——-----------------------------------------------------------------------请求 end------------------------------

    //_------------------------------------------------------------------------广告 start---------------------------------
    //要显示的棉花糖广告<index,name>
    private Map<Integer, GetAdBean> showSugar;
    //要显示的外接广告<index,name>
    private Map<Integer, GetAdBean> showOut;
    //显示的数据
    private ArrayList<GetAdBean> getAdBeans;
    private ArrayList<GetAdBean> getAdBeansA;
    //用于下载
    private ArrayList<GetAdBean> getAdBeansBackup;
    //公司宣传广告
    private ArrayList<GetAdBean> corporationAdBeans;
    //当前下载的索引
    private static int currentIndex;
    //下载成功后要删除的文件
    private ArrayList<File> allFile;
    private ArrayList<File> allFileA;

    /**
     * 上传设备id,返回该id的的广告资源
     *
     * @param s 要播放的数据
     */
    private void downAdvertising(String s) {
        showSugar = Hawk.get("show_sugar", new HashMap<Integer, GetAdBean>());
        showOut = Hawk.get("show_out", new HashMap<Integer, GetAdBean>());
        getAdBeans = new ArrayList<>();
        getAdBeansA = new ArrayList<>();
        getAdBeansBackup = new ArrayList<>();
        Gson gson = new Gson();
        //广告实体
        getAdBeans = gson.fromJson(s, new TypeToken<List<GetAdBean>>() {
        }.getType());
        getAdBeansBackup.addAll(getAdBeans);
        //只有公司宣传广告
        corporationAdBeans = new ArrayList<>();
        List<GetAdBean> indexList = new ArrayList<>();
        for (int i = 0; i < getAdBeansBackup.size(); i++) {
            if (getAdBeansBackup.get(i).getScreenType() == 0) {
                corporationAdBeans.add(getAdBeansBackup.get(i));
                indexList.add(getAdBeansBackup.get(i));
            }
        }
        for (int i = 0; i < indexList.size(); i++) {
            getAdBeansBackup.remove(indexList.get(i));
            getAdBeans.remove(indexList.get(i));
        }
        getAdBeansA.addAll(corporationAdBeans);
        currentIndex = 0;
        //全部默认显示 添加数据
        for (int i = 0; i < getAdBeansBackup.size(); i++) {
            showSugar.put(i, getAdBeansBackup.get(i));
            showOut.put(i, getAdBeansBackup.get(i));
        }
//        Hawk.put("show_sugar", showSugar);
//        Hawk.put("show_out", showOut);

        getFilesDir();
        LogUtil.d(TAG, "initView: " + getFilesDir().getName());
        //本地的所有广告数据

        File externalFilesDir = BaseApplication.getContext().getExternalFilesDir("");
        if (externalFilesDir == null) {
            externalFilesDir.mkdir();
        }
        if (!externalFilesDir.exists()) {
            externalFilesDir.mkdirs();
        }
        //1 本地的所有广告数据
        File[] allFiles = FileUtil.getAllFiles(Environment.getExternalStorageDirectory().getPath() + "/rightvideoimg/", "");
        //A屏
        File[] allFilesA = FileUtil.getAllFiles(Environment.getExternalStorageDirectory().getPath() + "/leftvideoimg/", "");
        allFile = new ArrayList<>();
        allFileA = new ArrayList<>();
        List<File> files = Arrays.asList(allFilesA);
        allFileA.addAll(files);
        if (allFiles != null && allFiles.length >= 0) {

            for (int i = 0; i < allFiles.length; i++) {
                allFile.add(allFiles[i]);
            }
        }

        //备份一个list用于删除
        //另外一个用于显示
        //相同 不下载（删除一个实体） 不删除本地文件

        ArrayList<File> unDeleteFiles = new ArrayList<>();
        if (allFiles != null) {
            for (int i = 0; i < allFiles.length; i++) {
                File file = allFiles[i];
                String name = allFiles[i].getName();
                LogUtil.d(TAG, "onNext: 本地的所有文件：" + name);
                for (int j = 0; j < getAdBeansBackup.size(); j++) {
                    GetAdBean getAdBean = getAdBeansBackup.get(j);
                    String id = getAdBean.getId();
                    //前缀名
                    String caselsh = name.substring(0, name.lastIndexOf("."));
                    if (id.equals(caselsh)) {
                        //相同的删除url 不下载
                        LogUtil.e(TAG, "onNext不下载的文件: " + name);
//                                        timeDatas.remove(j);
                        getAdBeansBackup.remove(j);
                        //记住不删除的文件
                        unDeleteFiles.add(file);
                    }
                }

            }

            for (int i = 0; i < unDeleteFiles.size(); i++) {
                LogUtil.e(TAG, "onNext: unDeleteFiles name=" + unDeleteFiles.get(i).getName());
            }


            //只剩下删除的文件
            allFile.removeAll(unDeleteFiles);
        }

        ArrayList<File> unDeleteFilesA = new ArrayList<>();
        if (allFilesA != null) {
            for (int i = 0; i < allFilesA.length; i++) {
                File file = allFilesA[i];
                String name = allFilesA[i].getName();
                LogUtil.e(TAG, "onNext: A屏本地的所有文件：" + name);
                //时间，用于判断唯一
                //跟网络数据进行对比 如果id一样的不进行下载
                for (int j = 0; j < corporationAdBeans.size(); j++) {
                    GetAdBean getAdBean = corporationAdBeans.get(j);
                    String id = getAdBean.getId();
                    //前缀名
                    String caselsh = name.substring(0, name.lastIndexOf("."));
                    if (id.equals(caselsh)) {
                        //相同的删除url 不下载
                        LogUtil.e(TAG, "onNext不下载的文件: " + name);
                        corporationAdBeans.remove(j);
                        //记住不删除的文件
                        unDeleteFilesA.add(file);
                    }
                }
            }
            //只剩下删除的文件
            allFileA.removeAll(unDeleteFilesA);
        }

        //3 下载数据
        if (getAdBeansBackup.size() <= 0) {
            LogUtil.e(TAG, "onNext: 推送过来的B屏数据相同，不下载");
            Hawk.put("showAd", getAdBeans);
            //全部默认显示 添加数据
            for (int i = 0; i < getAdBeans.size(); i++) {
                showSugar.put(i, getAdBeans.get(i));
                showOut.put(i, getAdBeans.get(i));
            }
            Log.d(TAG, "event: " + getAdBeans);
            Hawk.put("show_sugar", showSugar);
            Hawk.put("show_out", showOut);
            LogUtil.d(TAG, "synAdSuccess:保存完成广告数据3" + getAdBeans.size());
            SharedPreferencesUtils.setParam(Name.SYSTEM_ID, Heartbeat.managerId);
            SharedPreferencesUtils.setParam(Name.CONNECT_STATE, 2);
            //todo
//                            if (syncDialog != null) {
//                                syncDiaLogUtil.setAdState(R.string.sync_success);
//                                syncDiaLogUtil.dismiss();
//                            }
            if (corporationAdBeans.size() <= 0) {
                LogUtil.e(TAG, "onNext: 推送过来的A屏数据相同，不下载");
                Hawk.put("showAdA", getAdBeansA);
                Log.d(TAG, "GTIntentService:getAdBeansA 1" + getAdBeansA);
                //todo
//                if (syncDialog != null) {
//                    syncDiaLogUtil.setAdState(R.string.sync_success);
//                    getAdRuleId("1");
//                }
            } else {
                downLoadFile(0, "", corporationAdBeans);
            }
            return;
        }
        downLoadFile(currentIndex, "", getAdBeansBackup);
        //开始下载
        LogUtil.e(TAG, "synProductSuccess:同步广告管理成功 ");
        LogUtil.e(TAG, "synProductSuccess:全部同步成功 ");
    }

    private CompositeDisposable mDisposables;
    protected ApiStores apiStores = ApiClient.retrofit().create(ApiStores.class);

    protected void addSubscription(Observable observable, DisposableObserver observer) {
        if (mDisposables == null) {
            mDisposables = new CompositeDisposable();
        }
        observable
                .unsubscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
        mDisposables.add(observer);
    }

    /**
     * 保存广告id
     */
    private void getAdRuleId(String id) {


        Map<String, String> params = new HashMap<>();
        params.put("clientId", Heartbeat.deviceId);

        addSubscription(apiStores.synTimeRule(params), new ApiCallback<HttpResult<String>>() {
            @Override
            public void onSuccess(HttpResult<String> model) {
                saveAdRules(model.getData());
            }

            @Override
            public void onFailure(String msg) {

            }

            @Override
            public void onFinish() {

            }
        });


    }

    /**
     * 保存广告id
     */
    private void saveAdRules(String id) {
        LogUtil.d(TAG, "ad_id ->" + id);
        Long lid = Long.valueOf(id);
        Map<String, Long> params = new HashMap<>();
        params.put("id", lid);
        addSubscription(apiStores.getTimeRule(params), new ApiCallback<HttpResult<String>>() {

            @Override
            public void onSuccess(HttpResult<String> rule) {
                //广告数据
                ArrayList<GetAdBean> adBeans = Hawk.get("showAd", new ArrayList<GetAdBean>());
                Gson gson = new Gson();
                List<TimeRuleBean> list = gson.fromJson(rule.getData(), new TypeToken<List<TimeRuleBean>>() {
                }.getType());
                //每个id对应的时间数
                Map<String, String> adRulesMap = new HashMap<>();
                for (int i = 0; i < adBeans.size(); i++) {
                    GetAdBean getAdBean = adBeans.get(i);
                    StringBuilder sb = new StringBuilder();
                    for (int j = 0; j < list.size(); j++) {
                        //每个规则里对应的广告
                        List<String> ad = list.get(j).getAd();
                        for (int k = 0; k < ad.size(); k++) {
                            if (ad.get(k).equals(getAdBean.getId())) {
                                sb.append(list.get(j).getTime() + "、");
                            }
                        }
                    }
                    if (sb.length() > 0) {
                        sb.deleteCharAt(sb.length() - 1);
                    }

                    Log.e(TAG, "onNext: " + "ad_id=" + getAdBean.getId() + " rules=" + sb.toString());
                    adRulesMap.put(getAdBean.getId(), sb.toString());
                }
                //保存对应的id对应的广告规则
                Hawk.put("ad_rules_map", adRulesMap);

//                if (syncDialog != null) {
//                    syncDialog.setAdRuleState(R.string.sync_success);
//                    syncDialog.dismiss();
//                }
            }

            @Override
            public void onFailure(String msg) {

            }

            @Override
            public void onFinish() {

            }
        });
    }

    /**
     * 下载文件
     *
     * @param index 下载索引 第几个
     * @param type  没有
     * @param datas 要下载数据列表
     */
    private void downLoadFile(int index, String type, ArrayList<GetAdBean> datas) {
        //开始下载
        Intent downloadApkIntent = new Intent(getApplicationContext(), DownServer.class);
        Bundle bundle = new Bundle();
        if (datas.size() <= 0) {
            return;
        }
        GetAdBean getAdBean = datas.get(index);
        String url = getAdBean.getUrl();
        if (TextUtils.isEmpty(url)) {
            //todo
//            if (syncDialog != null) {
//                syncDialog.setAdState(R.string.synchroniz_fail);
//                syncDialog.dismiss();
//            }
            ToastUtil.showToast(UiUtil.getStringRes(R.string.synchroniz_fail));
            return;
        }
        String type1 = url.substring(url.lastIndexOf(".") + 1);
        bundle.putString("downloadUrl", url);
        bundle.putString("download_name", getAdBean.getName());
        String time = TimeUtil.getNoTime(getAdBean.getCreateDate());
        Log.d(TAG, "downLoadFile: time=" + time);
        bundle.putString("title", getAdBean.getId());
        Log.d(TAG, "downLoadFile: 开始下载" + getAdBean.getId());
        bundle.putString("downloadtype", type1);
        bundle.putInt("scrrentype", getAdBean.getScreenType());
        downloadApkIntent.putExtra("download", bundle);
        getApplicationContext().startService(downloadApkIntent);

    }
    //------------------------------------------------------------------------广告 end---------------------------------

    //-----------------------------------------------------------------------报警 start---------------------------------
    private Timer timerM600;
    private TimerTask taskM600;

    /**
     * 开始读取报警
     */
    private void startRead() {
        SerialPortSendQueue.clear();
        timerM600 = new Timer();
        taskM600 = new TimerTask() {
            @Override
            public void run() {
                SerialPortSendQueue.sendCommand(new ReadCommandFrame("M600", 8), 600, "M600");
            }
        };
        timerM600.schedule(taskM600, 0, 1000);
    }

    /**
     * 停止读取报警
     */
    private void stopRead() {
        if (timerM600 != null) {
            taskM600.cancel();
            timerM600.cancel();
            timerM600 = null;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(Message messageEvent) {
        switch (messageEvent.getType()) {
            case connected:
                break;
            case sendError:
                break;
            case ack:
                break;
            case nak:
                break;
            case disconnected:
                ToastUtil.showToast(messageEvent.getContent().toString());
                break;
            case response:
                ResponseFrame responseFrame = (ResponseFrame) messageEvent.getContent();
                if (responseFrame.isValidSum()) {
                    //通过校验
                    //1 获取本地存储的报警记录
                    //2 将本地的报警记录进行对比
                    //3 若没有的进行添加以及上传 没有的不管他
                    //4 最好走完将他覆盖
                    if (messageEvent.getName().equals("M600")) {
                        try {
                            String result = AsciiUtils.asciiByteArray2HexStr(responseFrame.getData());
                            Log.d(TAG, "resultM600=" + result + ";name" + messageEvent.getName());
                            List<String> strList = HexadecimalUtil.getStrList(result, 4);
                            if (result.length() != 16) {
                                return;
                            }
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0, len = strList.size(); i < len; i++) {
                                String list = strList.get(i);
                                String s1 = HexadecimalUtil.hexStringToByte(list);
                                String s2 = HexadecimalUtil.flipString(s1, 8);
                                sb.append(s2);
                            }
                            String s1 = sb.toString();
                            List<String> lis = Arrays.asList(s1.split(""));
                            ArrayList<String> list = new ArrayList(lis);
                            list.remove(0);
                            Log.d(TAG, "listevent: " + list);
                            showErrorDialog(list);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                }
        }
    }

    private boolean isOpenReadWarring = true;
    private List<String> errorListM600;
    //前进阻碍
    private boolean isadvance;
    //下降阻碍
    private boolean isdecline;

    private void showErrorDialog(ArrayList<String> list) {
        String json = (String) SharedPreferencesUtils.getParam("error_list_M600", "");
        Gson gson = new Gson();
        errorListM600 = gson.fromJson(json, new TypeToken<List<String>>() {
        }.getType());
        if (errorListM600 == null) {
            errorListM600 = new ArrayList<>();
        }

        ArrayList<String> errorList1 = new ArrayList<>();
        if (list.get(0).equals("1")) {
            //M600
            if (!isadvance) {
                showDialog(R.string.warring_forward_obstaclesM600);
                setError(0, UiUtil.getStringRes(R.string.warring_forward_obstaclesM600), errorList1, errorListM600, true);
                isadvance = true;
            }
        } else if (list.get(0).equals("0")) {
            //警告解除 弹窗消失
            if (isadvance) {
                if (warringDialog != null) {
                    warringDialog.dismiss();
                    isadvance = false;
                    //延迟三秒再设置。
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            SharedPreferencesUtils.setParam("isOpenReadWarring", true);
                        }
                    }, 3000);
                }
            }
        }
        if (list.get(1).equals("1")) {
            if (!isdecline) {
                //M601
                showDialog(R.string.warring_falling_blockM601);
                setError(1, UiUtil.getStringRes(R.string.warring_falling_blockM601), errorList1, errorListM600, true);
                isdecline = true;
            }
        } else if (list.get(1).equals("0")) {
            //警告解除 弹窗消失
            if (isdecline) {
                if (warringDialog != null) {
                    warringDialog.dismiss();
                    isdecline = false;
                    //延迟三秒再设置。
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            SharedPreferencesUtils.setParam("isOpenReadWarring", true);
                        }
                    }, 3000);

                }
            }
        }

        if (list.get(2).equals("1")) {
            //M602
            boolean isOpenReadWarring = (boolean) SharedPreferencesUtils.getParam("isOpenReadWarring", true);
            if (isOpenReadWarring) {
                showDialog(R.string.warring_x_axis_stepM602);
                setError(2, UiUtil.getStringRes(R.string.warring_x_axis_stepM602), errorList1, errorListM600, false);
            }
        }
        if (list.get(3).equals("1")) {
            //M603
            boolean isOpenReadWarring = (boolean) SharedPreferencesUtils.getParam("isOpenReadWarring", true);
            if (isOpenReadWarring) {
                showDialog(R.string.warring_y_axis_stepM603);
                setError(3, UiUtil.getStringRes(R.string.warring_y_axis_stepM603), errorList1, errorListM600, false);
            }
        }

        String s = gson.toJson(errorList1);
        SharedPreferencesUtils.setParam("error_list_M600", s);
    }

    private WarringDialog warringDialog;

    private void showDialog(int strId) {
        SharedPreferencesUtils.setParam("isOpenReadWarring", false);
        isOpenReadWarring = (boolean) SharedPreferencesUtils.getParam("isOpenReadWarring", true);
        if (warringDialog == null) {
            warringDialog = new WarringDialog(this);
        }
        warringDialog.setTvContent(strId);
        warringDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        if (!warringDialog.isShowing()) {
            warringDialog.show();
        }


    }

    private WarringBeanDao warringBeanDao;

    /**
     * @param key
     * @param reason
     * @param errorList1 新建的
     * @param errorListM 存在本地的
     */
    public void setError(int key, String reason, ArrayList<String> errorList1, List<String> errorListM, boolean isM660) {
        long date = System.currentTimeMillis();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(date);
        String time = formatter.format(curDate);
        ErrorBean errorBean = new ErrorBean();
        errorBean.setTime(time);
        errorBean.setThingError(reason);
        errorBean.setRemark("");

        AddAlarmRecordBean addAlarmRecordBean = new AddAlarmRecordBean(reason, Heartbeat.deviceId, time, "");
        WarringBean warringBean = new WarringBean();
        warringBean.setTime(date);
        warringBean.setThingError(reason);
        warringBeanDao.insert(warringBean);
        errorList1.add(key + "");
        if (errorListM == null) {
            //只用于上传M666
            Log.d(TAG + "22", "setError: 上传");
            Gson gson = new Gson();
            String json = gson.toJson(addAlarmRecordBean);
            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), json);
//            //上传到服务器
            addSubscription(apiStores.addAlarmRecord(body), new ApiCallback<HttpResult<String>>() {
                @Override
                public void onSuccess(HttpResult<String> model) {
                    if (model.getData() != null) {
                        Log.d(TAG, "onSuccess: " + model);
                        Log.d("AddAlarmRecordApi", "onNext: " + model.getData());
                    }
                }

                @Override
                public void onFailure(String msg) {

                }

                @Override
                public void onFinish() {

                }
            });
            return;
        }
        if (!errorListM.contains(key + "")) {
            //不包含，上传
            Log.d(TAG + "22", "setError: 上传");

            Gson gson = new Gson();
            String json = gson.toJson(addAlarmRecordBean);

            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), json);

            //上传到服务器
            addSubscription(apiStores.addAlarmRecord(body), new ApiCallback<HttpResult<String>>() {
                @Override
                public void onSuccess(HttpResult<String> model) {
                    Log.d(TAG, "onSuccess: " + model);
                    if (model.getData() != null) {
                        Log.d("AddAlarmRecordApi", "onNext: " + model.getData());
                    }
                }

                @Override
                public void onFailure(String msg) {

                }

                @Override
                public void onFinish() {

                }
            });
        } else {
            Log.d(TAG + "22", "setError: 不上传");
        }
    }
    //-----------------------------------------------------------------------报警 end---------------------------------

}
