<?php
// +----------------------------------------------------------------------
// | Ceeen Wise System
// +----------------------------------------------------------------------
// | Copyright (c) 2007-2017 http://fely.cc All rights reserved.
// +----------------------------------------------------------------------
// | Date: 2017/6/6 Time: 0:25
// +----------------------------------------------------------------------
// | Author: fely <fely@fely.cc> 
// +----------------------------------------------------------------------

namespace app\common\model\jarc;


use think\Model;

/**
 * Class Config 系统配置
 * @package common\model
 */
class User extends Model
{
    // 直接使用配置参数名
    protected $connection = 'db_jarc';

    /**
     * 更改积分
     */
    public function changeScore($score, $comment, $action = '', $union_id = '')
    {
        if (empty($union_id)) {
            return ['code' => 0, 'msg' => '用户不存在'];
        }
        $this->startTrans();
        try {
            $user = $this->lock(true)->where('union_id', $union_id)->find();
            if (empty($user)) {
                throw new \Exception("用户不存在");
            }

            //判断分数是否足够
            if ($score < 0 && $user['score'] < abs($score)) {
                throw new \Exception("积分不足,您的积分只有{$user['score']}!");
            }

            //记录日志
            UserScoreLog::create([
                'user_id'      => $user['id'],
                'create_time'  => time(),
                'action'       => $action,
                'score'        => $score,
                'score_before' => $user['score'],
                'score_after'  => $user['score'] + $score,
                'comment'      => $comment,
            ]);

            $user->score = $user['score'] + $score;
            $user->save();

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            return ['code' => 0, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '操作成功'];
    }

    /**
     * 状态
     */
    public static function isEnabled($user_id = 0)
    {
        return self::where(['id' => $user_id, 'user_status' => 1])->count() > 0;
    }
}