<?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\service\Config as ConfigService;
use think\facade\Request;
use app\adminapi\model\order\Recharge as RechargeModel;

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

    /**
     * 充值订单
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getOrderList($params=[]){
        $array           = [];
        $fields          = ["title",["title"=>$params["keywords"]??'']];
        $array["total"]  = RechargeModel::withSearch(...$fields)->count();
        $array["list"]   = RechargeModel::withSearch(...$fields)->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::getArray("recharge",[]);
        }

        $list  = $params['list'];
        $array = [];
        $price = [];
        foreach($list as $key=>$value){
            $array[$key] = [
                "order_amount" => isset($value["order_amount"]) ? (int)$value["order_amount"] : 0,
                "price"        => isset($value["price"]) ? (int)$value["price"] : 0
            ];

            $price[] = $array[$key]["order_amount"];
            if(empty($array[$key]["order_amount"])){
                throw new \Exception("请填写充值金额",0);
            }
        }

        if(count($price) != count(array_unique($price))){
            throw new \Exception("设置抢购，充值金额包含相同金额",0);
        }

        $params['list'] = $array;
        return ConfigService::save("recharge",$params);
    }

}