<?php

namespace App\Servers;

use App\Models\DrugReportInfo;
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 HistoryDrugReportService
{
    public function syncDrugReport(string $startTime, string $endTime = '', int $page = 1, int $pageSize = 20, $lastTime=0): int
    {

        $total = 0;

        $QueryDrugReportService = new QueryDrugReportService();
        $DrugReportAss          = new DrugReportAss();
        do {
            try {
                // 分批次拉取数据
                $data = $QueryDrugReportService->drugReportOptHistory($startTime, $endTime, $page, $pageSize);
                $total_num = $data['total_num'];
                $data = $data['data'];
                if (empty($data)) {
                    break;
                }
                var_dump($total_num,$startTime, $endTime, $page);
                $queryAssData           = [];
                foreach ($data as $item){
                    if ($lastTime <= strtotime($item['opt_time'])){
                        $reportAssList  = $DrugReportAss->where([
                            'batch_no' => $item['batch_no'],
                            'drug_id' => $item['drug_id'],
                        ])->get(['id', 'batch_no', 'drug_id', 'bill_code', 'bill_detail_id', 'crt_date']);
                        foreach ($reportAssList as $info){
                            $assBeginTime          = date('Y-m-d H:i:s',($info['crt_date'] - 10));
                            $assEndTime            = date('Y-m-d H:i:s',($info['crt_date'] + 10));
                            $queryAssList       = $QueryDrugReportService->querydrugreportass($assBeginTime, $assEndTime, $page, $pageSize, 0,'1', $info['bill_code'], $info['batch_no'], $info['drug_id']);
                            if ($queryAssList['total_num'] > 0) {
                                $queryAssData[]   = $queryAssList['data'][0];
                            }
                            sleep(1);
                        }
                    }

                }
                // 处理并保存数据
                $saveCount = $this->saveDrugReport($queryAssData);
                Log::info('drug-report-history','成功同步更新：'.$saveCount);
                $total += $saveCount;
                // 检查是否还有更多数据
                if (count($data) <> $pageSize) {
                    break;
                }

                $page++;

            } catch (\Exception $e) {
                Log::info('drug-report-history','操作历史同步错误', ['err'=>$e->getMessage()]);
                break;
            }
        } while (true);

        return $total;
    }
    /**
     * 处理并保存批次数据
     * @param string $source
     * @param array $data
     * @return int
     */
    protected function saveDrugReport(array $data): int
    {
        try {
            $SyncDrugReportService = new SyncDrugReportService();
            $data   =  $SyncDrugReportService->correctDrugReportAss($data);
            return DrugReportAss::bulkUpsert($data);
        } catch (\Throwable $e) {
            Log::info('history_drug_report', '处理数据异常', ['data'=>$data, 'err'=>$e->getMessage()]);
            return 0;
        }
    }
}
