<?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\Events\MemberUpdate;

class MemberService {

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

		if ($request->filled('username')) {
			$map[] = ['username', 'like', '%' . $request->input('username') . '%'];
		}
		if ($request->filled('mobile')) {
			$map[] = ['mobile', 'like', '%' . $request->input('mobile') . '%'];
		}
		if ($request->filled('email')) {
			$map[] = ['email', 'like', '%' . $request->input('email') . '%'];
		}

		$query = Member::with(['social', 'level'])->where($map)->orderBy('uid', 'desc');

		if ($request->filled('title')) {
			$query->whereAny(['nickname', 'username'], 'like', '%' . $request->input('title') . '%');
		}
		$data = [
			'total' => $query->count(),
			'page' => $request->input('page', 1),
			'data' => $query->offset($request->input('offset', 0))->limit($request->input('limit', 10))->get(),
		];
		return $data;
	}

	public function getDetail($request){
		$request->validate([
			'id_card' => 'required',
		], [
			'id_card.required' => '身份证号不能为空！',
		]);

		$query = Member::with(['level', 'extend']);
		if ($request->filled('id_card')) {
			$query->whereHas('extend', function ($query) use ($request) {
				$query->where('id_card', $request->input('id_card'));
			});
		}

		if ($request->is('api/*')) {
			$query->select(['nickname', 'uid', 'level_id']);
		}

		if ($query->exists()) {
			return $query->first();
		} else {
			throw new \Exception("会员不存在！", 1);
		}
	}

	/**
	 * @title 创建用户
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function create($request){
		$request->validate([
			'username' => 'required|unique:member',
			'nickname' => 'required',
			'mobile' => 'required|unique:member',
			'password' => 'required|min:6|max:16'
		], [
			'username.required' => '用户名不能为空！',
			'username.unique' => '用户名已存在！',
			'nickname.required' => '昵称不能为空！',
			'mobile.required' => '手机号不能为空！',
			'mobile.unique' => '手机号已存在！',
			'password.required' => '密码不能为空！',
			'password.min' => '密码长度不能小于6位！',
			'password.max' => '密码长度不能大于16位！'
		]);

		$member = new Member;

		if ($request->filled('username')) {
			$member->username = $request->input('username');
		}
		if ($request->filled('nickname')) {
			$member->nickname = $request->input('nickname');
		}
		if ($request->filled('avatar')) {
			$member->avatar = $request->input('avatar');
		}
		if ($request->filled('email')) {
			$member->email = $request->input('email');
		}
		if ($request->filled('gender')) {
			$member->gender = $request->input('gender');
		}
		if ($request->filled('birthday')) {
			$member->birthday = $request->input('birthday');
		}
		if ($request->filled('date_type')) {
			$member->date_type = $request->input('date_type');
		}
		if ($request->filled('mobile')) {
			$member->mobile = $request->input('mobile');
		}
		if ($request->filled('level_expire_time')) {
			$member->level_expire_time = $request->input('level_expire_time');
		}
		if ($request->filled('password')) {
			$member->password = $request->input('password');
		}
		if ($request->filled('status')) {
			$member->status = $request->input('status');
		}
		$member->invite_uid = $request->input('invite_uid', '1890000001');
		$member->pm_uid = $request->input('pm_uid', '1890000001');
		$member->store_uid = $request->input('store_uid', '1890000001');
		$member->level_id = $request->input('level_id', '1');

		$member->save();

		return $member;
	}

	/**
	 * @title 更新用户
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function update($request){
		$request->validate([
			'username' => 'unique:member,username,'.$request->input('uid').',uid',
			'mobile' => 'unique:member,mobile,'.$request->input('uid').',uid',
		],[
			'username.unique' => '用户名已存在！',
			'mobile.unique' => '手机号已存在！',
		]);
		if ($request->filled('uid')) {
			$members = Member::where('uid', $request->input('uid'))->first();
		}
		if ($request->is('api/*') && auth('api')->user()) {
			$members = Member::where('uid', auth('api')->user()['uid'])->first();
		}

		if ($request->filled('username')) {
			$members->username = $request->input('username');
		}
		if ($request->filled('nickname')) {
			$members->nickname = $request->input('nickname');
		}
		if ($request->filled('avatar')) {
			$members->avatar = $request->input('avatar');
		}
		if ($request->filled('email')) {
			$members->email = $request->input('email');
		}
		if ($request->filled('gender')) {
			$members->gender = $request->input('gender');
		}
		if ($request->filled('birthday')) {
			$members->birthday = $request->input('birthday');
		}
		if ($request->filled('date_type')) {
			$members->date_type = $request->input('date_type');
		}
		if ($request->filled('mobile')) {
			$members->mobile = $request->input('mobile');
		}
		if ($request->filled('password')) {
			$members->password = $request->input('password');
		}
		if ($request->filled('level_expire_time')) {
			$members->level_expire_time = $request->input('level_expire_time');
		}

		$members->save();

		MemberUpdate::dispatch($members);
		return $members;
	}

	public function delete($request){
		if(!$request->filled('uid')){
			throw new \Exception("非法操作！", 1);
		}

		if (is_array($request->input('uid'))) {
			// 批量删除
			$mebers = Member::whereIn('uid', $request->input('uid'))->get();
			if ($mebers->isEmpty()) {
				throw new \Exception("会员不存在！", 1);
			}
			$member = Member::destroy(request()->input('uid'));

			return $member;
		}else{
			// 单个删除
			try {
				$mebers = Member::findOrFail($request->input('uid'));
			} catch (\Throwable $th) {
				throw new \Exception("会员不存在！", 1);
			}
			$mebers->delete();
			return $mebers;
		}
	}

	public function updatePasswd($request){
		$request->validate([
			'password' => 'required|min:6|max:16'
		], [
			'password.required' => '密码不能为空！',
			'password.min' => '密码长度不能小于6位！',
			'password.max' => '密码长度不能大于16位！'
		]);
		if ($request->is('api/*')) {
			$request->validate([
				'old_password' => 'required',
				'password' => 'confirmed'
			], [
				'old_password.required' => '旧密码不能为空！',
				'password.confirmed' => '两次密码不一致！'
			]);
		}
		if(!$request->filled('uid')){
			throw new \Exception("非法操作！", 1);
		}

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

		if(!$request->filled('password')){
			throw new \Exception("密码不能为空！", 1);
		}

		$mebers->password = $request->input('password');

		$mebers->save();
		return $mebers;
	}

	public function import($request){
		$file = $request->file('file');

		if ($file->isValid()) {
			$ext = $file->extension();

			if (in_array($ext, ['csv', 'xlsx']) === false) {
				throw new \Exception("请上传csv文件");
			}

			$path = $file->store('import/'.date('Ymd'), 'public');

			$tasks = app()->tasks->create([
				'title' => '会员数据导入',
				'type' => 'import',
				'file' => $path,
				'params' => $request->except('file'),
				'status' => 0,
			]);
			if ($tasks->id) {
				\Modules\Member\Jobs\MemberImport::dispatch($path, $tasks);
			}
		}
	}

	public function export($request){
		$tasks = app()->tasks->create([
			'title' => '会员数据导出',
			'type' => 'export',
			'file' => 'export/' . $request->input('fileName', time().'xlsx'),
			'status' => 0,
		]);

		if ($tasks->id) {
			\Modules\Member\Jobs\MemberExport::dispatch($request->all(), $tasks);
		}
	}
}
