<?php

namespace common\models;

use common\helpers\Date;
use Exception;

/**
 * This is the model class for table "{{%USER_PERFORMANCE_LOGS}}".
 *
 * @property string ID
 * @property string USER_PERFORMANCE_ID
 * @property string ORDER_ID
 * @property double AMOUNTS
 * @property integer PERIOD_NUM
 * @property string CREATED_AT
 * @property string UPDATED_AT
 * @property string REMARK
 */
class UserPerformanceLogs extends \common\components\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%USER_PERFORMANCE_LOGS}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['USER_PERFORMANCE_ID'], 'required'],
            [['AMOUNTS'], 'number'],
            [['UPDATED_AT', 'PERIOD_NUM'], 'integer'],
            [['ID'], 'string', 'max' => 32],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID' => 'ID',
            'USER_PERFORMANCE_ID' => '奖金ID',
            'AMOUNTS' => '金额',
            'CREATED_AT' => '修改时间',
        ];
    }

    /**
     * @throws Exception
     */
    public static function changeAmountLogs($prpId, $amount, $periodNum, $orderId = '', $remark = '')
    {
        $id = Date::today('Ymd') . self::_random(10, 1);

        self::insertOne([
            'ID' => $id,
            'USER_PERFORMANCE_ID' => $prpId,
            'ORDER_ID' => $orderId,
            'AMOUNTS' => $amount,
            'PERIOD_NUM' => $periodNum,
            'REMARK' => $remark,
            'CREATED_AT' => date('Y-m-d  H:i:s', time()),
            'UPDATED_AT' => date('Y-m-d  H:i:s', time()),
        ]);
    }

    private static function _random($length, $numeric = 0) {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        $hash = '';
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed[mt_rand(0, $max)];
        }
        return $hash;
    }
}
