<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace app\dice\model\player;

use app\dice\helper\AdminScopeHelper;
use app\dice\model\DiceModel;
use app\dice\model\lottery_pool_config\DiceLotteryPoolConfig;

/**
 * 大富翁-玩家模型
 *
 * dice_player 大富翁-玩家
 *
 * @property  $id ID
 * @property  $dept_id 所属渠道ID
 * @property  $username 用户名（同渠道内唯一）
 * @property  $phone 手机
 * @property  $uid uid
 * @property  $name 昵称
 * @property  $password 密码
 * @property  $status 状态
 * @property  $coin 平台币
 * @property  $admin_id 创建该玩家的后台管理员ID，关联 sa_system_user.id
 * @property  $lottery_config_id 彩金池配置ID（0或null时使用自定义权重*_weight）
 * @property  $t1_weight T1池权重
 * @property  $t2_weight T2池权重
 * @property  $t3_weight T3池权重
 * @property  $t4_weight T4池权重
 * @property  $t5_weight T5池权重
 * @property  $total_ticket_count 总抽奖次数
 * @property  $paid_ticket_count 购买抽奖次数
 * @property  $free_ticket_count 赠送抽奖次数
 * @property  array|null $free_ticket 免费抽奖券：{"ante":1,"count":1}
 * @property  $create_time 创建时间
 * @property  $update_time 更新时间
 * @property  $delete_time 删除时间
 */
class DicePlayer extends DiceModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 数据库表名称
     * @var string
     */
    protected $table = 'dice_player';

    protected $createTime = 'create_time';

    protected $updateTime = 'update_time';

    protected $json = ['free_ticket'];

    protected $jsonAssoc = true;

    /**
     * 新增前：生成唯一 uid，昵称 name 默认使用 uid
     * 用 try-catch 避免表尚未含 uid 时 getAttr/getData 抛 InvalidArgumentException
     */
    public static function onBeforeInsert($model): void
    {
        parent::onBeforeInsert($model);
        try {
            $uid = $model->getAttr('uid');
        } catch (\Throwable $e) {
            $uid = null;
        }
        if ($uid === null || $uid === '') {
            $uid = self::generateUid();
            $model->setAttr('uid', $uid);
        }
        try {
            $name = $model->getAttr('name');
        } catch (\Throwable $e) {
            $name = null;
        }
        if ($name === null || $name === '') {
            $model->setAttr('name', $uid);
        }
        // 创建玩家时：未指定则关联 name=playerDefault（玩家默认彩金池），没有则为 0
        try {
            $lotteryConfigId = $model->getAttr('lottery_config_id');
        } catch (\Throwable $e) {
            $lotteryConfigId = null;
        }
        if ($lotteryConfigId === null || $lotteryConfigId === '' || (int) $lotteryConfigId === 0) {
            $config = self::findPlayerDefaultLotteryConfigForPlayer($model);
            $model->setAttr('lottery_config_id', $config ? (int) $config->id : 0);
        }
        // 展示用权重：从玩家关联的彩金池复制（playerDefault 在抽奖时仍实时读池配置）
        self::setDefaultWeightsFromLotteryConfig($model);
    }

    /**
     * 按玩家所属渠道查找玩家默认彩金池（name=playerDefault）
     */
    protected static function findPlayerDefaultLotteryConfigForPlayer(DicePlayer $model): ?DiceLotteryPoolConfig
    {
        try {
            $deptId = $model->getAttr('dept_id');
        } catch (\Throwable $e) {
            $deptId = null;
        }
        $normalizedDeptId = AdminScopeHelper::resolvePlayerConfigDeptId($model);
        if ($deptId !== null && $deptId !== '' && (int) $deptId > 0) {
            $normalizedDeptId = (int) $deptId;
        }
        $config = DiceLotteryPoolConfig::findByNameForDept(
            DiceLotteryPoolConfig::NAME_PLAYER_DEFAULT,
            $normalizedDeptId
        );
        if ($config) {
            return $config;
        }
        return DiceLotteryPoolConfig::findByNameForDept('default', $normalizedDeptId);
    }

    /**
     * 从玩家关联彩金池（或 playerDefault / default）取 t1_weight～t5_weight 作为未设置时的默认值
     */
    protected static function setDefaultWeightsFromLotteryConfig(DicePlayer $model): void
    {
        $config = null;
        try {
            $lotteryConfigId = (int) $model->getAttr('lottery_config_id');
        } catch (\Throwable $e) {
            $lotteryConfigId = 0;
        }
        if ($lotteryConfigId > 0) {
            $config = DiceLotteryPoolConfig::find($lotteryConfigId);
        }
        if (!$config) {
            $config = self::findPlayerDefaultLotteryConfigForPlayer($model);
        }
        if (!$config) {
            return;
        }
        $fields = ['t1_weight', 't2_weight', 't3_weight', 't4_weight', 't5_weight'];
        foreach ($fields as $field) {
            try {
                $val = $model->getAttr($field);
            } catch (\Throwable $e) {
                $val = null;
            }
            if ($val === null || $val === '') {
                try {
                    $model->setAttr($field, $config->getAttr($field));
                } catch (\Throwable $e) {
                    // 忽略字段不存在
                }
            }
        }
    }

    /**
     * 生成唯一标识 uid（12 位十六进制）
     */
    public static function generateUid(): string
    {
        return strtoupper(substr(bin2hex(random_bytes(6)), 0, 12));
    }

    /**
     * 用户名 搜索
     */
    public function searchUsernameAttr($query, $value)
    {
        $query->where('username', 'like', '%'.$value.'%');
    }

    /**
     * 昵称 搜索
     */
    public function searchNameAttr($query, $value)
    {
        $query->where('name', 'like', '%'.$value.'%');
    }

    /**
     * 手机号 模糊搜索
     */
    public function searchPhoneAttr($query, $value)
    {
        if ($value !== '' && $value !== null) {
            $query->where('phone', 'like', '%' . $value . '%');
        }
    }

    /**
     * 状态 搜索
     */
    public function searchStatusAttr($query, $value)
    {
        if ($value !== '' && $value !== null) {
            $query->where('status', '=', $value);
        }
    }

    /**
     * 平台币 搜索
     */
    public function searchCoinAttr($query, $value)
    {
        if ($value !== '' && $value !== null) {
            $query->where('coin', '=', $value);
        }
    }

    /**
     * 彩金池配置ID 搜索
     */
    public function searchLottery_config_idAttr($query, $value)
    {
        if ($value !== '' && $value !== null) {
            $query->where('lottery_config_id', '=', $value);
        }
    }

    /**
     * 关联彩金池配置
     */
    public function diceLotteryPoolConfig()
    {
        return $this->belongsTo(DiceLotteryPoolConfig::class, 'lottery_config_id', 'id');
    }
}
