<?php

namespace app\common\model;

use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];

    /**
     * 获取个人URL
     * @param   string $value
     * @param   array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user && $score != 0) {
            $before = $user->score;
            $after = $user->score + $score;
            //更新会员信息
            $user->score = $after;
            $user->save();
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

    /**
     * 积分记录
     */
    public function scoreLog($user_id,$page,$rows)
    {
        $list = ScoreLog::where('user_id',$user_id)
            ->order(['createtime' => 'desc'])
            ->paginate($rows,false,['page'=>$page])
            ->each(function($v){
                $v['createtime'] = date('Y-m-d H:i',$v['createtime']);
                $v->visible(['score','memo','createtime']);
            })->toArray();
        return ['total'=>$list['total'],'list'=>$list['data']];
    }
}