<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\common\model\dealer;

use app\common\enum\dealer\DealerUserEnum;
use app\common\library\helper;
use cores\BaseModel;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\model\relation\BelongsTo;

/**
 * 分销商用户模型
 * Class User
 * @package app\common\model\dealer
 */
class User extends BaseModel
{
    // 定义表名
    protected $name = 'dealer_user';

    // 定义主键
    protected $pk = 'user_id';

    /**
     * 强制类型转换
     * @var array
     */
    protected $type = [
        'first_num' => 'integer',
        'second_num' => 'integer',
        'third_num' => 'integer',
    ];

    // 追加的字段
    protected $append = ['full_money', 'type_text'];

    /**
     * @notes:身份标识
     * @param $value
     * @param $data
     * @return mixed
     * @author: wanghousheng
     */
    public function getTypeTextAttr($value, $data)
    {
        $result = DealerUserEnum::data();
        if (!empty($result[$data['type']]['name'])) {
            return $result[$data['type']]['name'];
        }
        return '未知';
    }

    /**
     * 关联会员记录表
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\User");
    }

    /**
     * 关联推荐人表
     * @return BelongsTo
     */
    public function referee(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\User", 'referee_id');
    }

    /**
     * 获取器:累积的佣金
     * @param $value
     * @param $item
     * @return string
     */
    public function getFullMoneyAttr($value, $item): string
    {
        $temp = helper::bcadd($item['freeze_money'], $item['total_money']);
        return helper::bcadd($item['money'], $temp);
    }

    /**
     * 获取分销商用户信息
     * @param int $userId
     * @param array $with
     * @return static|array|null
     */
    public static function detail(int $userId, array $with = ['user', 'referee'])
    {
        return self::get($userId, $with);
    }

    /**
     * 是否为分销商
     * @param int $userId
     * @return bool
     */
    public static function isDealerUser(int $userId): bool
    {
        return (bool)(new static)->where('user_id', '=', $userId)
            ->where('is_delete', '=', 0)
            ->value('user_id');
    }

    /**
     * 消减可提现佣金
     * @param int $dealerId 分销ID
     * @param float $money
     * @return mixed
     */
    public static function setDecMoney(int $dealerId, float $money)
    {
        return (new static)->setDec($dealerId, 'money', $money);
    }

    /**
     * 累计已冻结佣金
     * @param int $dealerId 分销ID
     * @param float $money
     * @return mixed
     */
    public static function setIncFreezeMoney(int $dealerId, float $money)
    {
        return (new static)->setInc($dealerId, 'freeze_money', $money);
    }

    /**
     * 累计可提现佣金
     * @param int $dealerId 分销ID
     * @param float $money
     * @return mixed
     */
    private static function setIncMoney(int $dealerId, float $money)
    {
        return (new static)->setInc($dealerId, 'money', $money);
    }

    /**
     * 新增分销商用户记录
     * @param int $userId
     * @param array $data
     * @return false|int
     */
    public static function add(int $userId, array $data)
    {
        $model = static::detail($userId) ?: new static;
        return $model->save(array_merge([
            'user_id' => $userId,
            'is_delete' => 0,
            'store_id' => $model::$storeId
        ], $data));
    }

    /**
     * 发放分销商佣金
     * @param int $dealerId
     * @param float $money
     * @param int $storeId
     * @return bool
     */
    public static function grantMoney(int $dealerId, float $money, int $storeId): bool
    {
        // 累积分销商可提现佣金
        static::setIncMoney($dealerId, $money);
        // 记录分销商资金明细
        Capital::add([
            'user_id' => $dealerId,
            'flow_type' => 10,
            'money' => $money,
            'describe' => '订单佣金结算',
            'store_id' => $storeId
        ]);
        return true;
    }

    /**
     * @notes:获取工程师分销商
     * @return array|Collection|User[]
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author: wanghousheng
     */
    public static function getEngineer()
    {
        return (new static())
            ->where(['type' => DealerUserEnum::ENGINEER])
            ->order(['create_time'])
            ->select();
    }
}