<?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\Account\Services;

use Illuminate\Http\Request;
use Modules\Account\Models\Family;
use Modules\Account\Models\FamilyMember;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class AdminFamilyService {

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

		// 名称搜索
		if ($request->filled('name')) {
			$map[] = ['name', 'like', '%' . $request->input('name') . '%'];
		}

		// 家主筛选
		if ($request->filled('owner_id')) {
			$map[] = ['owner_id', '=', $request->input('owner_id')];
		}

		// 邀请码筛选
		if ($request->filled('invite_code')) {
			$map[] = ['invite_code', '=', $request->input('invite_code')];
		}

		// 日期范围筛选
		if ($request->filled('start_date')) {
			$map[] = ['created_at', '>=', $request->input('start_date')];
		}
		if ($request->filled('end_date')) {
			$map[] = ['created_at', '<=', $request->input('end_date')];
		}

		$query = Family::with(['owner:uid,nickname,username', 'members:uid,nickname,username']);

		$query->where($map);

		// 排序
		$query->orderBy($request->input('order', 'created_at'), $request->input('sort', '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();
		}

		// 添加成员数量统计
		if ($request->filled('page')) {
			foreach ($data['data'] as $family) {
				$family->member_count = $family->members->count();
			}
		}

		return $data;
	}

	/**
	 * @title 创建家庭
	 *
	 * @param Request $request
	 * @return void
	 */
	public function create($request) {
		$request->validate([
			'name' => 'required|string|max:50',
			'owner_id' => 'required|integer'
		], [
			'name.required' => '请输入家庭名称',
			'owner_id.required' => '请选择家主'
		]);

		$data = $request->all();

		// 生成10位邀请码
		do {
			$inviteCode = strtoupper(substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 10));
		} while (Family::where('invite_code', $inviteCode)->exists());

		$data['invite_code'] = $inviteCode;

		DB::beginTransaction();
		try {
			$family = Family::create($data);

			// 家主自动加入家庭
			FamilyMember::create([
				'family_id' => $family->id,
				'user_id' => $data['owner_id']
			]);

			DB::commit();

			return $family;
		} catch (\Exception $e) {
			DB::rollBack();
			throw $e;
		}
	}

	/**
	 * @title 更新家庭
	 *
	 * @param Request $request
	 * @return void
	 */
	public function update($request) {
		$request->validate([
			'id' => 'required|integer',
			'name' => 'required|string|max:50',
			'owner_id' => 'required|integer'
		], [
			'id.required' => '请提供家庭ID',
			'name.required' => '请输入家庭名称',
			'owner_id.required' => '请选择家主'
		]);

		$family = Family::findOrFail($request->input('id'));
		$data = $request->all();

		unset($data['id']);

		$family->update($data);

		return $family;
	}

	/**
	 * @title 删除家庭
	 *
	 * @param Request $request
	 * @return void
	 */
	public function delete($request) {
		if ($request->filled('id')) {
			try {
				$family = Family::findOrFail($request->input('id'));
				DB::beginTransaction();
				try {
					// 删除家庭成员
					FamilyMember::where('family_id', $family->id)->delete();
					// 删除家庭
					$family->delete();
					DB::commit();
				} catch (\Throwable $th) {
					DB::rollBack();
					throw $th;
				}
			} catch (\Throwable $th) {
				throw new \Exception("家庭不存在！", 1);
			}
		}

		if ($request->filled('ids')) {
			try {
				$families = Family::whereIn('id', $request->input('ids'))->get();
				DB::beginTransaction();
				try {
					foreach ($families as $family) {
						// 删除家庭成员
						FamilyMember::where('family_id', $family->id)->delete();
					}
					// 删除家庭
					$families->each->delete();
					DB::commit();
				} catch (\Throwable $th) {
					DB::rollBack();
					throw $th;
				}
			} catch (\Throwable $th) {
				throw new \Exception($th->getMessage(), 1);
			}
		}

		return $family;
	}

	/**
	 * @title 家庭详情
	 *
	 * @param Request $request
	 * @return void
	 */
	public function detail($request) {
		$id = $request->input('id');

		$family = Family::with(['owner:uid,nickname,username', 'members:uid,nickname,username,email'])
			->findOrFail($id);

		// 添加成员数量
		$family->member_count = $family->members->count();

		// 添加统计信息
		$billCount = DB::table('account_bills')->where('family_id', $family->id)->count();
		$totalExpense = DB::table('account_bills')
			->where('family_id', $family->id)
			->where('type', 'expense')
			->sum('amount');
		$totalIncome = DB::table('account_bills')
			->where('family_id', $family->id)
			->where('type', 'income')
			->sum('amount');

		$family->statistics = [
			'bill_count' => $billCount,
			'total_expense' => (float)$totalExpense,
			'total_income' => (float)$totalIncome,
			'total_balance' => (float)($totalIncome - $totalExpense)
		];

		return $family;
	}

	/**
	 * @title 获取家庭成员列表
	 *
	 * @param Request $request
	 * @return void
	 */
	public function getMembers($request) {
		$familyId = $request->input('family_id');

		if (!$familyId) {
			throw new \Exception('请提供家庭ID');
		}

		$family = Family::findOrFail($familyId);

		$members = FamilyMember::with('user:uid,nickname,username,email')
			->where('family_id', $familyId)
			->get();

		return [
			'family_id' => $familyId,
			'family_name' => $family->name,
			'owner_id' => $family->owner_id,
			'members' => $members->map(function($member) use ($family) {
				return [
					'id' => $member->id,
					'user_id' => $member->user_id,
					'name' => $member->user->nickname ?? $member->user->username,
					'username' => $member->user->username,
					'email' => $member->user->email,
					'is_owner' => $family->owner_id == $member->user_id,
					'joined_at' => $member->created_at
				];
			})->toArray(),
			'total' => $members->count()
		];
	}

	/**
	 * @title 添加家庭成员
	 *
	 * @param Request $request
	 * @return void
	 */
	public function addMember($request) {
		$request->validate([
			'family_id' => 'required|integer',
			'user_id' => 'required|integer'
		], [
			'family_id.required' => '请提供家庭ID',
			'user_id.required' => '请选择用户'
		]);

		$familyId = $request->input('family_id');
		$userId = $request->input('user_id');

		// 检查家庭是否存在
		$family = Family::findOrFail($familyId);

		// 检查用户是否已在家庭中
		$existingMember = FamilyMember::where('family_id', $familyId)
			->where('user_id', $userId)
			->first();

		if ($existingMember) {
			throw new \Exception('该用户已在家庭中');
		}

		// 检查用户是否已在其他家庭中
		$userInOtherFamily = FamilyMember::where('user_id', $userId)->first();
		if ($userInOtherFamily) {
			throw new \Exception('该用户已在其他家庭中');
		}

		// 添加家庭成员
		FamilyMember::create([
			'family_id' => $familyId,
			'user_id' => $userId
		]);

		return ['message' => '成员已添加'];
	}

	/**
	 * @title 移除家庭成员
	 *
	 * @param Request $request
	 * @return void
	 */
	public function removeMember($request) {
		$request->validate([
			'family_id' => 'required|integer',
			'user_id' => 'required|integer'
		], [
			'family_id.required' => '请提供家庭ID',
			'user_id.required' => '请提供用户ID'
		]);

		$familyId = $request->input('family_id');
		$userId = $request->input('user_id');

		// 检查家庭是否存在
		$family = Family::findOrFail($familyId);

		// 不能移除家主
		if ($family->owner_id == $userId) {
			throw new \Exception('不能移除家主，请先转让家主');
		}

		// 移除成员
		$member = FamilyMember::where('family_id', $familyId)
			->where('user_id', $userId)
			->first();

		if (!$member) {
			throw new \Exception('该用户不在家庭中');
		}

		$member->delete();

		return ['message' => '成员已移除'];
	}

	/**
	 * @title 重新生成邀请码
	 *
	 * @param Request $request
	 * @return void
	 */
	public function regenerateInviteCode($request) {
		$familyId = $request->input('family_id');

		if (!$familyId) {
			throw new \Exception('请提供家庭ID');
		}

		$family = Family::findOrFail($familyId);

		// 生成新邀请码
		do {
			$inviteCode = strtoupper(substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 10));
		} while (Family::where('invite_code', $inviteCode)->exists());

		$family->update(['invite_code' => $inviteCode]);

		return [
			'invite_code' => $inviteCode,
			'family_name' => $family->name
		];
	}

	/**
	 * @title 转让家主
	 *
	 * @param Request $request
	 * @return void
	 */
	public function transferOwner($request) {
		$request->validate([
			'family_id' => 'required|integer',
			'user_id' => 'required|integer'
		], [
			'family_id.required' => '请提供家庭ID',
			'user_id.required' => '请提供用户ID'
		]);

		$familyId = $request->input('family_id');
		$userId = $request->input('user_id');

		$family = Family::findOrFail($familyId);

		// 目标用户必须在家庭中
		$targetMember = FamilyMember::where('family_id', $familyId)
			->where('user_id', $userId)
			->first();

		if (!$targetMember) {
			throw new \Exception('该用户不在家庭中');
		}

		// 转让家主
		$family->update(['owner_id' => $userId]);

		return ['message' => '家主已转让'];
	}
}
