<?php

namespace common\models;

use common\helpers\user\Info;
use Yii;
use common\libs\logging\operate\valueType\Config as ValueTypeConfig;

/**
 * This is the model class for table "{{%USER_BONUS}}".
 *
 * @property string $ID
 * @property string $USER_ID 会员ID
 * @property string $BONUS 奖金总额
 * @property string $BONUS_FREEZE 奖金冻结部分
 * @property int $VER 乐观锁标识
 * @property int $CREATED_AT 创建时间
 * @property int $RECONSUME_POINTS 复消积分
 * @property int $RECONSUME_POINTS_EXPIRED 复消积分过期
 * @property int $RECONSUME_POINTS_TOTAL 复消积分累计
 * @property int $MANAGE_TAX 管理费累计
 * @property int $BONUS_TOTAL 总奖金累计
 */
class UserBonus extends \common\components\ActiveRecord
{
    const TYPE = BalanceAudit::TYPE;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%USER_BONUS}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['USER_ID', 'CREATED_AT'], 'required'],
            [['BONUS', 'RECONSUME_POINTS', 'MANAGE_TAX', 'BONUS_TOTAL'], 'number'],
            [['VER', 'CREATED_AT'], 'integer'],
            [['ID','USER_ID'], 'string', 'max' => 32],
            [['USER_ID'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'ID' => 'ID',
            'USER_ID' => '会员ID',
            'BONUS' => '奖金总额',
            'VER' => '乐观锁标识',
            'CREATED_AT' => '创建时间',
            'RECONSUME_POINTS' => '复消积分',
            'RECONSUME_POINTS_TOTAL' => '复消积分累计',
            'RECONSUME_POINTS_EXPIRED' => '复消积分过期',
            'MANAGE_TAX' => '管理费累计',
            'BONUS_TOTAL' => '总奖金累计',
        ];
    }

    /**
     * 操作日志记录条件
     * @return array
     */
    public function attrLabelsWithLogType(){
        return [
            'USER_ID' => '会员ID',
            'BONUS' => '会员账户',
        ];
    }

    /**
     * 乐观锁
     * @return string
     */
    public function optimisticLock()
    {
        return 'VER';
    }

    /**
     * 获取一名会员的余额
     * @param $userId
     * @return array|null
     */
    public static function getBonusByUserId($userId)
    {
        $data = UserBonus::findOneAsArray('USER_ID=:USER_ID', [':USER_ID'=>$userId], 'USER_ID,BONUS');

        return $data ?: ['USER_ID' => $userId, 'BONUS' => 0];
    }

    public function insertOrUpdate()
    {
        if ($this->USER_ID !== null) {
            $pk = $this->USER_ID;
            if (!empty($this->$pk)) {
                return $this->update();
            } else {
                return $this->insert();
            }
        } else {
            // 如果模型没有定义主键，则直接插入
            return $this->insert();
        }
    }
}
