<?php

namespace App\Models;

use App\Models\traits\Filter;
use Illuminate\Support\Facades\Auth;

class Log extends Model
{
    use Filter;

    //查询字段
    public $fieldSearchable = [
        'module',
        'action',
        'target_type',
        'target_id',
        'target_field',
        'user_id',
        'start_time',
        'end_time',
    ];

    public $fillable = [
        'module',
        'action',
        'target_type',
        'target_id',
        'target_field',
        'before_update',
        'after_update',
    ];

    public function getModuleAttribute($value)
    {
        $map = [
            'goods' => '商品',
            'menu' => '菜单',
            'permission' => '权限',
            'role' => '角色',
            'user' => '用户',
            'plat' => '平台',
            'file' => '文件',
        ];

        return $map[$value] ?? $value;
    }

    public function getActionAttribute($value)
    {
        $map = [
            'GET' => '查看',
            'POST' => '新增',
            'PATCH' => '更新',
            'DELETE' => '删除',
        ];

        return $map[$value] ?? $value;
    }

    public function getTargetTypeAttribute($value)
    {
        $map = [
            'goods_sku' => '商品&规格',
            'goods_type' => '商品种类',
            'goods_brand' => '商品品牌',
            'permission' => '权限',
            'role' => '角色',
            'menu' => '菜单',
            'user' => '用户',
            'upload' => '上传',
            'kuaituantuan' => '快团团',
            'miaoxuan' => '妙选',
            'goods' => '商品',
        ];

        return $map[$value] ?? $value;
    }

    public function getTargetFieldAttribute($value)
    {
        $map = [
            'add' => '创建',
            'status' => '状态',
            'name' => '名称',
            'title' => '名称',
            'import' => '导入',
            'export' => '导出',
            'set' => '设置',
            'cost' => '成本',
            'stock' => '库存',
            'inventory' => '库存盘点',
            'reserve' => '预留量 ',
            'timingInventory' => '7店盘点 ',
            'pdd.ktt.goods.query.list' => '快团团下载绑定商品',
            'arrived_today_num' => '今日到货',
            'loss_num' => '损耗',
            'pdd.pop.auth.token.create' => '快团团授权',
            'reference_price' => '参考价格',
            'update' => '更新',
        ];

        return $map[$value] ?? $value;
    }

    public function setUserIdAttribute($value)
    {
        $this->attributes['user_id'] = Auth::id() ?: $value;
    }

    public function add($targetId = 0, $targetField = '')
    {
        $this->attributes['user_id'] = Auth::id();
        $this->attributes['target_id'] = $targetId;
        $this->attributes['target_field'] = $targetField;

        return $this->save();
    }

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }
}
