<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Facades\Servers\Encrypts\AccessToken;

class DrugReportInfo extends Model
{

    protected $table = 'drug_report_info';

    // 是否主动维护时间戳
    public $timestamps = false;
    protected $guarded = [];


    /**
     * 获取「是否签收」文本
     * @return string
     */
    public function getIsSignTextAttribute(): string
    {
        $options = [
            0 => '',
            1 => '未签收',
            2 => '已签收',
        ];
        return $options[$this->is_sign] ?? "未知「{$this->is_sign}」";
    }

    /**
     * 获取「是否盖章」文本
     * @return string
     */
    public function getIsSealTextAttribute(): string
    {
        $options = [
            0 => '',
            1 => '未盖章',
            2 => '已盖章',
        ];
        return $options[$this->is_sign] ?? "未知「{$this->is_sign}」";
    }

    /**
     * 批量更新或插入
     * @param array $data
     * @param array $uniqueKeys
     * @return int
     * @throws \Throwable
     */
    public static function bulkUpsert(array $data, array $uniqueKeys = ['report_id']): int
    {
        if (empty($data)) {
            return 0;
        }

        return DB::transaction(function () use ($data, $uniqueKeys) {
            $count = 0;
            foreach (array_chunk($data, 100) as $chunk) {
                self::upsert(
                    $chunk,
                    $uniqueKeys, // 组合唯一键
                    ['update_time','seal_report_url','report_name','is_seal'] // 要更新的字段
                );
                $count += count($chunk);
            }

            return $count;
        });
    }
}
