<?php

namespace App\Http\Controllers\Shop;

use App\Http\Controllers\Controller;
use App\Http\Resources\ShopsResource;
use App\Models\Shop;
use App\Models\ShopSender;
use App\Models\ShopShip;
use App\Services\Business\KuaiTuanTuan\FaceSheet;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class ShipController extends Controller
{
    public function index(Request $request)
    {
        $shops = Shop::query()
            ->select(['id', 'name', 'plat_id'])
            ->with('ship')
//            ->where('plat_id', 1)
            ->get();
        $time = date('Y-m-d H:i:s');
        foreach ($shops as $shop) {
            $faceSheet = new FaceSheet();
            $shop->authUrl = $faceSheet->getAuthUrl($shop->id, $shop->plat_id);
            $shop->status = 0;
            if ($shop->ship) {
                $shop->status = $shop->ship->getOriginal('status');
                if ($shop->ship->expires_at && $time >= $shop->ship->expires_at) {
                    ShopShip::query()->where('shop_id', $shop->id)->update(['status' => Shop::$STATUS_UNAUTHORIZED]);
                }
            }
        }

        return ShopsResource::collection($shops);
    }

    public function getSenders(Request $request)
    {
        $senders = ShopSender::query()
            ->where('shop_id', $request->get('shop_id'))
            ->where('shop_ship_id', $request->get('shop_ship_id'))
            ->orderBy('sort')
            ->get();

        return JsonResource::collection($senders);
    }

    public function saveSenders(Request $request)
    {
        $senderList = $request->input('senderList');
        foreach ($senderList as $item) {
            $item = json_decode($item, true);
            $sender = ShopSender::query()->findOrFail($item['id']);
            $sender->name = $item['name'];
            $sender->mobile = $item['mobile'];
            $sender->sort = $item['sort'];
            $sender->status = $item['status'];
            $sender->timed_delivery_code = $item['timed_delivery_code'];
            $sender->save();
        }

        return response(['message' => '保存成功']);
    }
}
