<?php

namespace app\workerapi\lists\shops;

use app\common\enum\YesNoEnum;
use app\common\lists\ListsSearchInterface;
use app\common\model\shops\ShopGoods;
use app\workerapi\lists\BaseWorkerDataLists;
use think\db\Query;

class ShopGoodLists extends BaseWorkerDataLists implements ListsSearchInterface
{
    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/07/07 18:23
     */
    public function setSearch(): array
    {
        return [
            '=' => ['goods_category_id', 'goods_status','is_recommend'],
            '%like%' => ['goods_name'],
        ];
    }

    public function lists(): array
    {
        record_sql();
        $lists = ShopGoods::with(['goodSpecsInventory'=>function(Query $query){
            $query->field(['id','shop_goods_id','remaining_inventory','service_fee','service_total']);
        }])
            ->where($this->searchWhere)
            ->field(['id', 'delivery_type' ,'shop_goods_type', 'goods_name','goods_category_id','company_name','goods_image','goods_banners'])
            ->when(isset($this->params['is_recommend']) && $this->params['is_recommend'],function (Query $query){
                $query->order('is_recommend','desc');
            })
            ->where('goods_status',YesNoEnum::YES)
            ->append(['delivery_type_text','shop_goods_type_text'])
            ->order('id','desc')
            ->select()
            ->each(function($item){
                $item['remaining_inventory'] =(int) $item->goodSpecsInventory()->sum('remaining_inventory');
                $item['service_fee'] = $item->goodSpecsInventory()->min('service_fee');
                $serviceItem = $item->goodSpecsInventory()->where('service_fee',$item['service_fee'])->find()->toArray();
                $item['service_total'] = floatval($serviceItem['service_total'] ?? 0);
                unset($item['goodSpecsInventory']);
            })
            ->toArray();

        return $lists;
    }

    public function count(): int
    {
        return ShopGoods::where($this->searchWhere)->where('goods_status',YesNoEnum::YES)->count();
    }
}