<?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\adminapi\model\promotion\Bargain as BargainModel;
use app\adminapi\model\promotion\BargainUsers as BargainUsersModel;
use app\common\model\promotion\BargainUsersHelp as BargainUsersHelpModel;

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

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

    /**
     * 帮助列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getUsersList($params){
        $array           = [];
        $fields          = ["active",["active"=>$params["active"]??0]];
        $array["total"]  = BargainUsersModel::withSearch(...$fields)->withJoin(["bargain","goods"])->count();
        $array["list"]   = BargainUsersModel::withSearch(...$fields)->withJoin(["bargain","goods"])->order("bargain_users.id","desc")->page($params["current"]??1,$params["size"]??10)->select()->map(function ($res){
            $total                  = BargainUsersHelpModel::where("bargain_id",$res["bargain_id"])->count();
            $people_num             = $res["bargain"]["people_num"];
            if($total > $people_num) {
                $surplus_count = 0;
            }else{
                $surplus_count = $people_num - $total;
            }

            $res["username"]        = getUserName($res["user_id"]);
            $res["photo"]           = Image::thumb($res["photo"]);
            $res["total"]           = $total;
            $res["surplus_count"]   = $surplus_count;
            return $res;
        });

        $array["count"]   = [
            "0" => BargainUsersModel::count(),
            "1" => BargainUsersModel::where("status",1)->count(),
            "2" => BargainUsersModel::where("status",2)->count(),
            "3" => BargainUsersModel::where("status",3)->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){
        $array  = BargainModel::where("id",$id)->find();
        if(empty($array)){
            return [];
        }

        $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;
            });
        }

        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){
        $peopleNum = bcmul(bcsub((string)$params['price'], (string)$params['min_price'], 2), '100');
        if ($params['people_num'] > $peopleNum) {
            throw new \Exception('砍价人数不能大于' . $peopleNum . '人');
        }

        if($params['min_price'] < 0 || $params['price'] <= 0 || $params['min_price'] === '' || $params['price'] === '') {
            throw new \Exception('金额不能小于0');
        }

        if($params['min_price'] >= $params['price']) {
            throw new \Exception('砍价最低价不能大于或等于起始金额');
        }

        if($params['quota'] > $params['store_nums']) {
            throw new \Exception('限量不能超过商品库存');
        }

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

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

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

        return true;
    }

}