<?php

namespace addons\webman\model;

use addons\webman\Admin;
use addons\webman\traits\DataPermissions;
use addons\webman\traits\HasDateTimeFormatter;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use support\Cache;

/**
 * Class Player
 * @property int id 主键
 * @property int recommend_id 推荐id
 * @property int department_id 部门/渠道id
 * @property string device_number 设备号
 * @property string facebook_id facebook id
 * @property string uuid uuid
 * @property int type 类型
 * @property int level 玩家等级
 * @property int status 状态
 * @property int status_withdraw 帐号状态 1啟用 0停用
 * @property float chip_amount 当前打码量
 * @property float must_chip_amount 达成条件
 * @property float bet_rebate_amount 当期返水打码量
 * @property float sign_reward 签到获得
 * @property string phone 手机号
 * @property string name 姓名
 * @property string country_code 手机号国家编号
 * @property string recommended_code 输入推荐吗
 * @property string recommend_code 玩家推荐码
 * @property string password 密码
 * @property string play_password 支付密码
 * @property string player_tag 玩家标签
 * @property string currency 币种
 * @property string flag 标签
 * @property string avatar 头像
 * @property string created_at 创建时间
 * @property string updated_at 最后一次修改时间
 * @property string deleted_at 删除时间
 * @property string last_login 最后登录时间
 *
 * @property PlayerExtend player_extend
 * @property PlayerPlatformCash wallet
 * @property Player recommend_player
 * @property PlayerLevel player_level
 * @property PlayerLoginRecord the_last_player_login_record
 * @property PlayerRegisterRecord player_register_record
 * @property Channel channel 渠道
 * @property PlayerRechargeRecord player_recharge_record 充值
 * @property PlayerWithdrawRecord player_withdraw_record 提现
 * @property PlayerGamePlatform playerGamePlatform 玩家平台账号
 * @property PlayerPromoter player_promoter 推广员
 * @property PlayerPromoter recommend_promoter 所属推广员
 * @package addons\webman\model
 */
class Player extends Model
{
    use SoftDeletes, HasDateTimeFormatter, DataPermissions;

    const STATUS_ENABLE = 1; // 启用状态
    const STATUS_STOP = 0; // 停用状态

    const TYPE_PLAYER = 1; // 普通玩家

    //数据权限字段
    protected $dataAuth = ['department_id' => 'department_id'];
    //简写省略id，默认后台用户表的id

    /**
     * 时间转换
     * @param DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->setTable(plugin()->webman->config('database.player_table'));
    }

    public function wallet(): HasOne
    {
        return $this->hasOne(plugin()->webman->config('database.player_platform_cash_model'))->where('platform_id', PlayerPlatformCash::PLATFORM_SELF);
    }

    public function player_level(): BelongsTo
    {
        return $this->belongsTo(plugin()->webman->config('database.player_level_model'), 'level', 'level');
    }

    /**
     * 玩家扩展信息
     * @return HasOne
     */
    public function player_extend(): HasOne
    {
        return $this->hasOne(plugin()->webman->config('database.player_extend_model'), 'player_id');
    }

    public function player_promoter(): HasOne
    {
        return $this->hasOne(PlayerPromoter::class, 'player_id');
    }

    /**
     * 渠道信息
     * @return BelongsTo
     */
    public function channel(): BelongsTo
    {
        return $this->belongsTo(plugin()->webman->config('database.channel_model'), 'department_id', 'department_id')->withTrashed();
    }

    /**
     * 提现信息
     * @return hasMany
     */
    public function player_withdraw_record(): hasMany
    {
        return $this->hasMany(plugin()->webman->config('database.player_withdraw_record_model'), 'player_id');
    }

    /**
     * 提现信息
     * @return hasMany
     */
    public function player_recharge_record(): hasMany
    {
        return $this->hasMany(plugin()->webman->config('database.player_recharge_record_model'), 'player_id');
    }

    /**
     * 推荐玩家
     * @return BelongsTo
     */
    public function recommend_player(): BelongsTo
    {
        return $this->belongsTo(plugin()->webman->config('database.player_model'), 'recommend_id');
    }

    public function the_last_player_login_record(): HasOne
    {
        return $this->hasOne(PlayerLoginRecord::class, 'player_id')->latest();
    }

    public function player_register_record(): HasOne
    {
        return $this->hasOne(PlayerRegisterRecord::class, 'player_id');
    }

    /**
     * 密码哈希加密
     * @param $value
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = password_hash($value, PASSWORD_DEFAULT);
    }

    /**
     * 支付密码哈希加密
     * @param $value
     */
    public function setPlayPasswordAttribute($value)
    {
        $this->attributes['play_password'] = password_hash($value, PASSWORD_DEFAULT);
    }

    /**
     * 获取器 - 标签id
     * @param $value
     * @return false|string[]
     */
    public function getPlayerTagAttribute($value)
    {
        return array_filter(explode(',', $value));
    }

    /**
     * 修改器 - 标签id
     * @param $value
     * @return string
     */
    public function setPlayerTagAttribute($value): string
    {
        $idsStr = json_encode($value);
        $cacheKey = md5("player_tag_options_ids_$idsStr");
        Cache::delete($cacheKey);

        return $this->attributes['player_tag'] = implode(',', $value);
    }

    /**
     * 获取器 - 玩家头像
     * @param $value
     * @return false|string[]
     */
    public function getAvatarAttribute($value)
    {
        return is_numeric($value) ? config('def_avatar.' . $value) : $value;
    }

    /**
     * 玩家平台账号
     * @return hasMany
     */
    public function playerGamePlatform(): hasMany
    {
        return $this->hasMany(plugin()->webman->config('database.player_game_platform_model'), 'player_id');
    }

    /**
     * 所属推广员
     * @return BelongsTo
     */
    public function recommend_promoter(): BelongsTo
    {
        return $this->belongsTo(plugin()->webman->config('database.player_promoter_model'), 'recommend_id', 'player_id');
    }

    /**
     * 模型的 "booted" 方法
     *
     * @return void
     */
    protected static function booted()
    {
        static::updated(function (Player $player) {
            $columns = [
                'type',
                'status',
                'status_withdraw',
                'status_open_coins',
                'status_open_coins',
                'name',
                'phone',
                'country_code',
                'play_password',
                'password',
                'flag',
                'avatar',
                'player_tag',
            ];
            if ($player->wasChanged($columns) && !empty(Admin::user())) {
                $orData = $player->getOriginal();
                $changeData = $player->getChanges();
                $orDataArr = [];
                $newDataArr = [];
                foreach ($changeData as $key => $item) {
                    if (empty($item) == empty($orData[$key])) {
                        continue;
                    }
                    if ($key == 'updated_at') {
                        $orData[$key] = date('Y-m-d H:i:s', strtotime($orData[$key]));
                    }
                    $orDataArr[$key] = $orData[$key];
                    $newDataArr[$key] = $item;
                }
                if (!empty($newDataArr)) {
                    $playerEditLog = new PlayerEditLog();
                    $playerEditLog->player_id = $player->id;
                    $playerEditLog->department_id = $player->department_id;
                    $playerEditLog->origin_data = json_encode($orDataArr);
                    $playerEditLog->new_data = json_encode($newDataArr);
                    $playerEditLog->user_id = Admin::id() ?? 0;
                    $playerEditLog->user_name = !empty(Admin::user()) ? Admin::user()->username : '';
                    $playerEditLog->save();
                }
            }
        });
    }
}
