<?php

namespace app\timetask\controller;

use app\common\controller\Api;
use think\Db;
use think\exception\HttpResponseException;

class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function get_history()
    {
        $client = new \GuzzleHttp\Client();
        $res = $client->request('GET', 'https://history.macaumarksix.com/history/macaujc2/y/2026');
        if ($res->getStatusCode() == 200) {
            try {
                $response = json_decode($res->getBody(), true);
                $data = $response['data'];
                foreach ($data as $item) {
                    $insert_data = [];
                    $insert_data['expect'] = $item['expect'];
                    $insert_data['openTime'] = $item['openTime'];
                    $openCode = explode(",", $item['openCode']);
                    $insert_data['num1'] = $openCode[0];
                    $insert_data['num2'] = $openCode[1];
                    $insert_data['num3'] = $openCode[2];
                    $insert_data['num4'] = $openCode[3];
                    $insert_data['num5'] = $openCode[4];
                    $insert_data['num6'] = $openCode[5];
                    $insert_data['num7'] = $openCode[6];
                    $exist = Db::name('history')->where('expect', $item['expect'])->find();
                    if (!$exist) {
                        Db::name('history')->insert($insert_data);
                    } else {
                        Db::name('history')->where('expect', $item['expect'])->update($insert_data);
                    }
                }
                $this->success('获取成功');
            } catch (HttpResponseException $e) {
                // 这是框架正常的响应异常，直接抛出让它继续执行
                throw $e;
            } catch (\Throwable $e) {
                // 捕获其他异常和错误
                $errorMsg = $e->getMessage() ?: get_class($e);
                $file = $e->getFile();
                $line = $e->getLine();
                \think\Log::write("get_history 异常: {$errorMsg} at {$file}:{$line}", 'error');
                $this->error('异常：' . $errorMsg . ' [' . $file . ':' . $line . ']');
            }


        } else {
            $this->error('获取失败');
        }


    }
}
