<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace Modules\Member\Services;

use Modules\Member\Models\Member;
use Modules\Member\Models\MemberScore;

class ScoreService {

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

		$query = MemberScore::query();

		if ($request->filled('store_id')) {
			$map[] = ['store_id', '=', $request->input('store_id')];
		}
		if ($request->filled('member_id')) {
			$map[] = ['member_id', '=', $request->input('member_id')];
		}
		if ($request->filled('is_user')) {
			$map[] = ['member_id', '=', auth('api')->user()['uid']];
			$query->whereIn('type', ['income', 'withdraw', 'transfer']);
		}
		$query->where($map)->orderBy('id', 'desc');

		if ($request->filled('username')) {
			$query->whereHas('member', function($query) use ($request){
				$query->where('username', 'like', '%' . $request->input('username') . '%');
			});
		}
		if ($request->filled('mobile')) {
			$query->whereHas('member', function($query) use ($request){
				$query->where('mobile', 'like', '%' . $request->input('mobile') . '%');
			});
		}
		if ($request->filled('store_title')) {
			$query->whereHas('store', function($query) use ($request){
				$query->where('title', 'like', '%' . $request->input('store_title') . '%');
			});
		}
		if ($request->filled('is_admin') && auth('admin')->user()) {
			$map[] = ['member_id', '=', auth('admin')->user()['uid']];
			$query->whereIn('type', ['service_income', 'service_withdraw', 'service_transfer']);
		}else{
			$query->whereIn('type', ['income', 'withdraw', 'transfer']);
		}
		if ($request->filled('type')) {
			if (is_string($request->input('type'))){
				$map[] = ['type', '=', $request->input('type')];
			}else if (is_array($request->input('type'))){
				$query->whereIn('type', $request->input('type'));
			}
		}

		$query->where($map);
		if($request->filled('page')){
			$data = [
				'total' => $query->count(),
				'page' => $request->input('page', 1),
				'data' => $query->offset($request->input('offset', 0))->limit($request->input('limit', 30))->get()->each(function($item){
					if (in_array($item->type, ['income', 'withdraw'])){
						$item->member = $item->member()->select(['uid', 'username', 'nickname', 'avatar'])->first();
					}else if (in_array($item->type, ['service_income', 'service_withdraw'])){
						$item->member = $item->admin()->select(['uid', 'username', 'nickname', 'avatar'])->first();
					}else{
						$item->member = $item->member()->select(['uid', 'username', 'nickname', 'avatar'])->first();
					}
				}),
			];
		}else{
			$data = $query->limit($request->input('limit', 30))->get();
		}
		return $data;
	}

	/**
	 * @title 添加会员
	 *
	 * @param Request $request
	 * @param MemberService $service
	 * @return void
	 */
	public function createScore($store_id, $order_id, $member_id, $amount, $type, $account_type, $remark){
		if($order_id != 0){
			$score = MemberScore::where('order_id', '=', $order_id)->where('member_id', '=', $member_id)->where('type', '=', $type)->where('account_type', '=', $account_type)->first();
			if($score){
				return $score;
			}
		}


		$member = Member::where('uid', $member_id)->first();
		if(!$member){
			return false;
		}
		$af_amount = $member['score'] ? (in_array($type, ['pay', 'transfer']) ? bcsub($member['score'], $amount,2) : bcadd($member['score'], $amount,2)) : $amount;
		$bf_amount = $member['score'] ? $member['score'] : 0;

		$data = [
			'store_id' => $store_id,
			'order_id' => $order_id,
			'member_id' => $member_id,
			'type' => $type,
			'account_type' => $account_type,
			'amount' => $amount,
			'bf_amount' => $bf_amount,
			'af_amount' => $af_amount,
			'status' => 0,
			'remark' => $remark,
		];

		if ($af_amount < 0){
			throw new \Exception("会员积分余额不足!", 0);
		}

		if (in_array($type, ['pay', 'transfer'])){
			$member->score = bcsub($member->score, $amount, 2);
		}else{
			$member->score = bcadd($member->score, $amount, 2);
		}

		$member->save();

		$score = MemberScore::create($data);
		return $score;
	}

	/**
	 * @title 修改会员
	 *
	 * @param Request $request
	 * @param MemberService $service
	 * @return void
	 */
	public function update($request){
		$request->validate([
			'title' => 'required|max:255',
			'name' => 'required|max:255|alpha_dash:ascii|unique:member_level,name,' . $request->input('id'),
		]);

		try {
			$score = MemberScore::findOrFail($request->input('id'));
		} catch (\Throwable $th) {
			throw new \Exception("会员不存在！", 1);
		}

		$data = [
			'title'=> $request->input('title', ''),
			'name' => $request->input('name', ''),
			'icon' => $request->input('icon', ''),
			'sort' => $request->input('sort', 0),
			'status' => $request->input('status', 1),
			'remark' => $request->input('remark', ''),
		];
		$score->update($data);
		return $score;
	}

	public function delete($request){
		if($request->filled('id')){
			try {
				$score = MemberScore::findOrFail($request->input('id'));
			} catch (\Throwable $th) {
				throw new \Exception("会员等级不存在！", 1);
			}
			$score->delete();
		}
		if($request->filled('ids')){
			try {
				$score = MemberScore::whereIn('id', $request->input('ids'));

				$score->delete();
			} catch (\Throwable $th) {
				throw new \Exception($th->getMessage(), 1);
			}
		}

		return $score;
	}
}
