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

namespace app\api\service\promotion;

use app\common\library\jwt\Token;
use app\common\model\promotion\Coupon as CouponModel;
use app\common\model\users\UsersCoupon as UsersCouponModel;
use app\common\service\Users as UsersService;
use app\common\exception\BaseException;

/**
 * @package app\api\service\promotion
 * @class Coupon
 * @author xzncit 2024-03-04
 */
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
        ];

        $page  = $params["page"]??1;
        $count = CouponModel::where(["status"=>1,"push_type"=>1])->count();
        $array["list"] = CouponModel::where(["status"=>1,"push_type"=>1])->page($page,$array["size"])->order('id','desc')->select()->map(function ($value){
            $status = 1; // 待领取
            $nowTime = time();
            if($value["expire_type"] == 2 && $nowTime > $value["end_time"]){
                $status = 3; // 已过期
            }

            if(Token::isAuth() && UsersCouponModel::where(["coupon_id"=>$value["id"],"user_id"=>Token::get("id")])->find()){
                $status = 2; // 已领取
            }

            if($value["expire_type"] == 2){
                $time = date("Y-m-d",$value["end_time"]);
            }else if($value["expire_type"] == 1){
                $time = $value["expire_day"];
            }

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

            $result = [
                "id"            => $value["id"],
                "name"          => $value["name"],
                "type"          => $value["type"],
                "expire_type"   => $value["expire_type"],
                "amount"        => $amount,
                "order_amount"  => $value["order_amount"],
                "status"        => $status,
                "time"          => $time
            ];

            return $result;
        });

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

        return $array;
    }

    /**
     * 领券
     * @param $id
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function receive($id){
        $coupon = CouponModel::where(["id"=>$id,"status"=>1,"push_type"=>1])->find();
        if(empty($coupon)){
            throw new \Exception("您要领取的优惠券不存在",0);
        }

        $nowTime = time();
        if($coupon["expire_type"] == 2 && $nowTime >= $coupon["end_time"]){
            throw new \Exception("您要领取的优惠券已过期",0);
        }

        if($coupon["total_num"] != '-1' && $coupon["receive_num"] >= $coupon["total_num"]){
            throw new \Exception("您要领取的优惠券已被领完",0);
        }

        if(UsersCouponModel::where(["coupon_id"=>$coupon["id"],"user_id"=>UsersService::get("id",0)])->find()){
            throw new \Exception("您已领取该优惠券",0);
        }

        if($coupon["expire_type"] == 1){
            $start_time = $coupon["create_time"];
            $end_time   = strtotime(date("Y-m-d H:i:s") . " +" . $coupon["expire_day"] . " day");
        }else{
            $start_time = $coupon["start_time"];
            $end_time   = $coupon["end_time"];
        }

        UsersCouponModel::create([
            "user_id"       => Token::get("id"),
            "coupon_id"     => $coupon["id"],
            "status"        => 0,
            "start_time"    => $start_time,
            "end_time"      => $end_time,
            "create_time"   => time()
        ]);

        return true;
    }

}