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

namespace app\adminapi\service\promotion;

use think\facade\Request;
use app\adminapi\model\promotion\Second as SecondModel;
use app\common\model\promotion\SecondGoods as SecondGoodsModel;
use app\common\exception\BaseException;
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\common\service\Config as ConfigService;
use app\common\library\utils\Image;

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

    /**
     * 列表
     * @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"]  = SecondModel::withSearch(...$fields)->count();
        $array["list"]   = SecondModel::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  = SecondModel::where("id",$id)->find();
        $time   = ConfigService::getArray("second",[]);
        if(empty($array)){
            return ["time"=>$time];
        }

        $array["time"]  = $time;
        $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"]   = SecondGoodsModel::where("pid",$array["id"]??0)->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;
        });

        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){
        SecondModel::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"]) && SecondModel::where("id",$params["id"])->find()){
                $params["update_time"] = time();
                SecondModel::where("id",$params["id"])->save($params);
            }else{
                $params["create_time"] = time();
                $params["id"] = SecondModel::create($params)->id;
            }

            if(!empty($params["products"])){
                $goodsItem = [];
                SecondGoodsModel::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"]
                    ];
                }

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

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

        return true;
    }

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

        $list  = $params['list'];
        $array = [];
        foreach($list as $key=>$value){
            $array[$key] = [
                "open_time" => isset($value["open_time"]) ? $value["open_time"] : "",
                "duration"  => isset($value["duration"]) ? $value["duration"] : ""
            ];

            if(empty($array[$key]["open_time"])){
                throw new \Exception("请填写开启时间",0);
            }

            if (!preg_match('/^(\d|1\d|2[0-3])$/', $array[$key]["open_time"])) {
                throw new \Exception("请输入0-23点之前的整点数",0);
            }

            if(empty($array[$key]["duration"])){
                throw new \Exception("请填写开持续时间",0);
            }

            if (!preg_match('/^([1-9]|1\d|2[0-4])$/',$array[$key]["duration"])) {
                throw new \Exception("请输入1-24点之前的持续时间",0);
            }

            if(($array[$key]["open_time"] + $array[$key]["duration"]) > 24) {
                throw new \Exception("开始时间+持续时间不能大于24小时",0);
            }

        }

        $times = [];
        foreach($array as $item) {
            for($i = 0; $i < $item['duration']; $i++) {
                $times[] = $item['open_time'] + $i;
            }
        }

        if(count($times) != count(array_unique($times))){
            throw new \Exception("您填写的时间段包含已被占用的时间段",0);
        }

        return ConfigService::save("second",$array);
    }

}