<?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\MemberPolymer;

class PolymerService {

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

		$query = MemberPolymer::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', 'pay']);
		}
		$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', 'pay']);
		}
		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','pay'])){
						$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 createPolymer($store_id, $order_id, $member_id, $amount, $type, $account_type, $remark){
		if($order_id != 0){
			$polymer = MemberPolymer::where('order_id', '=', $order_id)->where('member_id', '=', $member_id)->where('type', '=', $type)->where('account_type', '=', $account_type)->first();
			if($polymer){
				return $polymer;
			}
		}


		$member = Member::where('uid', $member_id)->first();
		if(!$member){
			return false;
		}
		$af_amount = $member['polymer_money'] ? (in_array($type, ['pay', 'transfer']) ? bcsub($member['polymer_money'], $amount,2) : bcadd($member['polymer_money'], $amount,2)) : $amount;
		$bf_amount = $member['polymer_money'] ? $member['polymer_money'] : 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->polymer_money = bcsub($member->polymer_money, $amount, 2);
		}else{
			$member->polymer_money = bcadd($member->polymer_money, $amount, 2);
		}

		$member->save();

		$polymer = MemberPolymer::create($data);
		return $polymer;
	}

	/**
	 * @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 {
			$polymer = MemberPolymer::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', ''),
		];
		$polymer->update($data);
		return $polymer;
	}

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

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

		return $polymer;
	}
}
