<?php
declare(strict_types=1);

/**
 * 数据单模型，对应 wash_sheet 表
 * 明细（wash_sheet_item）增删改时会回来调 touch()，把本表的更新时间同步刷新
 */
class WashSheet extends Model
{
    protected string $table = 'wash_sheet';
    protected string $key   = 'wash_sheet_id';

    /** 当前登录用户 ID，由 Action 层注入（Model 不读 SESSION），新增时用作"添加人"默认值 */
    private int $currentAdminId = 0;

    public function setCurrentAdminId(int $adminId): void
    {
        $this->currentAdminId = $adminId;
    }

    /**
     * 供数据单明细的"数据单"下拉选择用，显示成 "#单号 标题"
     */
    public function listAll(): array
    {
        $rows = $this->db->select($this->table, [
            'wash_sheet_id',
            'wash_sheet_title',
        ], ['ORDER' => ['wash_sheet_id' => 'DESC']]);

        foreach ($rows as &$row) {
            $row['wash_sheet_display'] = '#' . $row['wash_sheet_id'] . ' ' . $row['wash_sheet_title'];
        }

        return $rows;
    }

    /**
     * 按单号取一条数据单，找不到返回 null（明细页要用标题做表头和标签名）
     */
    public function find(int $sheetId): ?array
    {
        return $this->db->get($this->table, '*', [$this->key => $sheetId]) ?: null;
    }

    /**
     * 刷新指定数据单的更新时间，明细变更时由 WashSheetItem 调用
     */
    public function touch(int $sheetId): void
    {
        if ($sheetId <= 0) {
            return;
        }

        $this->db->update($this->table, [
            'wash_sheet_update_time' => date('Y-m-d H:i:s'),
        ], [$this->key => $sheetId]);
    }

    public function gridInsert(array $values): mixed
    {
        $this->stripReadOnly($values);

        if (empty($values['wash_sheet_lnk_admin_id']) && $this->currentAdminId > 0) {
            $values['wash_sheet_lnk_admin_id'] = $this->currentAdminId;
        }

        return parent::gridInsert($values);
    }

    public function gridUpdate(mixed $key, array $values): int
    {
        $this->stripReadOnly($values);

        return $values ? parent::gridUpdate($key, $values) : 0;
    }

    /**
     * 删除数据单时级联删掉它下面的明细，避免 wash_sheet_item 留下挂空单号的孤儿行
     */
    public function gridRemove(mixed $key): int
    {
        (new WashSheetItem($this->db))->removeBySheet((int) $key);

        return parent::gridRemove($key);
    }

    /**
     * 创建时间/更新时间由数据库维护，不接受前端提交的值
     */
    private function stripReadOnly(array &$values): void
    {
        unset($values['wash_sheet_create_time'], $values['wash_sheet_update_time']);
    }
}
