<?php

namespace app\controller\api;

use app\exception\RepositoryException;
use app\model\Account;
use app\repository\AccountRepository;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\response\Json;

class Sign extends Base
{
    protected $noNeedLogin = [];


    /**
     * 签到页面加载
     * */
    public function miniLoad()
    {
        Config::load('extra/base', 'base');
        $baseConfig = config('base');
        $score = isset($baseConfig['sign_score']) ? abs($baseConfig['sign_score']) : 1;

        $userId = $this->request->user['user_id'] ?? 0;
        if ($userId == 0) {
            return $this->json(6001, "请先登录");
        }

        $account = Account::findOne(["id" => $userId], []);
        if (empty($account)) {
            return $this->json(6001, "请先登录");
        }

        //更新连续签到次数
        AccountRepository::getInstance()->checkContinuitySign($account);

        $weekDate = getLatelyWeekDate();

        $weedSignInOnlineRecord = AccountRepository::getInstance()->weedSignInOnlineRecord($userId, $weekDate["1"]["date"], strtotime($weekDate["7"]["date"]) + 86399);

        foreach ($weedSignInOnlineRecord as $item) {
            $w = date("w", strtotime($item['created_at']));
            if ($w == 0) {
                $weekDate["1"]["record"] = $item["score"];
            } else {
                $weekDate[$w]["record"] = $item["score"];
            }
            $weekDate[$w]['is_sign'] = AccountSignOnline::COMMON_ON;//当天是否签到
        }
        $todaySignIn = AccountSignOnline::COMMON_OFF;
        foreach ($weekDate as &$item) {

            $key = date("m.d", strtotime($item['date']));
            if (!isset($item['record'])) {
                $item['record'] = $score;
                $item['is_sign'] = AccountSignOnline::COMMON_OFF;//当天是否签到
            }

            if ($key == date("m.d")) {
                $key = "今天";

                if ($item['is_sign'] == AccountSignOnline::COMMON_ON) {
                    $todaySignIn = AccountSignOnline::COMMON_ON;
                }
            } elseif ($key == (date("m.d", strtotime("+1 day")))) {
                $key = "明天";
            }
            $item["key"] = $key;


        }

        return $this->json(0, "操作成功", [
            "sign_record" => $weekDate,
            "reward_score" => $score,
            "user_score" => $account['score'],
            "today_sign_in" => $todaySignIn,
        ]);
    }

    /**
     * 签到记录
     * */

    public function onlineSignRecord()
    {
        $userId = $this->request->user['user_id'] ?? 0;
        if ($userId == 0) {
            return $this->json(6001, "请先登录");
        }

        $page = input("page/d", 1);
        $size = input("size/d", 10);

        $record = AccountRepository::getInstance()->onlineSignRecordList($userId, $page, $size);
        if ($record->isEmpty()) {
            return $this->json(4001, "没有更多");
        }
        return $this->json(0, "ok", $record);
    }

    /**
     * 线上签到
     * */
    public function onlineSingIn(): Json
    {
        //检查是否已经签到
        $userId = $this->request->user['user_id'] ?? 0;
        if ($userId == 0) {
            return $this->json(6001, "请先登录");
        }

        $check = AccountRepository::getInstance()->checkSignInOnline($userId);
        if ($check) {
            return $this->json(4003, "今天已经签到了,请明天再来");
        }
        $account = Account::findOne(["id" => $userId], [], function ($q) {
            return $q->lock(true);
        });
        if (empty($account)) {
            return $this->json(6001, "请先登录");
        }

        //更新连续签到次数
        AccountRepository::getInstance()->checkContinuitySign($account);

        Config::load('extra/base', 'base');
        $baseConfig = config('base');
        $score = isset($baseConfig['sign_score']) ? abs($baseConfig['sign_score']) : 1;

        Db::startTrans();
        try {
            AccountRepository::getInstance()->SignInOnline($account, $score);
            Db::commit();
            return $this->json();
        } catch (Exception $e) {
            Db::rollback();
            $this->json(4003, "签到失败");
        } catch (RepositoryException $e) {
            Db::rollback();
            $this->json(4003, "签到失败");
        }

    }


    /**
     * 线下签到
     * */
    public function SingIn(): Json
    {
        //检查是否已经签到
        $userId = $this->request->user['user_id'] ?? 0;
        if ($userId == 0) {
            return $this->json(6001, "请先登录");
        }

        $check = AccountRepository::getInstance()->checkSignIn($userId);
        if ($check) {
            return $this->json(4003, "今天已经签到了,请明天再来");
        }
        Db::startTrans();
        try {
            AccountRepository::getInstance()->SignIn($userId);
            Db::commit();
            return $this->json();
        } catch (RepositoryException $e) {
            Db::rollback();
            $this->json(4003, "签到失败");
        } catch (Exception $e) {
            Db::rollback();
            $this->json(5000, "签到失败");
        }
    }

}