<?php

namespace App\Servers;

use App\Models\DrugReportAss;
use App\Servers\Aliyun\Oss;
use App\Servers\QueryDrugReportService;
use Carbon\Carbon;
use App\Facades\Servers\Logs\Log;

use GuzzleHttp\Client;

class UpdateDrugReportService
{
    public function syncDrugReport(string $startTime, string $endTime = '', int $page = 1, int $pageSize = 20)
    {

        $total = 0;
        $count  = 0;
        $time  = time();
        $QueryDrugReportService = new QueryDrugReportService();
        $DrugReportAss          = new DrugReportAss();
        do {
            try {
                // 分批次拉取数据
                $data = $QueryDrugReportService->querydrugreportass($startTime, $endTime, $page, $pageSize);
                sleep(1);
                $count = $data['total_num'];
                $data = $data['data'];
                if (empty($data)) {
                    break;
                }
                var_dump($startTime, $endTime, $page);
                foreach ($data as $item){
                    $info  = $DrugReportAss->where([
                        'batch_no' => $item['produce_batch_no'],
                        'drug_id' => $item['drug_id'],
                        'bill_detail_id' => $item['bill_detail_id'],
                        'bill_id' => $item['bill_id'],
                    ])->first();
                    if (!$info){
                        continue;
                    }
                    if ( (int)$item['drug_report_sign_status'] != $info['drug_report_sign_status']){
                        $updateData = [
                            'drug_report_sign_status'=>$item['drug_report_sign_status'],
                            'seal_status'=>$item['seal_status'],
                            'update_time'=>$time
                        ];
                        if(!$info['seal_report_url']){
                            if (!empty($item['sealed_report_url'])) {
                                $fileName = $item['physic_name'] . '_' . str_replace('/', '', $item['pkg_spec']) . '_' . $item['produce_batch_no'];
                                $fileName               = uniqid($fileName.'_').'.pdf';
                                try {
                                    //上传报告pdf到oss
                                    $Oss = new Oss();
                                    $client = new Client(); // GuzzleHttp的客户端实例
                                    $response = $client->get($item['sealed_report_url']); // 下载文件
                                    $body = $response->getBody(); // 获取响应体
                                    $content = (string)$body; // 转换为字符串内容
                                    // 上传文件到OSS
                                    $ossPath = 'path/' . date('Y') . '/' . date('m') . '/' . $fileName;
                                    $res = $Oss->putObject($ossPath, $content);
                                    $updateData['seal_report_url'] = $res;
                                    $updateData['report_name'] = $fileName;
                                } catch (\Throwable $th) {
                                    var_dump('上传oss报表失败:' . $th->getMessage());
                                    Log::error('syncDrug/oss', '上传oss报表失败:' . $th->getMessage(), $item);
                                }
                            }
                        }
                        $res  = $DrugReportAss->where([
                            'batch_no' => $item['produce_batch_no'],
                            'drug_id' => $item['drug_id'],
                            'bill_detail_id' => $item['bill_detail_id'],
                            'bill_id' => $item['bill_id'],
                        ])->update($updateData);
                        if (!$res){
                            var_dump('更新单据失败：'.$res);
                            Log::info('update-drug-report-ass','更新单据失败', ['res'=>$res,'item'=>$item]);
                        }else{
                            Log::info('update-drug-report-ass','更新成功', ['res'=>$res,'data'=>$updateData]);
                            $total++;
                        }
                    }
                }
                // 检查是否还有更多数据
                if (count($data) <> $pageSize) {
                    break;
                }
                $page++;
                sleep(1);

            } catch (\Exception $e) {
                var_dump($e->getMessage());
                Log::info('update-drug-report-ass','更新单据错误', ['err'=>$e->getMessage()]);
                break;
            }
        } while (true);

        return ['total' => $total, 'count' => $count];
    }
}
