<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\api\service\diy\widget;

use app\common\library\utils\Image;
use app\common\model\goods\Goods as GoodsModel;

/**
 * @package app\api\service\diy\widget
 * @class Goods
 * @author xzncit 2024-03-07
 */
class Goods {

    /**
     * 返回组件数据
     * @param $value
     * @return mixed
     */
    public function getData($value){
        if($value["type"] == 1){
            $value["list"] = $this->getGoods($value["list"]);
        }else{
            $value["list"] = $this->getCategoryGoodsList($value["group"]);
        }

        unset($value["group"]);
        return $value;
    }

    protected function getGoods($data){
        $array = [];
        foreach($data as $key=>$value){
            $array[$key] = [
                "name"          => $value["name"],
                "sell_price"    => $value["sell_price"],
                "image"         => Image::thumb(Image::parseUrl($value["image"]),["prefix"=>"medium"]),
                "link"          => [
                    "path"  => $value["link"]["path"] ?? ""
                ]
            ];
        }

        return $array;
    }

    protected function getCategoryGoodsList($data){
        $condition = [];
        if(!empty($data["id"])){
            $result      = getCategoryChildren(["pid"=>$data["id"]]);
            $result[]    = $data["id"];
            $condition[] = ["pid","in",$result];
        }

        $goods = GoodsModel::where($condition)->limit($data["limit"]??20)->select()->toArray();
        $array = [];
        foreach($goods as $key=>$value){
            $array[$key] = [
                "name"          => $value["title"],
                "sell_price"    => $value["sell_price"],
                "image"         => Image::thumb(Image::parseUrl($value["photo"]),["prefix"=>"medium"]),
                "link"          => [
                    "path"  => "/pages/goods/view?id=" . $value["id"]
                ]
            ];
        }

        return $array;
    }

}