<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Spatie\Activitylog\Models\Activity;

class ActivityLogExport implements FromQuery, WithHeadings, WithMapping, WithStyles
{
    protected $query;

    public function __construct($query)
    {
        $this->query = $query;
    }

    /**
     * 查询数据
     */
    public function query()
    {
        return $this->query;
    }

    /**
     * 表头
     */
    public function headings(): array
    {
        return [
            '操作时间',
            '操作用户',
            '操作类型',
            '对象类型',
            '对象ID',
            '日志名称',
            '变更详情',
        ];
    }

    /**
     * 数据映射
     */
    public function map($activity): array
    {
        // 格式化操作类型
        $description = match ($activity->description) {
            'created' => '创建',
            'updated' => '更新',
            'deleted' => '删除',
            default => $activity->description,
        };

        // 格式化对象类型
        $subjectType = '-';
        if ($activity->subject_type) {
            $className = class_basename($activity->subject_type);
            $subjectType = match ($className) {
                'SystemSetting' => '系统设置',
                'User' => '用户',
                'Document' => '文档',
                'Group' => '分组',
                'Terminal' => '终端',
                'Guide' => '操作指引',
                default => $className,
            };
        }

        // 格式化变更详情
        $changes = '';
        if (is_array($activity->properties)) {
            $changesArray = [];
            if (isset($activity->properties['attributes'])) {
                $changesArray[] = '新值: ' . json_encode($activity->properties['attributes'], JSON_UNESCAPED_UNICODE);
            }
            if (isset($activity->properties['old'])) {
                $changesArray[] = '旧值: ' . json_encode($activity->properties['old'], JSON_UNESCAPED_UNICODE);
            }
            $changes = implode(' | ', $changesArray);
        }

        return [
            $activity->created_at->format('Y-m-d H:i:s'),
            $activity->causer?->name ?? '系统',
            $description,
            $subjectType,
            $activity->subject_id ?? '-',
            $activity->log_name ?? 'default',
            $changes,
        ];
    }

    /**
     * 样式设置
     */
    public function styles(Worksheet $sheet)
    {
        return [
            // 表头样式
            1 => [
                'font' => ['bold' => true],
                'fill' => [
                    'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                    'startColor' => ['rgb' => 'E2E8F0'],
                ],
            ],
        ];
    }
}
