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

use Modules\Store\Models\Store;
use Modules\Member\Models\Member;
use Modules\Member\Models\MemberStore;
use Modules\Goods\Models\Order;
use Modules\Member\Services\AccountService;
use Modules\Member\Services\ScoreService;
use App\Support\Tree;
use App\Support\Time;

class StoreService {

	/**
	 * @title 店铺分类列表
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getDataList($request){
		$map = [];

		$query = Store::with(['category:id,title,description,cover,sort', 'service:uid,username,nickname,mobile']);

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

		$query->where($map);

		if ($request->is('admin/*')){
			if(auth('admin')->user()['uid'] != 1){
				$query->whereIn('service_id', [auth('admin')->user()['uid'], 0]);
			}
		}
		if($request->filled('is_invite') && $request->input('is_invite') == 1 && auth('api')->user()){
			$query->where('invite_uid', '=', auth('api')->user()['uid']);
		}

		if($request->filled('lat') && $request->filled('lng')){
			$query->selectRaw('*, ( 6371 * acos( cos( radians('.$request->input('lat').') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('.$request->input('lng').') ) + sin( radians('.$request->input('lat').') ) * sin( radians( latitude ) ) ) ) AS distance');
			if($request->filled('radius')){
				$query->havingRaw('distance < ?', [$request->input('radius')]);
			}
			$query->orderBy('distance', 'asc');
		}

		if($request->filled('my_store') && auth('api')->user()){
			$query->whereIn('id', function($q){
				$q->select('store_id')->from('member_store')->where('member_id', '=', auth('api')->user()['uid']);
			});
		}

		$query->orderBy($request->input('order', 'id'), $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->limit($request->input('limit', 1000))->get();
		}
		return $data;
	}

	/**
	 * @title 店铺详情
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getData($request){
		$map = [];
		if($request->filled('id')){
			$map[] = ['id', '=', $request->input('id')];
		}else{
			$store_id = Member::where('uid', '=', auth('api')->user()['uid'])->value('store_id');
			$map[] = ['id', '=', $store_id ? $store_id : 16];
		}
		if($request->filled('status')){
			$map[] = ['status', '=', $request->input('status')];
		}

		$query = Store::with(['category:id,title,description,cover,sort'])->where($map);

		$store = $query->first();

		if($store->status == 0 || $store->status == 2){
			throw new \Exception("店铺暂未开通！", 1);
		}

		if($request->filled('is_visit')){
			$visit = MemberStore::where('store_id', '=', $store->id)->where('member_id', '=', auth('api')->user()['uid'])->first();
			if(!$visit){
				$visit = new MemberStore();
				$visit->store_id = $store->id;
				$visit->member_id = auth('api')->user()['uid'];
				$visit->count = 1;
				$visit->save();
			}else{
				$visit->increment('count');
			}
		}
		if($request->is('api/*') && auth('api')->user()){
			$store->is_collect = \Modules\Member\Models\MemberCollect::where('store_id', '=', $store->id)->where('type', 'store')->where('member_id', '=', auth('api')->user()['uid'])->exists();
		}
		return $store;
	}

	public function mystore($request){
		if(!auth('api')->user()){
			throw new \Exception("您未创建店铺，可去申请店铺！", 100);
		}
		$store = Store::with(['service:uid,username,nickname,mobile'])->where('member_id', '=', auth('api')->user()['uid'])->first();

		$store->score = \Modules\Member\Models\MemberScore::where('member_id', '=', auth('api')->user()['uid'])->where('type', 'income')->whereDate('created_at', date('Y-m-d'))->sum('amount');
		$store->money = \Modules\Member\Models\MemberAccount::where('member_id', '=', auth('api')->user()['uid'])->where('type', 'income')->whereDate('created_at', date('Y-m-d'))->sum('amount');
		$store->order_count = \Modules\Order\Models\OrderItem::where('store_id', '=', $store->id)->where('status', '>', 1)->whereDate('created_at', date('Y-m-d'))->count();  //当天单量统计
		$store->order_amount = \Modules\Order\Models\OrderItem::where('store_id', '=', $store->id)->where('status', '>', 1)->whereDate('created_at', date('Y-m-d'))->sum('total_price');
		return $store;
	}

	/**
	 * @title 添加店铺分类
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function create($request){
		if(auth('api')->user()){
			$request->mergeIfMissing(['member_id' => auth('api')->user()['uid']]);
		}
		$request->mergeIfMissing(['status' => 0]);
		$request->validate([
			'title' => 'required|max:255',
			'member_id' => 'required|unique:store',
		], [
			'title.required' => '请输入店铺名称！',
			'member_id.required' => '请输入店主ID！',
			'member_id.unique' => '当前店主已存在！',
		]);

		$store = Store::where('member_id', '=', $request->input('member_id'))->first();

		if($request->is('api/*') && $store){
			if($store->member_id == auth('api')->user()['uid'] && $store->status == 1){
				throw new \Exception("您已创建店铺，请勿重复创建！", 1);
			}
		}

		if(!$store){
			$store = new Store();
		}

		foreach ($store->setFilterFields($request->all()) as $key => $value) {
			$store->$key = $value;
		}
		$store->save();
		return $store;
	}

	/**
	 * @title 更新店铺分类
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function update($request){
		$store = Store::where('id', $request->input('id'))->first();
		if(!$store){
			throw new \Exception("店铺分类不存在！", 1);
		}

		if($request->is('api/*') && $store){
			if($store->member_id != auth('api')->user()['uid']){
				throw new \Exception("您无权修改当前店铺！", 1);
			}
		}

		foreach ($store->setFilterFields($request->all()) as $key => $value) {
			$store->$key = $value;
		}
		$store->save();
		return $store;
	}

	public function delete($request){
		if($request->filled('id')){
			try {
				$store = Store::where('id', $request->input('id'))->first();
			} catch (\Throwable $th) {
				throw new \Exception("店铺分类不存在！", 1);
			}
			$store->delete();
		}
		if($request->filled('ids')){
			try {
				$store = Store::whereIn('id', $request->input('ids'));
				$store->delete();
			} catch (\Throwable $th) {
				throw new \Exception($th->getMessage(), 1);
			}
		}

		return $store;
	}

	public function copyStore($request){
		$request->validate([
			'title' => 'required|max:255',
			'member_id' => 'required|unique:store,member_id'
		],[
			'title.required' => '请输入店铺名称！',
			'member_id.required' => '请输入店主ID！',
			'member_id.unique' => '当前店主已存在！',
		]);

		$copy_store = Store::find($request->input('copy_id'));
		if(!$copy_store){
			throw new \Exception("复制店铺不存在！", 1);
		}

		$store = $copy_store->replicate()->fill([
			'title' => $request->input('title'),
			'member_id' => $request->input('member_id'),
			'service_id' => auth('admin')->user()['uid'],
		]);
		$store->save();
		return $store;
	}

	public function addGoods($request){
		$store = Store::find($request->input('store_id'));
		if(!$store){
			throw new \Exception("店铺不存在！", 1);
		}

		$store->goods()->syncWithoutDetaching($request->input('goods'));

		return $store;
	}

	public function deleteGoods($request){
		$store = Store::find($request->input('store_id'));
		if(!$store){
			throw new \Exception("店铺不存在！", 1);
		}

		$store->goods()->detach($request->input('goods_id'));

		return $store;
	}

	public function getTrendCount($params){
		$map = [];
		$time = [];

		if(isset($params['date_type']) && $params['date_type'] != ''){
			switch ($params['date_type']) {
				case 'day':
					$time = Time::today();
					break;
				case 'yesterday':
					$time = Time::yesterday();
					break;
				case 'seven':
					$time = Time::dayToNow(7);
					break;
				case 'diy':
					if(isset($params['date']) && $params['date'] != ''){
						$start_time = strtotime(date('Y-m-d', strtotime($params['date'])).' 00:00:00');
						$end_time = Time::daysAfter($start_time, 30);
						$time = [$start_time, $end_time];
					}
					break;
				default:
					$time = Time::today();
					break;
			}
		}


		$store_id = Store::where('member_id', auth('api')->user()['uid'])->value('id');
		// if(!$store_id){
		// 	throw new \Exception("您不是店主！", 0);
		// }
		$map[] = ['store_id', '=', $store_id];
		$sale_price = Order::where($map)->whereBetween('created_at', [date('Y-m-d H:i:s', $time[0]), date('Y-m-d H:i:s', $time[1])])->where('status', '=', 4)->sum('amount');
		$shop_user = MemberStore::where($map)->whereBetween('created_at', [date('Y-m-d H:i:s', $time[0]), date('Y-m-d H:i:s', $time[1])])->count();
		$order_total = Order::where($map)->whereBetween('created_at', [date('Y-m-d H:i:s', $time[0]), date('Y-m-d H:i:s', $time[1])])->count();
		$total_price = Order::where($map)->whereBetween('created_at', [date('Y-m-d H:i:s', $time[0]), date('Y-m-d H:i:s', $time[1])])->where('pay_time', '<>', null)->whereIn('status', [2, 3])->sum('amount');
		$order_total_sub = Order::where($map)->whereBetween('created_at', [date('Y-m-d H:i:s', $time[0]), date('Y-m-d H:i:s', $time[1])])->where('status', '=', 0)->count();
		$total_refund = Order::where($map)->whereBetween('created_at', [date('Y-m-d H:i:s', $time[0]), date('Y-m-d H:i:s', $time[1])])->where('pay_time', '<>', null)->where('status', '=', 4)->count();

		$data = [
			[ "name" => '实收金额', "number" => $sale_price ? $sale_price : 0, "isSelect" => true],
			[ "name" => '成交金额', "number" => $total_price ? $total_price : 0, "isSelect" => false],
			[ "name" => '订单数', "number" => $order_total ? $order_total : 0, "isSelect" => false],
			[ "name" => '新增客户', "number" => $shop_user ? $shop_user : 0, "isSelect" => false],
			[ "name" => '待确认订单', "number" => $order_total_sub ? $order_total_sub : 0, "isSelect" => false],
			[ "name" => '退款数', "number" => $total_refund ? $total_refund : 0, "isSelect" => false]
		];
		return $data;
	}

	/**
	 * @title 门店订单结算
	 *
	 * @param [type] $order
	 * @param [type] $goods
	 * @param [type] $member
	 * @return void
	 */
	public function orderBalance($order, $item, $store, $member, $goods, $sku){
	}
}
