<?php


namespace app\models\point_plan;


use app\models\user\UserMoney;
use crmeb\basic\BaseModel;
use crmeb\traits\ModelTrait;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

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


    public static function joinPlan($id, $uid)
    {
        $info = self::where('is_del', 0)->where('id', $id)->find();
        $money = UserMoney::initialUserMoney($uid, $info['buy_money_type']);
        $money_num = bcmul($info['buy_num'], $info['buy_price'], 8);
        if ($money['money'] < $money_num) return self::setErrorInfo('账户不足!');
        BaseModel::beginTrans();
        try {
            $res = UserMoney::expendMoney($uid, $info['buy_money_type'], $money_num, 'join_point_plan', '认购节点', '认购' . $info['name'] . '节点');
            if (!$res) {
                return self::setErrorInfo(UserMoney::getErrorInfo('支付失败'), true);
            }
            $res = UserPointPlan::create([
                'buy_num' => $info['buy_num'],
                'buy_all_price' => $money_num,
                'release_ratio' => $info['release_ratio'],
                'release_money_type' => $info['release_money_type'],
                'buy_money_type' => $info['buy_money_type'],
                'check_end_time' => bcadd(time(), bcmul($info['exam_time'], 24 * 3600)),
                'layer_award_ratio' => $info['layer_award_ratio'],
                'add_time' => time(),
                'layer_award_layer' => $info['layer_award_layer'],
                'uid' => $uid,
                'release_time_all' => $info['release_day'],
                'plan_id' => $info['id'],
            ]);
            if ($res) {
                BaseModel::commitTrans();
                return $res;
            } else {
                return self::setErrorInfo('认购失败', true);
            }
        } catch (Exception $e) {
            return self::setErrorInfo($e->getMessage(), true);
        }
    }

    /**
     * @param $where
     * @return array
     */
    public static function getList($where)
    {
        $model = new self();
        if (isset($where['title']) && $where['title'] != '') {
            $model->where('id|plan_name', 'like', "%{$where['title']}%");
        }
        $count = $model->count();
        $data = $model->page((int)$where['page'], (int)$where['limit'])->select()->each(function ($item) {
            $item['join_number'] = UserPointPlan::where('plan_id', $item['id'])->count();
            $item['_start_time'] = date('Y-m-d H:i:s', $item['start_time']);
        });
        return compact('count', 'data');

    }
}