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

namespace app\api\service\ucenter;

use app\common\exception\BaseException;
use app\api\model\users\UsersCoupon as UsersCouponModel;
use app\common\service\Users as UsersService;

/**
 * @package app\api\service\ucenter
 * @class Coupon
 * @author xzncit 2024-03-03
 */
class Coupon {

    /**
     * @param array $params
     * @return array
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList($params=[]){
        $array = [
            "total" => 0,
            "list"  => [],
            "size"  => 10
        ];

        $fields = ["active",[
            "active" => intval($params["active"]??'0')
        ]];

        $condition = [];
        $condition[] = ["users_coupon.user_id","=",UsersService::get("id",0)];
        $page  = $params["page"]??1;
        $count = UsersCouponModel::withSearch(...$fields)->withJoin("coupon")->where($condition)->count();
        $array["list"] = UsersCouponModel::withSearch(...$fields)->withJoin("coupon")->where($condition)->order('users_coupon.id','desc')->page($page,$array["size"])->select()->map(function($value){
            $coupon = $value["coupon"];

            $amount = $coupon["reduce_price"];
            if($coupon["type"] == 2){
                $amount = number_format(($coupon["discount"] / 100) * 10,1);
            }

            $result = [
                "id"            => $coupon["id"],
                "name"          => $coupon["name"],
                "type"          => $coupon["type"],
                "expire_type"   => $coupon["expire_type"],
                "amount"        => $amount,
                "order_amount"  => $coupon["order_amount"],
                "status"        => 1,
                "time"          => date("Y-m-d",$value["end_time"])
            ];

            return $result;
        });

        $array["total"] = ceil($count / $array["size"]);
        if($array["total"] == $page -1){
            throw new BaseException("没有数据了哦！",-1,$array);
        }

        return $array;
    }

}