<?php

namespace app\api\service\ucenter;

use think\facade\Db;
use app\common\exception\BaseException;
use app\common\service\Users as UsersService;
use app\common\model\Users as UsersModel;
use app\common\model\users\UsersSignLog as UsersSignLogModel;
use app\common\model\users\UsersPointLog as UsersPointLogModel;
use app\common\model\promotion\Sign as SignModel;
use app\common\library\utils\Image;

/**
 * @package app\api\service\ucenter
 * @class Sign
 * @author xzncit 2024/3/22
 */
class Sign {

    /**
     * 签到中心
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getData(){
        $user           = UsersService::get();
        $isDay          = UsersSignLogModel::where('user_id', $user["id"])->whereTime("create_time","today")->count();
        $isYesterDay    = UsersSignLogModel::where('user_id', $user["id"])->whereTime("create_time","yesterday")->count();
        $config         = SignModel::where("status",1)->find();
        $config["list"] = !empty($config["list"]) ? json_decode($config["list"],true) : [];
        return [
            "username"      => getUserName($user["id"]),
            "point"         => $user["score"],
            "time"          => strtotime("-1 day"),
            "config"        => $config,
            "avatar"        => Image::avatar($user["avatar"]),
            "is_day"        => $isDay,
            "is_yester_day" => $isYesterDay,
            "sign_count"    => (!$isDay && !$isYesterDay ? 0 : $user["sign_count"]),
            "sing_total"    => UsersSignLogModel::where('user_id',$user["id"])->count()
        ];
    }

    public static function send(){
        $config         = SignModel::where("status",1)->find();
        if($config["status"] == 0){
            throw new BaseException("签到功能已被管理员关闭",0);
        }

        $config["list"] = !empty($config["list"]) ? json_decode($config["list"],true) : [];
        if(count($config["list"]) <= 0){
            throw new BaseException("您还没有配置签到天数，请到后台设置签到相关功能。",0);
        }

        if(UsersSignLogModel::where('user_id', UsersService::get("id",0))->whereTime("create_time","today")->count()){
            throw new BaseException("您已签到",0);
        }

        $users = UsersModel::where("id",UsersService::get("id",0))->find();
        $point = 0;

        // 检查昨天是否签到
        if(UsersSignLogModel::where('user_id', UsersService::get("id",0))->whereTime("create_time","yesterday")->count()){
            if($users["sign_count"] > (count($config["list"]) -1)) {
                $users["sign_count"] = 0;
            }
        }else{
            $users["sign_count"] = 0;
        }

        foreach ($config["list"] as $key=>$item){
            if($users["sign_count"] == $key){
                $point = $item['point'];
                break;
            }
        }

        $users["sign_count"] += 1;
        $text = "签到奖励";
        if($users["sign_count"] == count($config["list"])){
            $text = "连续签到奖励";
        }

        try{
            UsersModel::startTrans();
            UsersModel::where('id', UsersService::get("id"))->save([
                "sign_count" => $users["sign_count"],
                "score"      => Db::raw("score+" . $point)
            ]);

            UsersPointLogModel::create([
                "user_id"       => UsersService::get("id"),
                "type"          => 1,
                "value"         => $point,
                "content"       => $text,
                "create_time"   => time()
            ]);

            UsersSignLogModel::create([
                "user_id"       => UsersService::get("id"),
                "description"   => $text,
                "point"         => $point,
                "create_time"   => time()
            ]);

            UsersModel::commit();
            return [
                "sign_count"    => $users["sign_count"],
                "point"         => UsersModel::where('id', UsersService::get("id"))->value("score")
            ];
        }catch (\Exception $ex){
            UsersModel::rollback();
            throw new BaseException($ex->getMessage());
        }
    }

}