<?php

namespace app\model\api;

use library\traits\ModelTrait;
use think\Model;

/**
 * @mixin \think\Model
 */
class Product extends Model
{
    use ModelTrait;

    public static function getProductList($data)
    {
        $cid = $data['cid'];
        $keyword = $data['keyword'];
        $page = $data['page'];
        $limit = $data['limit'];
        $model = self::where('is_del', 0)->where('is_show', 1);
        if($keyword != ''){
            $model->where('store_name|keyword', 'LIKE', "%$keyword%");
        }
        if($cid){
            if($cid == -1){
                $model->where('issuing', 1);
            }else if($cid == -2){
                $model->where('is_leftover', 1);
            }else{
                $model->where('cate_id', $cid);
            }
            if($data['sort'] == 'sort'){
                $model->order('sort DESC, add_time DESC');
            }
        }else{
            if($data['sort'] == 'sort'){
                $model->where('is_best', 1)->order('sort DESC, add_time DESC');
            }
        }
        if($data['sort'] == 'sales'){
            $model->orderRaw('sales+ficti desc');
        }
        if($data['sort'] == 'commission'){
            $model->orderRaw('price-ot_price desc');
        }
        if($data['sort'] == 'new'){
            $model->order('add_time DESC');
        }
        $list = $model->page((int)$page, (int)$limit)->field('id,store_name,image,price,cost,ot_price,(price-ot_price) as commission,IFNULL(sales,0) + IFNULL(ficti,0) as sales')->select();
        $list = count($list) ? $list->toArray() : [];
        return $list;
    }

    public static function getValidProduct($productId, $field = 'add_time,browse,cate_id,code_path,cost,ficti,id,image,is_sub,is_best,is_del,is_hot,is_show,keyword,ot_price,postage,price,(price-ot_price) as commission,sales,slider_image,sort,stock,store_info,store_name,unit_name,vip_price,spec_type,IFNULL(sales,0) + IFNULL(ficti,0) as fsales,video_link,description')
    {
        $Product = self::where('is_del', 0)->where('is_show', 1)->where('id', $productId)->field($field)->find();
        if ($Product) return $Product->toArray();
        else return false;
    }

    public static function getGoodList($limit = 18, $field = '*')
    {
        $list = self::where('is_best', 1)->order('sort desc,id desc')->limit($limit)->field($field)->select();
        $list = count($list) ? $list->toArray() : [];
        return $list;
    }

}
