<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */

namespace app\api\controller\pointsshop;

// use app\api\lists\OrderLists;
use app\api\logic\twoshop\OrderLogic;
use app\api\validate\twoshop\PlaceOrderValidate;
use app\api\validate\twoshop\OrderValidate;

/**
 * 订单
 * Class OrderController
 * @package app\api\controller
 */
class Order extends \app\api\controller\BaseShopController
{

    /**
     * 创建订单
     */
    public function create()
    {
        $params = $this->request->post();

        $goods = \app\common\model\PointsGoods::find($params['goods_id']);

        if($params['goods_num'] > $goods->stock){
            return show(config('status.error'),'库存不足');
        };
        if($params['goods_num'] < 1){
            return show(config('status.error'),'购买数量需大于1');
        };

        // 计算积分
        $total_points_price = $params['goods_num'] * $goods->points_price;
        
        $user = \app\common\model\User::find($this->userId);

        if($user->user_integral < $total_points_price){
            return show(config('status.error'),'积分不足');
        }

        \think\facade\Db::startTrans();
        try{
            // 创建订单
            $order_data = [
                "user_id" => $this->userId,
                "sn" => time().round(10000,99999),
                'goods_id'=> $goods->id,
                'goods_num'=> $params['goods_num'],
                'total_points' => $total_points_price,
                'status' => 0,//待发货
                'address' => $params['address'],
                'phone' => $params['phone'],
                'remark'    => $params['remark'],
            ];
            \app\common\model\PointsOrder::create($order_data);

            // 扣除积分
            \app\common\model\User::update([
                'user_integral' => ['dec', $total_points_price]
            ], ['id' => $this->userId]);
            
            //积分流水
            \app\common\model\PointsLog::create([
                'user_id'=>$this->userId,
                'points'=>$total_points_price,
                'transaction_type'=>2,//消费
                'transaction_source'=>4,//兑换商品
                'remark'=>'兑换商品：'.$goods->name,
            ]);

            \think\facade\Db::commit();
            return show(config('status.success'),'下单成功');
        }catch(\Exception $e){
            \think\facade\Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }

    }


    /**
     * @notes 订单列表
     * @return \think\response\Json
     */
    public function list()
    {
        $params = $this->request->get();
        $where = [
            'user_id'=>$this->userId,
        ];
        if(isset($params['status'])){
            $where[]=['status','=',$params['status']];
        }
        $list = \app\common\model\PointsOrder::where($where)
        ->paginate(10);

        return show(config('status.success'),'订单列表',$list);
    }


    /**
     * @notes 订单详情
     * @return \think\response\Json
     */
    public function detail()
    {
        $order = \app\common\model\PointsOrder::with('goods')
        ->find($this->request->get('id'));
        
        return show(config('status.success'),'订单详情',$order);
    }


}