<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */


namespace app\api\logic;

use app\common\enum\AccountLogEnum;
use app\common\enum\SignEnum;
use app\common\enum\YesNoEnum;
use app\common\logic\AccountLogLogic;
use app\common\logic\BaseLogic;
use app\common\model\SignDaily;
use app\common\model\SignLog;
use app\common\model\User;
use app\common\service\ConfigService;
use app\common\service\FileService;
use think\facade\Db;

/**
 * 签到逻辑层
 * Class SignLogic
 * @package app\shopapi\logic
 */
class SignLogic extends BaseLogic
{
    /**
     * @notes 查看签到列表
     * @param $userId
     * @return array
     */
    public static function lists($userId)
    {
        // 用户信息
        $user = User::field('nickname,avatar,user_money,user_integral')->findOrEmpty($userId)->toArray();
        $user['avatar'] = FileService::getFileUrl($user['avatar']);
        // 先标识用户当天未签到
        $user['today_sign'] = false;
        // 先标识用户连续签到天数为0
        $user['continuous_days'] = 0;
        // 获取昨天签到记录
        $yesterdaySign = SignLog::where('user_id', $userId)->whereDay('create_time', 'yesterday')->findOrEmpty();
        if(!$yesterdaySign->isEmpty()) {
            // 读取连续签到天数
            $user['continuous_days'] = $yesterdaySign['days'];
        }
        // 获取当天签到记录
        $todaySign = SignLog::where('user_id', $userId)->whereDay('create_time')->findOrEmpty();
        if(!$todaySign->isEmpty()) {
            // 标识用户已签到
            $user['today_sign'] = true;
            // 读取连续签到天数
            $user['continuous_days'] = $todaySign['days'];
        }
        // 获取签到规则列表
        $signDailyLists = SignDaily::field('type,days,money,money_status,money_status,points,points_status')->where('type','=',2)->order(['type' => 'asc', 'days' => 'asc'])->select()->toArray();
        $lists =$signDailyLists;
        // dd($signDailyLists);//integral
        // dd($user);
        if(!empty($signDailyLists)) {
            // 格式化列表
            // $lists = self::format($signDailyLists, $user);
        }

        $isOpen = ConfigService::get('sign', 'is_open', YesNoEnum::NO);
        $earn = [];
        if ($isOpen && $signDailyLists) {
            // 赚积分
            $earn = [
                'name' => '每日签到',
                'is_done' => $user['today_sign'],
                'money' => SignDaily::field('type,days,money,money_status')->where('type','=',1)->where('money_status','=',1)->value('money'),
                'points' => SignDaily::field('type,days,money,money_status,points,points_status')->where('type','=',1)->where('points_status','=',1)->value('points'),
                'icon' => FileService::getFileUrl('resource/image/shopapi/default/sign.png')
            ];
        }
        return [
            'user' => $user,
            'lists' => $lists,
            'earn' => $earn,
            'is_open' => $isOpen,
        ];
    }


    /**
     * @notes 签到
     * @param $userId
     * @return bool
     */
    public static function sign($userId,$params)
    {
        Db::startTrans();
        try {
            $isOpen = ConfigService::get('sign', 'is_open', YesNoEnum::YES);
            if(!$isOpen) {
                throw new \think\Exception('系统已关闭签到功能');
            }
            // 判断是否已签到
            $signLog = SignLog::where('user_id', $userId)->whereDay('create_time')->findOrEmpty();
            if(!$signLog->isEmpty()) {
                throw new \think\Exception('今天已签到,请明天再来');
            }
            // 判断是否连续签到
            $continuousDays = 0;
            $yesterdaySignLog = SignLog::where('user_id', $userId)->whereDay('create_time', 'yesterday')->findOrEmpty();
            if(!$yesterdaySignLog->isEmpty()) {
                // 记录已连续签到天数
                $continuousDays = $yesterdaySignLog['days'];
            }
            // 计算金币赠送数量
            $dailySign = SignDaily::order(['type' => 'asc', 'days' => 'asc'])->column('*', 'days');
            // dd($dailySign);
            if(empty($dailySign)) {
                // 每日签到赠送金币
                $money = 0;
                // 连续签到赠送金币
                $continuousMoney = 0;

                // 每日签到赠送积分
                $points = 0;
                // 连续签到赠送积分
                $continuousPoints = 0;
            }
            // 首次签到
            if($continuousDays == 0) {
                $money = isset($dailySign[1]) &&  $dailySign[1]['money_status'] ? $dailySign[1]['money'] : 0;
                $continuousMoney = 0;

                $points = isset($dailySign[1]) &&  $dailySign[1]['points_status'] ? $dailySign[1]['points'] : 0;
                $continuousPoints = 0;
            } else { // 连续签到
                $money = isset($dailySign[1]) &&  $dailySign[1]['money_status'] ? $dailySign[1]['money'] : 0;
                $continuousMoney = isset($dailySign[$continuousDays + 1]) && $dailySign[$continuousDays + 1]['money_status'] ? $dailySign[$continuousDays + 1]['money'] : 0;

                $points = isset($dailySign[1]) &&  $dailySign[1]['points_status'] ? $dailySign[1]['points'] : 0;
                $continuousPoints = isset($dailySign[$continuousDays + 1]) && $dailySign[$continuousDays + 1]['points_status'] ? $dailySign[$continuousDays + 1]['points'] : 0;
            }
            if($money == 0) {
                throw new \think\Exception('无赠送金币');
            }
            if($points == 0) {
                throw new \think\Exception('无赠送积分');
            }
            // 获取最大连续签到天数
            $maxDays = SignDaily::max('days');
            $continuousDays = $continuousDays >= $maxDays ? 0 : $continuousDays;
            $data = [
                'days' => $continuousDays + 1,
                'user_id' => $userId,
                'money' => $money,
                'continuous_money' => $continuousMoney,
                'points' => $points,
                'continuous_points' => $continuousPoints
            ];
            if(isset($params['emote_id'])) {
                $data['emote_id'] = $params['emote_id'];
            }
            if (isset($params['emote_text'])) {
                $data['emote_text'] = $params['emote_text'];
            }
            $signLog = SignLog::create($data);
            // 增加用户积分
            $user = User::findOrEmpty($userId);
            $user->user_money = $user->user_money + $money + $continuousMoney;
            $user->user_integral = $user->user_integral + $points + $continuousPoints;
            $user->save();
            // 记录积分流水
            $remark = $continuousDays == 0 ? '每日签到' : '连续签到' . ($continuousDays + 1) . '天';
            AccountLogLogic::add($userId, AccountLogEnum::BW_INC_SIGN, AccountLogEnum::INC, ($money + $continuousMoney), '', $remark);

            Db::commit();
            return [
                'total_money' => $money + $continuousMoney,
                'days' => $continuousDays + 1
            ];
        } catch(\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
}