<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AIElement extends Model
{
    use HasFactory;

    protected $table = 'mp_ai_elements';

    protected $fillable = [
        'id',
        'task_id',
        'external_task_id',
        'task_status',
        'task_status_msg',
        'element_id',
        'element_name',
        'element_description',
        'reference_type',
        'element_image_list',
        'element_video_list',
        'element_voice_id',
        'element_voice_info',
        'tag_list',
        'owned_by',
        'status',
        'callback_url',
        'final_unit_deduction',
    ];

    protected $casts = [
        'element_image_list' => 'array',
        'element_video_list' => 'array',
        'element_voice_info' => 'array',
        'tag_list' => 'array',
    ];

    /**
     * 任务状态常量
     */
    const STATUS_SUBMITTED = 'submitted';
    const STATUS_PROCESSING = 'processing';
    const STATUS_SUCCEED = 'succeed';
    const STATUS_FAILED = 'failed';

    /**
     * 参考类型常量
     */
    const REFERENCE_TYPE_IMAGE = 'image_refer';
    const REFERENCE_TYPE_VIDEO = 'video_refer';

    /**
     * 主体状态常量
     */
    const ELEMENT_STATUS_SUCCEED = 'succeed';
    const ELEMENT_STATUS_DELETED = 'deleted';

    /**
     * 标签映射
     */
    const TAG_MAP = [
        'o_101' => '热梗',
        'o_102' => '人物',
        'o_103' => '动物',
        'o_104' => '道具',
        'o_105' => '服饰',
        'o_106' => '场景',
        'o_107' => '特效',
        'o_108' => '其他',
    ];

    /**
     * 获取标签名称
     */
    public function getTagNamesAttribute()
    {
        if (!$this->tag_list) {
            return [];
        }

        return collect($this->tag_list)->map(function ($tag) {
            return [
                'tag_id' => $tag['tag_id'],
                'tag_name' => self::TAG_MAP[$tag['tag_id']] ?? '未知',
            ];
        })->toArray();
    }

    /**
     * 是否为自定义主体
     */
    public function isCustomElement()
    {
        return $this->owned_by !== 'kling';
    }

    /**
     * 是否任务成功
     */
    public function isTaskSucceed()
    {
        return $this->task_status === self::STATUS_SUCCEED;
    }

    /**
     * 是否主体可用
     */
    public function isElementAvailable()
    {
        return $this->status === self::ELEMENT_STATUS_SUCCEED;
    }
}