<?php
namespace app\api\controller;

use support\Request;
use support\Response;
use app\model\UserSignin as UserSigninModel;
use app\model\UserXuanchuan as UserXuanchuanModel;
use support\Jwt\JwtToken;
use Shopwwi\WebmanFilesystem\FilesystemFactory;
use Shopwwi\WebmanFilesystem\Facade\Storage;
use hg\apidoc\annotation as Apidoc;
/**
 * 签到模块
 */

class SigninController extends BaseController
{
    /**
     * 不需要鉴权的方法
     * @var array
     */
    public $noNeedAuth = ['*'];
    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    public $noNeedLogin = [];
    /**
     * 列表
     * @Apidoc\Query("status", type="int", require=true, desc="状态")
     * @Apidoc\Query("page", type="int", require=true, desc="页码",default=1)
     * @Apidoc\Query("limit", type="int", require=true, desc="分页大小",default=10)
     */
    public function list(){
        $limit = (int)input('limit',10);
        $status = (int)input('status');

        $model = UserXuanchuanModel::where('id','>',0);
        if($status && $status!='all'){
            $model = $model->where('status',$status);
        }
        $list = $model->order('id','desc')->paginate($limit);
        return $this->success(__('successful'),$list);

    }
    /**
     * @Apidoc\Title("用户签到")
     * @Apidoc\Method("GET")
     */
    public function info(Request $request)
    {
        $user_id = JwtToken::getCurrentId();
        if (!$user_id) {
            return $this->error(__('Please login first'));
        }
        /** @var UserSigninModel $last */
        $last = UserSigninModel::where('user_id', $user_id)->order('id','desc')->find();
        return $this->success(__('successful'),[
            'continuous_days' 	=>	$last->continuous_days,
            'last_day' 			=>	$last->sign_date,
            'signed' 			=>	$last->sign_date == date('Y-m-d'),
            'invite_complete'	=>	cache('invite_'.$user_id.'_'.date('Ymd')),
            'pyq_complete'		=>	UserXuanchuanModel::where('user_id',$user_id)->where('type','pyq')->whereTime('created_at','today')->count() > 0,
            'group_complete'	=>	UserXuanchuanModel::where('user_id',$user_id)->where('type','group_complete')->whereTime('created_at','today')->count() > 0,
            'signinList'    	=>	[20,20,20,20,20,20,100]
        ]);

    }
    /**
     * @Apidoc\Title("用户签到")
     * @Apidoc\Method("GET")
     */
    public function sign(Request $request)
    {
        $user = JwtToken::getUser();
        if (!$user->realname_verify) {
            return $this->error(__('Please complete real-name verification first'));
        }
        $user_id = $user->id;
        $today = date('Y-m-d');
        // 检查今天是否已签到
        if (UserSigninModel::where('user_id', $user_id)->where('sign_date', $today)->find()) {
            return $this->error(__('今日已签到'));
        }

        // 检查昨天是否签到
        $continuous_days = UserSigninModel::where('user_id', $user_id)->count('id');
        $continuous_days = $continuous_days ? ($continuous_days + 1) : 1;
        // 奖励规则（可自定义/读取配置/数据库）
        $reward = $this->getReward($continuous_days);

        // 写入签到记录
        UserSigninModel::create([
            'user_id' => $user_id,
            'sign_date' => $today,
            'reward' => $reward,
            'continuous_days' => $continuous_days,
        ]);

        // 发放奖励（如积分、余额等）
        \app\model\User::currency1($user_id, $reward, \app\enum\BalanceType::SIGNIN);
        
        return $this->success(__('successful'),[
            'reward' => $reward, 
            'continuous_days' => $continuous_days
        ]);
    }

    /**
     * @Apidoc\Title("查询签到状态")
     * @Apidoc\Method("GET")
     */
    public function status(Request $request)
    {
        $user_id = JwtToken::getCurrentId();
        if (!$user_id) {
            return $this->error(__('Please login first'));
        }
        $today = date('Y-m-d');
        $record = UserSigninModel::where('user_id', $user_id)->where('sign_date', $today)->find();
        $continuous_days = UserSigninModel::where('user_id', $user_id)->order('id','desc')->value('continuous_days');
        return $this->success(__('successful'),[
            'signed' => !!$record,
            'continuous_days' => $continuous_days ?: 0,
        ]);
    }

    /**
     * @Apidoc\Title("查询签到记录")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("page", type="int", require=true, desc="页码",default=1)
     * @Apidoc\Query("limit", type="int", require=true, desc="分页大小",default=10)
     */
    public function records(Request $request)
    {
        $user_id = JwtToken::getCurrentId();
        if (!$user_id) {
            return $this->error(__('Please login first'));
        }
        $limit = (int)$request->get('limit', 30);
        $list = UserSigninModel::where('user_id', $user_id)
            ->order('id','desc')
            ->limit($limit)
            ->select();
        return $this->success(__('successful'),$list);
    }

