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

namespace app\adminapi\service\promotion;

use app\common\exception\BaseException;
use app\common\library\utils\Image;
use app\common\model\goods\Goods as GoodsModel;
use app\common\model\goods\Spec as SpecModel;
use app\common\model\goods\SpecValue as SpecValueModel;
use app\adminapi\model\promotion\Discount as DiscountModel;
use app\common\model\promotion\DiscountGoods as DiscountGoodsModel;
use app\common\model\promotion\DiscountGoodsItem as DiscountGoodsItemModel;

/**
 * @package app\adminapi\service\promotion
 * @class Discount
 * @author xzncit 2024-02-21
 */
class Discount {

    /**
     * 列表
     * @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           = [];
        $fields          = ["title",["title"=>$params["keywords"]??'']];
        $array["total"]  = DiscountModel::withSearch(...$fields)->count();
        $array["list"]   = DiscountModel::withSearch(...$fields)->order("id","desc")->page($params["current"]??1,$params["size"]??10)->select()->toArray();
        return $array;
    }

    public static function detail($id){
        $array = DiscountModel::where("id",$id)->find();
        if(empty($array)){
            return [];
        }

        $array["goods"] = DiscountGoodsModel::where("pid",$array["id"])->select()->map(function ($res){
            $goods = GoodsModel::where("id",$res["goods_id"])->find();
            $res["id"]       = $goods["id"];
            $res["sku_type"] = $goods["sku_type"];
            $res["title"]    = $goods["title"]??"-";
            $res["photo"]    = Image::thumb($goods["photo"]??"");
            $res["products"] = DiscountGoodsItemModel::where("gid",$res["id"])->select()->map(function ($item){
                $array = explode(",",$item["spec_value"]);

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

                $item["value"] = implode(",",$spec);
                return $item;
            });

            return $res;
        });

        if(!empty($array["start_time"])) $array["start_time"] = date("Y-m-d H:i:s",$array["start_time"]);
        if(!empty($array["end_time"])) $array["end_time"]   = date("Y-m-d H:i:s",$array["end_time"]);
        return $array;
    }

    /**
     * 保存
     * @param $params
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function save($params){
        DiscountModel::transaction(function () use($params){
            if(!empty($params["start_time"])) $params["start_time"] = strtotime($params["start_time"]);
            if(!empty($params["end_time"])) $params["end_time"] = strtotime($params["end_time"]);
            if(!empty($params["id"]) && DiscountModel::where("id",$params["id"])->find()){
                $params["update_time"] = time();
                DiscountModel::where("id",$params["id"])->save($params);
            }else{
                $params["create_time"] = time();
                $params["id"] = DiscountModel::create($params)->id;
            }

            DiscountGoodsModel::where("pid",$params["id"])->delete();
            DiscountGoodsItemModel::where("pid",$params["id"])->delete();
            if(!empty($params["goods"])){
                foreach($params["goods"] as $value){
                    $gid = DiscountGoodsModel::create([
                        "pid"           => $params["id"],
                        "goods_id"      => (!empty($value["goods_id"]) ? $value["goods_id"] : $value["id"]),
                        "goods_number"  => $value["goods_number"],
                        "store_nums"    => $value["store_nums"],
                        "market_price"  => $value["market_price"],
                        "sell_price"    => $value["sell_price"],
                        "cost_price"    => $value["cost_price"],
                        "goods_weight"  => $value["goods_weight"]
                    ])->id;
                    if(!empty($value["products"])){
                        $product = [];
                        foreach($value["products"] as $val){
                            $product[] = [
                                "pid"           => $params["id"],
                                "gid"           => $gid,
                                "goods_id"      => $val["goods_id"],
                                "sku_id"        => $val["sku_id"],
                                "spec_value"    => $val["spec_value"],
                                "goods_number"  => $val["goods_number"],
                                "store_nums"    => $val["store_nums"],
                                "market_price"  => $val["market_price"],
                                "sell_price"    => $val["sell_price"],
                                "cost_price"    => $val["cost_price"],
                                "goods_weight"  => $val["goods_weight"],
                                "thumb_image"   => $val["thumb_image"]
                            ];
                        }

                        DiscountGoodsItemModel::insertAll($product);
                    }
                }
            }
        });
        return true;
    }

    /**
     * 修改状态
     * @param $params
     * @return bool
     * @throws BaseException
     */
    public static function status($params){
        if(!in_array($params["type"],["status"])){
            throw new BaseException("error status",0);
        }

        $data = [ $params["type"]=>intval($params["value"]??0) ];
        DiscountModel::where("id",$params["id"]??0)->save($data);
        return true;
    }

    /**
     * 删除
     * @param $id
     * @return bool
     */
    public static function delete($id){
        DiscountModel::transaction(function () use($id){
            DiscountModel::where("id",$id)->delete();
            DiscountGoodsModel::where("pid",$id)->delete();
            DiscountGoodsItemModel::where("pid",$id)->delete();
        });

        return true;
    }

}