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

namespace app\common\model\goods;

use think\Model;

use app\common\model\goods\SpecValue as SpecValueModel;

/**
 * @package app\common\model\goods
 * @class Spec
 * @author xzncit 2024-02-15
 */
class Spec extends Model {

    protected $name = "goods_spec";

    /**
     * @param string $value
     * @return string
     */
    public static function getSpecInfo($value=""){
        if(empty($value)){
            return "";
        }

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

        if(empty($spec)){
            return "";
        }

        return implode(",",$spec);
    }

    /**
     * 添加/修改
     * @param $goods_id
     * @param $value
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function edit($goods_id,$value){
        if(isset($value["id"]) && self::where("id",$value["id"])->find()){
            self::where("id",$value["id"])->save([ "name"=>$value["name"] ]);
            return $value["id"];
        }

        return self::create([
            "goods_id"      => $goods_id,
            "name"          => $value["name"],
            "create_time"   => time()
        ])->id;
    }

}