<?php

namespace app\admin\model;

use support\Db;
use support\Model;

/**
 * 悦活健康超市订单
 * Class Order
 * @package app\admin\model
 */
class GoodsOrder extends Model
{
    /**
     *
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'life_market_order';

    public $timestamps = false;

    /**
     * Notes:获取订单列表
     * @param string $keywords
     * @param int $page
     * @param int $limit
     * @return array
     * User: ZQ
     * Date: 2022/10/13
     */
    public static function getOrderList(int $page, int $limit,$keywords,$order_type_model)
    {
        $list = static::select(['life_market_order.*','merchant_shop.shop_name'])
            ->leftJoin('merchant_shop','shop_id','=','life_market_order.order_shop_id')
            ->when($keywords != '', function ($query) use ($keywords){
                $query->where('order_dno', 'like', '%' . $keywords . '%');
            })
            ->where('order_type_model',$order_type_model)
            ->with(['user','Detail'])
            ->orderBy('order_create_time','DESC')
            ->forPage($page, $limit)
            ->get()->toArray();

        $count = static::when($keywords != '', function ($query) use ($keywords){
            $query->where('order_dno', 'like', '%' . $keywords . '%');
        })->count();
        return [$list, $count];
    }

    //关联店铺
    public function Shop(){
        return $this->belongsTo(MerchantShop::class,'order_shop_id','shop_id');
    }
    //获取用户信息
   public function User(){
        return $this->belongsTo(User::class,'order_user_id','user_id');
   }
    //获取订单详情
    public function Detail(){
        return $this->hasMany(GoodsOrderDetail::class,'detail_order_id','order_id')
            ->leftJoin('life_market_goods','goods_id','=','life_market_order_detail.detail_goods_id')
            ->leftJoin('category','category_id','=','life_market_goods.goods_category_id')
            ->select(['life_market_order_detail.*','life_market_goods.goods_name','life_market_goods.goods_category_id','category.category_name']);
    }
    //关联购物车
    public function Cart(){
        return $this->hasMany(GoodsOrderCart::class,'cart_id','order_cart_id')
            ->leftJoin('life_market_goods','goods_id','=','life_market_cart.cart_goods_id')
            ->select(['life_market_cart.*','life_market_goods.goods_name']);
    }

    //时间格式
    public function getOrderCreateTimeAttribute($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    public function getOrderPayTimeAttribute($value)
    {
        if($value == 0 || $value == ''){
            return 0;
        }else{
            return date('Y-m-d H:i:s', $value);
        }
        
    }
}