/**
   * 下载一个任务
   *
   * @param url
   * @param listener
   */
  public void addTask(String url, DownloadListener listener) {
    if (StringUtils.isEmpty(url)) {
      Logger.d("download url null");
      return;
    }

    DownloadInfo downloadInfo = new DownloadInfo();
    downloadInfo.setUrl(url);
    if (!hasTask(url)) {
      downloadInfo.setTargetFolder(mTargetFolder);
      try {
        mDbHelper.save(downloadInfo);
      } catch (DbException e) {
        Logger.e(e);
      }

      if (mDownloadingTasks.size() < MAX_DOWNLOAD_COUNT) {
        downloadInfo.setState(DownloadInfo.DOWNLOADING);
        mDownloadingTasks.add(downloadInfo);
        DownloadHttpTask task =
            new DownloadHttpTask(downloadInfo, mDownloadUIHandler, mDbHelper, this);
        mDownloadingTaskMap.put(url, task);
        task.start();
      } else { // 加入等待队列
        downloadInfo.setState(DownloadInfo.WAIT);
        boolean b = mWaitTasks.offer(downloadInfo);
        if (b) {
          addTaskListener(url, listener);
        }
      }
      mAllTasks.add(downloadInfo);
    } else {
      Logger.d("任务已存在");
    }
  }
  @Override
  public void nextTask() {
    synchronized (mNextTaskLockObj) {
      if (!mNextTaskLock) {
        mNextTaskLock = true;
        // TODO mDownloadingTasks 同步状态(临时解决方案)
        synchronized (mIteratorLock) {
          Iterator<DownloadInfo> downloadingIt = mDownloadingTasks.iterator();
          while (downloadingIt.hasNext()) {
            DownloadInfo b = downloadingIt.next();
            if (b.getState() == DownloadInfo.PAUSE) {
              mPausingTasks.add(b);
              try {
                downloadingIt.remove();
              } catch (Exception e) {
                Logger.e(e);
              }
            } else if (b.getState() == DownloadInfo.COMPLETE) {
              mCompleteTasks.add(b);
              try {
                downloadingIt.remove();
              } catch (Exception e) {
                Logger.e(e);
              }
            }
          }
        }
        synchronized (mIteratorLock) {
          Iterator<Map.Entry<String, DownloadHttpTask>> downloadinMapIt =
              mDownloadingTaskMap.entrySet().iterator();
          while (downloadinMapIt.hasNext()) {
            Map.Entry<String, DownloadHttpTask> entry = downloadinMapIt.next();
            DownloadHttpTask task = entry.getValue();
            if (task != null && task.isInterrupt()) {
              try {
                downloadinMapIt.remove();
              } catch (Exception e) {
                Logger.e(e);
              }
            }
          }
        }

        executeNextTask();
        mNextTaskLock = false;
      }
    }
  }
  private DbHelper createDownloadDb(Context context) {
    try {
      DbHelper.DaoConfig config = new DbHelper.DaoConfig(context);
      config.setDbName("download.db");
      config.setDbVersion(1);
      DbHelper dbHelper = DbHelper.create(config);
      return dbHelper;
    } catch (Exception e) {
      Logger.e(e);
    }

    return null;
  }
 private void executeNextTask() {
   if (mDownloadingTasks.size() < MAX_DOWNLOAD_COUNT) {
     if (mWaitTasks.size() > 0) {
       DownloadInfo downloadInfo = mWaitTasks.poll();
       if (downloadInfo != null) {
         String url = downloadInfo.getUrl();
         downloadInfo.setState(DownloadInfo.DOWNLOADING);
         DownloadHttpTask task =
             new DownloadHttpTask(downloadInfo, mDownloadUIHandler, mDbHelper, this);
         mDownloadingTaskMap.put(url, task);
         task.start();
       }
     }
   } else {
     Logger.d("已达到最大下载数量:" + mDownloadingTasks.size());
   }
 }
  public DownloadManager(Context context) {

    mAllTasks = Collections.synchronizedList(new ArrayList());
    mDownloadingTasks = Collections.synchronizedList(new ArrayList());
    mPausingTasks = Collections.synchronizedList(new ArrayList());
    mCompleteTasks = Collections.synchronizedList(new ArrayList());
    mWaitTasks = new ConcurrentLinkedQueue<>();
    mDownloadingTaskMap = Collections.synchronizedMap(new HashMap<String, DownloadHttpTask>());
    mListenerListMap = Collections.synchronizedMap(new HashMap<String, List<DownloadListener>>());
    mDownloadUIHandler = new DownloadUIHandler(mListenerListMap);

    // 初始化目标Download保存目录
    String folder =
        StorageUtils.getCacheDirectory(context).getAbsolutePath() + Constants.DM_TARGET_FOLDER;
    if (!new File(folder).exists()) {
      FileUtils.makeFolders(folder);
    }
    mTargetFolder = folder;

    // 构建下载Downlaod DbHelper
    mDbHelper = createDownloadDb(context);
    // 获取所有任务
    if (mDbHelper != null) {
      try {
        List<DownloadInfo> list = mDbHelper.findAll(DownloadInfo.class);
        if (list != null && list.size() > 0) {

          for (DownloadInfo info : list) {
            if (info.getProgress() == 100) {
              info.setState(DownloadInfo.COMPLETE);
              mCompleteTasks.add(info);
            } else {
              info.setState(DownloadInfo.PAUSE);
              mPausingTasks.add(info);
            }
          }

          mAllTasks.addAll(mPausingTasks);
          mAllTasks.addAll(mCompleteTasks);
        }
      } catch (DbException e) {
        Logger.e(e);
      }
    }
  }
 private synchronized void removeDownloadingMap(String url) {
   synchronized (mIteratorLock) {
     Iterator<Map.Entry<String, DownloadHttpTask>> it = mDownloadingTaskMap.entrySet().iterator();
     while (it.hasNext()) {
       Map.Entry<String, DownloadHttpTask> entry = it.next();
       String key = entry.getKey();
       DownloadHttpTask task = entry.getValue();
       if (TextUtils.equals(key, url)) {
         if (task != null) {
           task.setInterrupt(true);
         }
         try {
           it.remove();
         } catch (Exception e) {
           Logger.e(e);
         }
         break;
       }
     }
   }
 }
  /**
   * 删除任务
   *
   * @param url
   */
  public void deleteTask(String url) {
    // 从等待队列和下载中
    stopTask(url, true);
    // 从已暂停队列移除
    Iterator<DownloadInfo> pausingIt = mPausingTasks.iterator();
    synchronized (mIteratorLock) {
      while (pausingIt.hasNext()) {
        DownloadInfo bean = pausingIt.next();
        if (TextUtils.equals(bean.getUrl(), url)) {
          bean.setState(DownloadInfo.PAUSE);
          pausingIt.remove();
          break;
        }
      }
    }

    // 从完成队列移除
    Iterator<DownloadInfo> completeIt = mCompleteTasks.iterator();
    synchronized (mIteratorLock) {
      while (completeIt.hasNext()) {
        DownloadInfo bean = completeIt.next();
        if (TextUtils.equals(bean.getUrl(), url)) {
          bean.setState(DownloadInfo.PAUSE);
          completeIt.remove();
          break;
        }
      }
    }

    synchronized (mIteratorLock) {
      String filePath = "";
      // 所有任务
      Iterator<DownloadInfo> allTaskIt = mAllTasks.iterator();
      while (allTaskIt.hasNext()) {
        DownloadInfo bean = allTaskIt.next();
        if (TextUtils.equals(bean.getUrl(), url)) {
          bean.setState(DownloadInfo.PAUSE);
          filePath = bean.getTargetPath();
          allTaskIt.remove();
          break;
        }
      }

      if (!StringUtils.isEmpty(filePath)) {
        FileUtils.deleteFile(filePath);
      }
    }

    synchronized (mIteratorLock) {
      // 任务时间回调
      for (Map.Entry<String, List<DownloadListener>> entry : mListenerListMap.entrySet()) {
        List<DownloadListener> listenerList = entry.getValue();
        if (listenerList != null) {
          listenerList.clear();
          listenerList = null;
        }
      }
    }

    // 清除数据库
    try {
      mDbHelper.delete(DownloadInfo.class, WhereBuilder.b("url", "=", url));
    } catch (DbException e) {
      Logger.e(e);
    }
  }