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

namespace app\adminapi\service\shop;

use app\common\service\Config as ConfigService;
use app\common\library\utils\Image;
use app\common\model\goods\GoodsItem as GoodsItemModel;
use app\common\model\goods\GoodsImage as GoodsImageModel;
use app\common\model\goods\Attribute as AttributeModel;
use app\common\model\goods\Spec as SpecModel;
use app\common\model\goods\SpecValue as SpecValueModel;
use app\common\model\Category as CategoryModel;
use app\adminapi\model\shop\Goods as GoodsModel;
use app\adminapi\model\shop\Brand as BrandModel;
use app\common\model\goods\Distribution as DistributionModel;

/**
 * @package app\adminapi\service\shop
 * @class Goods
 * @author xzncit 2024-02-15
 */
class Goods {

    public static function getDiyList($params=[]){
        $condition = [];
        if(!empty($params["id"])){
            $condition[] = ["cat_id","=",$params["id"]];
        }
        $result = GoodsModel::where($condition)->limit($params["limit"]??20)->select()->toArray();
        $array = [];
        foreach($result as $value){
            $array[] = [
                "name"          => $value["title"],
                "image"         => Image::thumb($value["photo"]),
                "sell_price"    => $value["sell_price"]
            ];
        }

        return $array;
    }

