<?php


namespace Modules\Member\Services;


use Modules\Member\Models\Member;
use Modules\Member\Models\SignRecord;

class SignService
{

	/**
	 * @title 获取签到列表
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getDataList($request){
		$map = [];

		if($request->filled('is_user')){
			$map[] = ['member_id', '=', auth('api')->user()['uid']];
		}

		if($request->filled('month')){
			$map[] = ['month', '=', $request->input('month')];
		}

		$query = SignRecord::where($map)->orderBy('id', 'desc');

		if($request->filled('page')){
			$data = [
				'total' => $query->count(),
				'page' => $request->input('page', 1),
				'data' => $query->offset($request->input('offset', 0))->limit($request->input('limit', 10))->get(),
			];
		}else{
			$data = $query->get();
		}
		return $data;
	}


	/**
	 * @title 添加签到
	 *
	 * @param Request $request
	 * @return void
	 */
	public function create($request){

		$member_id=auth('api')->user()['uid'];

		$checkSign=SignRecord::where(['member_id' => $member_id])->whereDate('created_at', date('Y-m-d'))->count();
		if($checkSign){
			throw new \Exception('不能重复签到');
		}

		$config = cache()->get('config');

		$member = Member::where('uid', $member_id)->first();
		if(!$member){
			throw new \Exception('用户不存在！');
		}

		if($config['score']){//送积分
			$member->score = bcadd($member->score, $config['score']);
			$member->save();
		}

		$record = new SignRecord();
		$record->member_id = $member_id;
		$record->score = $config['score'];
		$record->day = date('d');
		$record->month = date('Y-m');
		$record->save();
		return $checkSign;
	}
}