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

namespace app\api\controller;

/**
 * 
 * Summary of Group
 */
class MerchantGoods extends BaseShopController
{

    public array $notNeedLogin = ['list','details'];

    /**
     * 商家添加商品
     * @return void
     */
    public function CreateGoods()
    {
        $params = $this->request->post();

        $data = [
            'user_id'=>$this->userId,
            'name'=>$params['name'],
            'desc'=>$params['desc'],
            'image'=>$params['image'],
            'price'=>$params['price'],
            'limit_per_user'=>$params['limit_per_user'],
            'sort'=>$params['sort'],
            'stock'=>$params['stock'],
            'status'=>1,//
        ];

        $res = \app\common\model\MerchantGoods::create($data);

        return show(config('status.success'),'添加成成功',$res->id);

    }

    /**
     * 商家添加商品
     * @return void
     */
    public function updateGoods($id)
    {
        $params = $this->request->post();

        $goods = \app\common\model\MerchantGoods::find($id);
        if($goods && $goods->user_id!=$this->userId){
            return show(0,'无权限修改');
        }

        $res = \app\common\model\MerchantGoods::where('id',$id)->update($params);

        return show(config('status.success'),'修改成功');

    }

    public function delGoods($id)
    {
        $goods = \app\common\model\MerchantGoods::find($id);
        if($goods && $goods->user_id!=$this->userId){
            return show(0,'无权限删除');
        }

        $res = \app\common\model\MerchantGoods::where('id',$id)->delete();

        return show(config('status.success'),'删除成功');

    }


    /**
     * 商家商品数据搜索
     * @return void
     */
    public function list()
    {

        $params = $this->request->get();

        $where = [];

        if(isset($params['user_id'])){
            $where[]=['user_id','=',$params['user_id']];
        }

        $list = \app\common\model\MerchantGoods::with(['user','user.merchant'])
        ->where($where)
        ->paginate(20);

        return show(config('status.success'),'',$list);
    }

    public function details($id)
    {

        $list = \app\common\model\MerchantGoods::with(['user','user.merchant'])
        ->find($id);

        return show(config('status.success'),'',$list);
    }


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

        $goods = \app\common\model\MerchantGoods::find($params['goods_id'])->toArray();

        $params['user_id'] = $this->userId;
        $params['terminal'] = $this->userInfo['terminal'];

        if($params['order_num']<1){
            return show(\config('status.error'),"购买数量不能小于1");
        }
        
        if($params['order_num'] > $goods['limit_per_user']){
            return \show(\config('status.error'),'超出最大购买限制');
        }

        if($params['order_num'] > $goods['stock']){
            return \show(\config('status.error'),'库存不足');
        }

        $price = $params['order_num'] * $goods['price'];
        
        $data = [
            'sn'            => time().rand(00000,99999),
            'terminal'      => $params['terminal'],
            'user_id'       => $params['user_id'],
            'pay_status'    => \app\common\enum\PayEnum::UNPAID,
            'pay_way'       => $params['pay_way'] ?? 2,
            'order_amount'  => $price,
            'goods_id'      => $params['goods_id'],
            'is_use'        => 0,//未使用
            'order_num'     => $params['order_num'],
            'sell_user_id'  => $goods['user_id'],
        ];

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

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

    }

    /**
     * 查询用户购买的订单
     */
    public function userOrder()
    {
        $params = $this->request->post();
        $where = [];

        if(isset($params['status'])){
            $where[]=['status','=',$params['status']];
        }

        $list = \app\common\model\MerchantGoodsOrder::with(['goods'])
        ->where('user_id',$this->userId)
        ->where($where)
        ->order('create_time','desc')
        ->paginate(20);

        return show(config('status.success'),'',$list);
    }

    /**
     * 查询商家卖出的商品订单
     */
    public function merchantOder()
    {
        $params = $this->request->post();
        $where = [];

        if(isset($params['status'])){
            $where[]=['status','=',$params['status']];
        }

        $list = \app\common\model\MerchantGoodsOrder::with(['goods'])
        ->where('sell_user_id',$this->userId)
        ->where($where)
        ->order('create_time','desc')
        ->paginate(20);

        return show(config('status.success'),'',$list);
    }

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

        $order = \app\common\model\MerchantGoodsOrder::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'),'使用成功');
        
    }

    /**
     * 添加评论
     */
    public function addConmment()
    {
        $params = $this->request->post();

        // 判断已评论不能再评论
        $comment =  \app\common\model\MerchantGoodsComment::where('order_id',$params['order_id'])
        ->find();

        if($comment){
            return \show(\config('status.error'),'已评价过了,请勿重复评价');
        }

        $order = \app\common\model\MerchantGoodsOrder::find($params['order_id']);
        $data = [
            'goods_id'=>$order->goods_id,
            'order_id'=>$params['order_id'],
            'user_id'=>$this->userId,
            'sell_user_id'=>$order->sell_user_id,
            'goods_comment'=>$params['goods_comment'],
            
            'service_comment'=>$params['service_comment'],
            'description_comment'=>$params['description_comment'],
            'express_comment'=>$params['express_comment'],
            'comment'=>$params['comment'],
            'images'=>$params['images']??'',
            'status'=>1,//审核通过
        ];

        $res = \app\common\model\MerchantGoodsComment::create($data);
        if(!$res){
            return \show(\config('status.error'),'添加失败');
        }

        return show(config('status.success'),'添加成功');
    }

    public function commentList()
    {
        $params = $this->request->get();


        if(isset($params['order_id'])){
            $where[]=['order_id','=',$params['order_id']];
        }

        if(isset($params['goods_id'])){
            $where[]=['goods_id','=',$params['goods_id']];
        }

        if(isset($params['sell_user_id'])){
            $where[]=['sell_user_id','=',$params['sell_user_id']];
        }

        if(isset($params['status'])){
            $where[]=['status','=',$params['status']];

            if($params['status']!=1){
                $where[]=['user_id','=',$this->userId];
            }
        }

        $list = \app\common\model\MerchantGoodsComment::with('user')
        ->where($where)
        ->order('id','desc')
        ->paginate(20);

        return \show(\config('status.success'),'',$list);
    }
    
}