<?php

namespace app\model;

use think\Model;

class GameControlAutoRTPConfigModel extends Model
{
    // 设置表名
    protected $name = 'control_auto_rtp_config';

    protected $connection = 'fortue_tiger';

    // 设置主键
    protected $pk = 'id';
    // 设置自动时间戳
    protected $autoWriteTimestamp = 'int';

    // 设置字段类型
    protected $type = [
        'id' => 'int',
        'app_id' => 'int', // 商户ID
        'new_user_number' => 'int', // 定义新手玩家的游戏局数
        'float_rate' => 'int', // 玩家RTP高于游戏设定RTP进入系统判断
        'rtp_check' => 'int', // 游戏内统计数据周期
        'rtp_float' => 'int', // 玩家RTP上下限的误差范围
        'status' => 'int', // 状态 1 正常，0 取消
        'rtp_kill_data' => 'string', // 配置列表
        'create_time' => 'int',
        'update_time' => 'int',
    ];

    /**
     * 初始化 生成默认配置
     * @param $appId
     * @return array
     */
    public static function initCreateData($appId) {
        $form = [
            'app_id' => $appId,
            'new_user_number' => 150,
            'float_rate' => 15 * 100,
            'rtp_check' => 10,
            'rtp_float' => 2.5 * 100,
            'status' => 1,
            'rtp_kill_data' => [
                ['new' => 0, 'old' => 5000,], // defaultRtpValue * 100 + float_rate ~ defaultRtpValue * 100 + float_rate + (rtp_float * 2)
                ['new' => 500, 'old' => 5000],
                ['new' => 1000, 'old' => 5000],
                ['new' => 1500, 'old' => 5000],
                ['new' => 2000, 'old' => 5000],
                ['new' => 2000, 'old' => 5000],
                ['new' => 2000, 'old' => 6000],
                ['new' => 2000, 'old' => 7000],
                ['new' => 2000, 'old' => 8000],
                ['new' => 2000, 'old' => 9000],
            ]
        ];
        $form['rtp_kill_data'] = json_encode($form['rtp_kill_data']);
        self::create($form);
        return $form;
    }

    public static function getAutoRtpConfigInfo($app_id, $defaultRtp = null)
    {
        $info = self::where(['app_id' => $app_id])->find();
        if(empty($info)) {
            return null;
        }
        $info = $info->toArray();
        $info['rtp_kill_data'] = json_decode($info['rtp_kill_data'], true);
        $diff_rtp = $info['rtp_float'] * 2;

        $rtp = ($defaultRtp ?? $GLOBALS['defaultRTPValue']) * 100;
        foreach ($info['rtp_kill_data'] as $idx => $item) {
            // $start = $rtp + ($diff_rtp * $idx) + $info['float_rate'];
            // $end = $start + $diff_rtp;
            $item['new'] = bcdiv($item['new'], 100, 2) * 1;
            $item['old'] = bcdiv($item['old'], 100, 2) * 1;
            $info['rtp_kill_data'][$idx] = $item;
        }

        $info['float_rate'] = bcdiv($info['float_rate'], 100, 2) * 1;
        $info['rtp_float'] = bcdiv($info['rtp_float'], 100, 2) * 1;
        $info['default_rtp'] = bcdiv($rtp, 100, 2) * 1;
        return $info;
    }
}