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

namespace app\api\controller;

/**
 * 好团团购功能:套餐搭配优惠
 * Summary of Group
 */
class MerchantGoodsPackage extends BaseShopController
{
    public array $notNeedLogin = ['packageList','details'];

    // 商家发布优惠套餐
    public function create()
    {
        $params=$this->request->post();

        $goods=\app\common\model\MerchantGoods::where('user_id',$this->userId)
        ->whereIn("id",$params['goods_ids'])->select()->toArray();

        if(empty($goods)){
            return \show(0,'未选择有效商品');
        }

        \think\facade\Db::startTrans();
        try{

            // 添加商品优惠套餐主表数据
            $package_data=[
                "user_id"=>$this->userId,
                "name"=>$params['start_time'],//套餐名称
                "package_price"=>1,//套餐价格
                'start_time'=>$params['start_time'],//开始时间
                'end_time'=>$params['end_time'],//结束时间
                'total_stock'=>$params['total_stock'],//总库存（套餐库存）
                'sold_count'=>$params['sold_count'],//已销售数量
                'cover_image'=>$params['cover_image'],//套餐封面图
                'description'=>$params['description'],//套餐描述
                'limit_per_user'=>$params['limit_per_user'],//每人限购数量，0则不限购
                'status'=>0,//下架
            ];

            $res = \app\common\model\MerchantGoodsPackage::create($package_data);
            // 套餐包含商品关联表
            $package_goods_data=[];
            foreach($goods as $v){
                $package_goods_data[]=[
                    'user_id'=>$this->userId,
                    'package_id'=> $res->id,
                    'goods_id'=>$v['id'],
                ];
            }

            // 商品关联表
            \app\common\model\MerchantGoodsPackageGoods::insertAll($package_goods_data);
        
            \think\facade\Db::commit();
            return show(1,'添加成功');

        }catch(\Exception $e){
            \think\facade\Db::rollback();
            return show(config('status.error'),'添加失败'.$e->getMessage());
        }
       


    }

    // 编辑修改优惠套餐
    public function delGoods($packageGoodsId)
    {
        $packageGoods=\app\common\model\MerchantGoodsPackageGoods::where('user_id',$this->userId)
        ->where('id',$packageGoodsId)
        ->delete();

        return show(1,'删除成功');
    }

    // 给优惠套餐添加商品
    public function addGoods()
    {
        $params=$this->request->post();

        $package = \app\common\model\MerchantGoodsPackage::where('user_id',$this->userId)
        ->where('id',$params['package'])->find();

        if(empty($package)){
            return \show(0,'未找到优惠套餐');
        }

        $goods=\app\common\model\MerchantGoods::where('user_id',$this->userId)
        ->whereIn("id",$params['goods_ids'])->select()->toArray();

        if(empty($goods)){
            return \show(0,'未选择有效商品');
        }

        //  套餐包含商品关联表
        $package_goods_data=[];
        foreach($goods as $v){
            $package_goods_data[]=[
                'package_id'=>1,
                'goods_id'=>$v['id'],
            ];
        }

        // 商品关联表
        \app\common\model\MerchantGoodsPackageGoods::insertAll($package_goods_data);
      
        return show(1,'添加成功');
    }

    // 删除优惠套餐
    public function del($id)
    {
        \think\facade\Db::startTrans();
        try{

            // 删除套餐数据
            \app\common\model\MerchantGoodsPackage::where('user_id',$this->userId)
            ->where('id',$id)->delete();

            // 删除套餐关联数据
            \app\common\model\MerchantGoodsPackageGoods::where('user_id',$this->userId)
            ->where('package_id',$id)
            ->delete();
            
            \think\facade\Db::commit();
            return show(1,'删除成功');

        }catch(\Exception $e){
            \think\facade\Db::rollback();
            return show(config('status.error'),'删除失败'.$e->getMessage());
        }

    }

    // 商家查询自己发布的商家商品
    public function myPackageList()
    {
        $list=\app\common\model\MerchantGoodsPackage::with('goods')
        ->where('user_id',$this->userId)->paginate(10);

        return \show(1,'',$list);
    }
       

