<?php

namespace Workerman\Lib;

use Workerman\Worker;

$bot_loop = new Worker();
$bot_loop->count = 1;
$bot_loop->name = 'ComboChange';
function ComboChange($db, $table_name, $task, $content)
{
  /*** status
   * 1-待执行
   * 2-执行中
   * 3-已完成
   * 4-执行报错
   * 5-已删除
   */
  Tool::log("任务进度[999/100]", 2);

  $message = '处理完成';
  Tool::log("{$message}[{$task['id']}]", 2);
  Db2::u($db, $table_name, [
    'message' => $message,
    'status' => 3,
  ], 'where id = ?', [$task['id']]);
}

function ComboChangeFunc()
{
  $db = Db::get();
  $table_name = 'bot_task';
  $task = $db->getRow("select * from $table_name where status = ? or status = ? order by id asc", [1, 2]);
  if (!!$task) {
    Tool::log("检测到任务[{$task['id']}]", 2);
    if (strtotime($task['create_time']) - time() < 60 * 60 * 24 * 3) {
      $message = '文件超时';
      Tool::log("{$message}[{$task['id']}]", 5);
      Db2::u($db, $table_name, [
        'message' => $message,
        'status' => 4,
      ], 'where id = ?', [$task['id']]);
    } else {
      Db2::u($db, $table_name, [
        'start_time' => date('Y-m-d H:i:s'),
        'status' => 2,
      ], 'where id = ?', [$task['id']]);
    }
    if (!!is_file($task['path'])) {
      $file_content = file_get_contents($task['path']);
      if (!!json_decode($file_content, true)) {
        ComboChange($db, $table_name, $task, json_decode($file_content, true));
      } else {
        $message = '解析JSON失败';
        Tool::log("{$message}[{$task['id']}]", 5);
        Db2::u($db, $table_name, [
          'message' => $message,
          'status' => 4,
        ], 'where id = ?', [$task['id']]);
      }
    } else {
      $message = '文件不存在';
      Tool::log("{$message}[{$task['id']}]", 5);
      Db2::u($db, $table_name, [
        'message' => $message,
        'status' => 4,
      ], 'where id = ?', [$task['id']]);
    }
  } else {
    Tool::log('未检测到任务');
  }
}

$bot_loop->onWorkerStart = function () {
  ComboChangeFunc();
  Timer::add(10, function () {
    ComboChangeFunc();
  });
};