    /**
     * 列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList($params){
        $array            = ["total"=>0,"list"=>[]];
        $fields           = ["title,active",["title"=>$params["keywords"]??'',"active"=>$params["active"]??0]];
        $array["total"]   = GoodsModel::withSearch(...$fields)->count();
        $array["list"]    = GoodsModel::withSearch(...$fields)->order("id","desc")->page($params["current"]??1,$params["size"]??10)->select()->map(function ($res){
            $res["photo"] = Image::thumb($res["photo"]);
            return $res;
        });

        $array["count"]   = [
            "0" => GoodsModel::count(),
            "1" => GoodsModel::where("status",0)->count(),
            "2" => GoodsModel::where("status",1)->count()
        ];

        return $array;
    }

    /**
     * 详情
     * @param $id
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detail($id){
        $goods = GoodsModel::where("id",$id)->find();
        if(!empty($goods)){
            if(!empty($goods["cat_id"])){
                $category = CategoryModel::where("id",$goods["cat_id"])->find();
                $goods["cat_id"] = !empty($category["path"]) ? array_map("intval",explode(",",$category["path"])) : [$goods["cat_id"]];
            }

            $image = GoodsImageModel::where("goods_id",$id)->select()->map(function ($res){
                return [
                    "photo"=>Image::thumb($res["path"])
                ];
            });

            $goods["content"] = Image::replace(Image::removeAttribute($goods["content"]),function($path,$content){
                return str_replace($path, Image::thumb($path), $content);
            });

            $attribute = AttributeModel::where("goods_id",$id)->select()->toArray();

            $spec = SpecModel::where("goods_id",$id)->order("id","ASC")->select()->map(function ($res){
                $array = [
                    "id"        => $res["id"],
                    "name"      => $res["name"],
                    "goods_id"  => $res["id"],
                    "children"  => []
                ];

                $specValue = SpecValueModel::where("spec_id",$res["id"])->select()->toArray();
                foreach($specValue as $key=>$value){
                    $array["children"][$key] = [
                        "id"          => $value["id"],
                        "goods_id"    => $value["goods_id"],
                        "spec_id"     => $value["spec_id"],
                        "value"       => $value["value"],
                        "thumb_image" => $value["thumb_image"],
                    ];
                }

                return $array;
            });

            $skuList = GoodsItemModel::where("goods_id",$id)->select()->map(function ($res){
                $array = explode(",",$res["spec_value"]);

                $spec = [];
                foreach($array as $k=>$item){
                    $value = explode(":",$item);
                    $spec[] = SpecValueModel::where(["spec_id"=>$value[0],"id"=>$value[1]])->value("value","");
                }

                $res["value"] = $spec;
                return $res;
            });
        }

        return [
            "goods"        => $goods,
            "image"        => $image??[],
            "attribute"    => $attribute??[],
            "spec"         => $spec??[],
            "sku_list"     => $skuList??[],
            "brand"        => BrandModel::where("status",1)->select()->toArray(),
            "distribution" => DistributionModel::where("status",1)->select()->toArray(),
            "unit"         => array_map(function ($res){
                return ["value"=>$res];
            },explode(",",ConfigService::getArray("goods.unit","件")))
        ];
    }

    /**
     * 保存
     * @param $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function save($data){
        $data["cat_id"]  = end($data["cat_id"]);
        $data["photo"]   = Image::parseUrl($data["photo"]??"");
        $data["content"] = Image::replace($data["content"],function ($path,$content){
            return str_replace($path, Image::parseUrl($path), $content);
        });

        if($data["sku_type"] == 2){
            $goods = current($data["goods_item"]);
            $data["goods_number"]     = $goods["goods_number"]??"";
            $data["sell_price"]       = GoodsModel::getGoodsPrice($data["goods_item"],"sell_price")[0];
            $data["market_price"]     = $goods["market_price"]??"";
            $data["cost_price"]       = $goods["cost_price"]??"";
            $data["goods_weight"]     = $goods["goods_weight"]??"";
            $data["store_nums"]       = $goods["store_nums"]??"";
        }

        GoodsModel::transaction(function () use($data){
            if(!empty($data["id"]) && GoodsModel::where("id",$data["id"])->find()){
                $data["update_time"] = time();
                GoodsModel::where("id",$data["id"])->save($data);
            }else{
                $data["create_time"] = time();
                if(isset($data["id"])) unset($data["id"]);
                $data["id"] = GoodsModel::create($data)->id;
            }

            // 规格
            if(!empty($data["spec"])){
                $skuID = ["spec_id"=>[],"spec_value_id"=>[]];
                foreach($data["spec"] as $key=>$value){
                    $specId = SpecModel::edit($data["id"],$value);

                    $data["spec"][$key]["spec_id"] = $specId;
                    $skuID["spec_id"][] = $specId;
                    foreach($value["children"] as $val){
                        $skuID["spec_value_id"][] = SpecValueModel::edit($data["id"],$specId,$val);
                    }
                }

                SpecModel::where("goods_id",$data["id"])->whereNotIn("id",$skuID["spec_id"])->delete();
                SpecValueModel::where("goods_id",$data["id"])->whereNotIn("id",$skuID["spec_value_id"])->delete();
            }else{
                SpecModel::where("goods_id",$data["id"])->delete();
                SpecValueModel::where("goods_id",$data["id"])->delete();
            }

            // SKU
            GoodsItemModel::where("goods_id",$data["id"])->delete();
            if(!empty($data["goods_item"])){
                $goodsItem = [];
                foreach($data["goods_item"] as $key=>$item){
                    $goodsItem[$key] = [
                        "goods_id"      => $data["id"],
                        "goods_number"  => $item["goods_number"],
                        "store_nums"    => $item["store_nums"],
                        "market_price"  => $item["market_price"],
                        "sell_price"    => $item["sell_price"],
                        "cost_price"    => $item["cost_price"],
                        "goods_weight"  => $item["goods_weight"],
                        "thumb_image"   => $item["thumb_image"]
                    ];

                    $specValue = [];
                    foreach($item["value"] as $k=>$v){
                        $sv = SpecValueModel::where([
                            ["goods_id","=",$data["id"]],
                            ["spec_id","=",$data["spec"][$k]["spec_id"]??0],
                            ["value","=",$v]
                        ])->find();
                        $specValue[] = $sv["spec_id"] . ':' . $sv["id"];
                    }

                    $goodsItem[$key]["spec_value"] = implode(",",$specValue);
                    $goodsItem[$key]["sku_id"]     = str_replace([",",":"],["",""],$goodsItem[$key]["spec_value"]);
                }

                GoodsItemModel::insertAll($goodsItem);
            }

            // 相册
            GoodsImageModel::where("goods_id",$data["id"])->delete();
            GoodsImageModel::insertAll(array_map(function ($path) use($data){
                return [
                    "goods_id"      => $data["id"],
                    "path"          => Image::parseUrl($path),
                    "create_time"   => time()
                ];
            },$data["image"]));

            // 商品属性
            AttributeModel::where("goods_id",$data["id"])->delete();
            AttributeModel::insertAll(array_map(function($value) use($data){
                return [
                    "goods_id"      => $data["id"],
                    "name"          => $value["name"],
                    "value"         => $value["value"],
                    "create_time"   => time()
                ];
            },$data["params"]));
        });

        return true;
    }

    /**
     * 修改状态
     * @param $id
     * @param $value
     * @return bool
     */
    public static function status($id,$value){
        GoodsModel::where("id","in",is_array($id)?$id:[$id])->save([
            "status"=>$value
        ]);
        return true;
    }

    /**
     * 删除
     * @param $id
     */
    public static function delete($id){
        GoodsModel::transaction(function () use($id){
            $goods = GoodsModel::where("id","in",is_array($id)?$id:[$id])->select()->toArray();
            foreach($goods as $key=>$value){
                AttributeModel::where("goods_id",$value["id"])->delete();
                GoodsImageModel::where("goods_id",$value["id"])->delete();
                GoodsItemModel::where("goods_id",$value["id"])->delete();
                SpecModel::where("goods_id",$value["id"])->delete();
                SpecValueModel::where("goods_id",$value["id"])->delete();
                GoodsModel::where("id",$value["id"])->delete();
            }
        });
    }

    /**
     * 商品设置
     * @param $params
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public static function setting($params){
        return ConfigService::save("goods",$params);
    }

}