    // 商家查看自己的套餐商品详情
    public function myPackageDetails($id)
    {
        $data=\app\common\model\MerchantGoodsPackage::with('goods')
        ->where('user_id',$this->userId)
        ->where('id',$id)
        ->find();

        return \show(1,'',$data);
    }

    // 用户查询/搜索可用的团购套餐优惠商品
    public function packageList()
    {
        $params=$this->request->get();

        $where=[
            ['start_time','>',time()],
            ['end_time','<',time()],
            ['status','=',1],
        ];

        
        $order=[
            'update_time'=>'desc',
        ];

        $list=\app\common\model\MerchantGoodsPackage::with('goods')
        ->where($where)
        ->order($order)
        ->paginate(10);

        return \show(1,'',$list);
    }

    // 用户查询套餐详情
     public function details($id)
    {
        $data=\app\common\model\MerchantGoodsPackage::with('goods')
        ->where('id',$id)
        ->find();

        return \show(1,'',$data);
    }
      
    // 创建团购套餐订单
    public function createOrder()
    {
        $params = $this->request->post();

        $package=\app\common\model\MerchantGoodsPackage::with('goods')
        ->where('id',$params['package_id'])
        ->find();

        // 开始结束时间判断
        $currentTime=time();
        if($package->start_time < $currentTime){
            return show(0,'未到开始时间');
        }
        if($package->end_time > $currentTime){
            return show(0,'已结束');
        }

        
        if($params['buy_num']<1){
            return show(0,'购买数量不能小于1');
        }
        // 库存判断
        if($package->total_stock < 1){
            return show(0,'库存不足');
        }
        if($package->total_stock < $params['buy_num']){
            return show(0,'库存低于你买入的数量');
        }


        // 限购判断
        if($package->limit_per_user>0 && $package->limit_per_user < $params['buy_num']){
            return show(0,'超出限购的数量');
        }
        $orderNum=\app\common\model\MerchantGoodsPackageOrder::where([
            'user_id'=>$this->userId,
            'package_id'=>$params['package_id'],
            'pay_status'=>1,
        ])->count();
        if($package->limit_per_user>0 && $package->limit_per_user <= $orderNum){
            return show(0,'超出限购的数量');
        }

        // 计算订单总价
        $price=$package->package_price*$params['buy_num'];
        // 套餐里的商品id
        $goods_ids='';
        foreach($package->goods as $v){
            if(empty($goods_ids)){
                $goods_ids=$v->id;
            }else{   
                $goods_ids.=','.$v->id;
            }
        }

        // 创建订单
        $data = [
            'sn'            => time().rand(00000,99999),
            'terminal'      => $this->terminal,
            'user_id'       => $this->userId,
            'pay_status'    => 0,
            'pay_way'       => $params['pay_way'] ?? 2,
            'order_amount'  => $price,
            'package_id'      => $params['package_id'],
            'goods_ids'      => $goods_ids,
            'is_use'        => 0,//未使用
            'order_num'     => $params['buy_num'],
            'sell_user_id'  => $package->user_id,
        ];

        $order = \app\common\model\MerchantGoodsPackageOrder::create($data);
        if(!$order){
            return show(config('status.error'),'error');
        }

        return show(config('status.success'),'ok',[
            'order_id' => $order->id,
            'from' => 'merchant_goods_package'
        ]);

    }

    // 查询我的订单
    public function myOrderList()
    {
        $list=\app\common\model\MerchantGoodsPackageOrder::with('package')
        ->where('user_id',$this->userId)
        ->order('create_time','desc')
        ->paginate(10);

        return \show(1,'',$list);
    }

    // 查询我的订单详情
    public function myOrderDetails($id)
    {
        $data=\app\common\model\MerchantGoodsPackageOrder::with('package')
        ->where('user_id',$this->userId)
        ->find($id);

        return \show(1,'',$data);
    }


    /**
     * 商家使用订单
     */
    public function userUseOrder()
    {
        $params = $this->request->post();

        $order = \app\common\model\MerchantGoodsPackageOrder::where([
            'user_id'=>$this->userId,
            'id'=>$params['id'],
            'is_use'=>0,
        ])->find();

        if(!$order){
            return show(config('status.error'),'订单不存在或订单已使用');
        }

        $order->is_user = 1;
        $order->save();

        return show(config('status.error'),'使用成功');
    }



}

