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

use app\dice\basic\DiceBaseLogic;
use app\dice\model\lottery_pool_config\DiceLotteryPoolConfig;
use plugin\saiadmin\exception\ApiException;
use plugin\saiadmin\utils\Helper;
use app\dice\model\player\DicePlayer;

/**
 * 大富翁-玩家逻辑层
 */
class DicePlayerLogic extends DiceBaseLogic
{
    /** 密码加密盐（可与 config 统一） */
    private const PASSWORD_SALT = 'dice_player_salt_2024';

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new DicePlayer();
    }

    /**
     * 添加数据（密码 md5+salt 加密）
     */
    public function add(array $data): mixed
    {
        if (!empty($data['password'])) {
            $data['password'] = $this->hashPassword($data['password']);
        }
        return parent::add($data);
    }

    /**
     * 修改数据（仅当传入 password 时用 md5+salt 加密后更新）
     */
    public function edit($id, array $data): mixed
    {
        if (isset($data['password']) && $data['password'] !== '') {
            $data['password'] = $this->hashPassword($data['password']);
        } else {
            unset($data['password']);
        }
        $data = $this->applyLotteryPoolWeightsToPlayerData($data);
        return parent::edit($id, $data);
    }

    /**
     * 已绑定彩金池时：玩家 T1–T5 以池配置为准，避免前端提交陈旧权重覆盖同步结果
     */
    private function applyLotteryPoolWeightsToPlayerData(array $data): array
    {
        $configId = isset($data['lottery_config_id']) ? (int) $data['lottery_config_id'] : 0;
        if ($configId <= 0) {
            return $data;
        }
        $config = DiceLotteryPoolConfig::find($configId);
        if (!$config) {
            return $data;
        }
        $row = $config->getData();
        foreach (['t1_weight', 't2_weight', 't3_weight', 't4_weight', 't5_weight'] as $field) {
            $data[$field] = $row[$field] ?? 0;
        }
        return $data;
    }

    /**
     * 密码加密：md5(salt . password)
     */
    private function hashPassword(string $password): string
    {
        return md5(self::PASSWORD_SALT . $password);
    }
}