    /**
     * @Apidoc\Title("发布朋友圈")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("files", type="string",require=true, desc="文件列表")
     */
    public function pyq(Request $request)
    {
        $user = JwtToken::getUser();
        if (!$user->realname_verify) {
            return $this->error(__('Please complete real-name verification first'));
        }
        $user_id = $user->id;
        $files = Input('files');
        if(count($files) != 2) {
            return $this->error(__('请上传2张图片'));
        }
        if(UserXuanchuanModel::where('user_id',$user_id)->where('type','pyq')->whereTime('created_at','today')->count() > 0) {
            return $this->error(__('请明日再来'));
        }
        UserXuanchuanModel::create([
            'user_id' => $user_id,
            'files' => implode(',',$files),
            'type' => 'pyq'
        ]);
        return $this->success(__('successful'));
    }
    /**
     * @Apidoc\Title("发布微信群")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("files", type="string",require=true, desc="文件")
     */
    public function wx(Request $request)
    {
        $user = JwtToken::getUser();
        if (!$user->realname_verify) {
            return $this->error(__('Please complete real-name verification first'));
        }
        $user_id = $user->id;
        $files = Input('files');
        if(count($files) != 1) {
            return $this->error(__('请上传1张图片'));
        }
        if(UserXuanchuanModel::where('user_id',$user_id)->where('type','group')->whereTime('created_at','today')->count() > 0) {
            return $this->error(__('请每日再来'));
        }
        UserXuanchuanModel::create([
            'user_id' => $user_id,
            'files' => implode(',',$files),
            'type' => 'group'
        ]);
        return $this->success(__('successful'));
    }

    /**
     * @Apidoc\Title("补签")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("date", type="string",require=true, desc="补签日期")
     */
    public function makeUp(Request $request)
    {
        $user_id = JwtToken::getCurrentId();
        if (!$user_id) {
            return $this->error(__('Please login first'));
        }
        $date = $request->post('date');
        $today = date('Y-m-d');
        if (!$date || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            return $this->error(__('日期格式错误'));
        }
        // 补签日期不能大于今天
        if ($date > $today) {
            return $this->error(__('补签日期不能大于今天'));
        }
        // 检查是否已签到
        if (UserSigninModel::where('user_id', $user_id)->where('sign_date', $date)->find()) {
            return $this->error(__('该日已签到'));
        }
        // 补签消耗积分或奖励减半（此处以奖励减半为例）
        $yesterday = date('Y-m-d', strtotime($date . ' -1 day'));
        /** @var UserSigninModel $last */
        $last = UserSigninModel::where('user_id', $user_id)->where('sign_date', $yesterday)->find();
        $continuous_days = $last ? ($last->continuous_days + 1) : 1;
        $reward = floor($this->getReward($continuous_days) / 2); // 奖励减半
        UserSigninModel::create([
            'user_id' => $user_id,
            'sign_date' => $date,
            'reward' => $reward,
            'continuous_days' => $continuous_days,
        ]);
        \app\model\User::currency1($user_id, $reward, \app\enum\BalanceType::SIGNIN);
        return $this->success(__('successful'),['reward' => $reward, 'continuous_days' => $continuous_days]);
    }

    /**
     * @Apidoc\Title("签到统计报表")
     * @Apidoc\Method("GET")
     */
    public function report(Request $request)
    {
        $user_id = JwtToken::getCurrentId();
        if (!$user_id) {
            return $this->error(__('Please login first'));
        }
        $total = UserSigninModel::where('user_id', $user_id)->count();
        $max_continuous = UserSigninModel::where('user_id', $user_id)->max('continuous_days');
        $month = date('Y-m');
        $month_count = UserSigninModel::where('user_id', $user_id)
            ->whereLike('sign_date', "$month%")
            ->count();
        return $this->success(__('successful'),[
            'total' => $total,
            'max_continuous' => $max_continuous,
            'month_count' => $month_count,
        ]);
    }

    // 奖励规则，可自定义
    protected function getReward($continuous_days)
    {
        $rewards = [20,20,20,20,20,20,100];
        $continuous_days = $continuous_days  - 1;
        $continuous_days = $continuous_days  % 7;
        return $rewards[$continuous_days];
    }

    /**
     * @Apidoc\Title("上传")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("file", type="string",require=true, desc="文件")
     */
    function upload(Request $request)
    {
        //多文件上传
        $files = $request->file();
        try {
            $result = Storage::adapter('public')
                ->path('upload/files')
                ->size(1024*1024*50)
                ->extYes(['image/jpeg','image/png'])
                ->uploads($files,0,1024*1024*20,false);
            return $this->success(__('successful'),$result);
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }
}