<?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 think\facade\Request;
use app\common\service\Config as ConfigService;
use app\adminapi\model\promotion\Point as PointModel;
use app\common\model\promotion\PointGoods as PointGoodsModel;
use app\common\model\users\UsersPointLog as UsersPointLogModel;

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

    /**
     * 列表
     * @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"]  = PointModel::withSearch(...$fields)->count();
        $array["list"]   = PointModel::withSearch(...$fields)->order("id","desc")->page($params["current"]??1,$params["size"]??10)->select()->toArray();
        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){
        $array = PointModel::where("id",$id)->find();
        if(empty($array)){
            return $array??[];
        }

        $array["goods"] = [];
        if(!empty($array["goods_id"])){
            $array["goods"] = GoodsModel::field("id,title,sell_price,store_nums,photo")->where("id",$array["goods_id"])->select()->map(function ($res){
                $res["photo"] = Image::thumb($res["photo"]);
                return $res;
            });
        }

        $array["products"]   = PointGoodsModel::where("pid",$array["id"])->select()->map(function ($res){
            $array = explode(",",$res["spec_value"]);

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

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

        $array["start_time"] = date("Y-m-d H:i:s",$array["start_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){
        PointModel::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"]) && PointModel::where("id",$params["id"])->find()){
                $params["update_time"] = time();
                PointModel::where("id",$params["id"])->save($params);
            }else{
                $params["create_time"] = time();
                $params["id"] = PointModel::create($params)->id;
            }

            if(!empty($params["products"])){
                $goodsItem = [];
                PointGoodsModel::where("pid",$params["id"])->delete();
                foreach($params["products"] as $value){
                    $goodsItem[] = [
                        "pid"           => $params["id"],
                        "goods_id"      => $value["goods_id"],
                        "sku_id"        => $value["sku_id"],
                        "spec_value"    => $value["spec_value"],
                        "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"],
                        "thumb_image"   => $value["thumb_image"],
                        "status"        => $value["status"],
                        "point"         => $value["point"]
                    ];
                }

                PointGoodsModel::insertAll($goodsItem);
            }
        });
        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) ];
        PointModel::where("id",$params["id"]??0)->save($data);
        return true;
    }

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

        return true;
    }

    /**
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getLog($params=[]){
        $array           = [];
        $array["total"]  = UsersPointLogModel::count();
        $array["list"]   = UsersPointLogModel::order("id","desc")->page($params["current"]??1,$params["size"]??10)->select()->map(function ($res){
            $res["username"] = getUserName($res["user_id"]);
            return $res;
        });
        return $array;
    }

    /**
     * 设置
     * @param array $params
     * @return array|bool|mixed|null
     * @throws \think\db\exception\DbException
     */
    public static function setting($params=[]){
        if(Request::isPost()){
            return ConfigService::save("point",$params);
        }

        return ConfigService::getArray("point",[]);
    }

}