<?php


namespace app\models\mining;


use app\models\user\UserMoney;
use crmeb\basic\BaseModel;
use crmeb\traits\ModelTrait;
use think\Exception;

class UserMiningMachine extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';
    /**
     * 模型名称
     * @var string
     */
    protected $name = 'user_mining_machine';
    use ModelTrait;


    /**
     * @param int $status
     * @return UserMiningMachine
     */
    public static function valid($status = 1)
    {
        return self::where('status', $status)->where('mining_start_time', '>', time())
            ->where('mining_end_time', '<', time())->where('paid', 1);
    }

    /**
     * @return UserMiningMachine
     */
    public static function dayMiningStatusStart()
    {
        return self::valid(0)->update(['status' => 1]);
    }

    /**
     * @return UserMiningMachine
     */
    public static function dayMiningStatusEnd()
    {
        return self::where('status', [0, 1])->where('mining_end_time', '>', time())
            ->where('paid', 1)->update(['status' => 2]);
    }

    public static function dayMining()
    {
        //今日已发放矿机
        BaseModel::beginTrans();
        self::dayMiningStatusEnd();
        self::dayMiningStatusStart();
        try {
            $res = true;
            $send_ids = UserMining::where('add_date', strtotime('Y-m-d'))->column('umid');
            //今日需发放且未发放的矿机
            $list = self::valid()->whereNotIn('id', $send_ids)->select();
            if (count($list)) {
                foreach ($list as $v) {
                    $res = $res && UserMining::create([
                            'umid' => $v['id'],
                            'get_money' => bcmul($v['day_get'], $v['num'], 8),
                            'get_money_type' => $v['get_money_type'],
                            'add_time' => time(),
                            'add_date' => date('Y-m-d'),
                        ]) && UserMoney::incomeMoney($v['uid'], $v['get_money_type'], bcmul($v['day_get'], $v['num'], 8), 'mining', '挖矿', '本日挖矿释放');
                }
            }
            if ($res) {
                BaseModel::commitTrans();
                return true;
            } else
                return self::setErrorInfo(self::getErrorInfo(), false);
        } catch (Exception $e) {
            return self::setErrorInfo($e->getMessage(), true);
        }
    }
}