PackageOrder.php 2.1 KB
<?php

namespace app\api\model;

use think\Model;
use addons\shopro\exception\Exception;
use addons\shopro\model\User;
use app\admin\model\package\Package;
use think\Db;

class PackageOrder extends Model
{
    // 表名,不含前缀
    protected $name = 'package_order';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;

    // 追加属性
    protected $append = [

    ];

    // 获取订单号
    public static function getSn($user_id)
    {
        $rand = $user_id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
        $order_sn = date('Yhis') . $rand;

        $id = str_pad($user_id, (24 - strlen($order_sn)), '0', STR_PAD_BOTH);

        return $order_sn . $id;
    }

    // 创建订单
    public static function createOrder($params)
    {
        $user = User::info();

        // 入参
        extract($params);

        $package = Package::get($package_id);
        if (!$package) {
            throw new Exception('会员套餐不存在');
        }
        // 订单备注
        $have_order = self::where('user_id',$user->id)->where('status',1)->field('id')->find();
        $remark = $have_order ? '续费('.$package['month'].'个月)' : '开通会员';

        $orderData = [];
        $orderData['order_sn'] = self::getSn($user->id);
        $orderData['user_id'] = $user->id;
        $orderData['package_id'] = $package_id;
        $orderData['package_name'] = $package['package_name'];
        $orderData['package_price'] = $package['package_price'];
        $orderData['month'] = $package['month'];
        $orderData['pay_fee'] = $package['package_price'];
        $orderData['remark'] = $remark;
        $orderData['inviter_id'] = (!empty($inviter_id) && $inviter_id != $user->id) ? $inviter_id : 0; // 邀请人ID
        $order = new PackageOrder();
        $order->allowField(true)->save($orderData);

        // 重新获取订单
        $order = self::where('id', $order['id'])->find();

        return $order;
    }
}