<?php

namespace App\Http\Controllers\Shop;

use App\Http\Controllers\Controller;
use App\Models\BusinessGoodsSku;
use App\Models\DeveloperConfig;
use App\Models\GoodsSku;
use App\Models\Shop;
use App\Http\Resources\ShopsResource;
use App\Models\ShopSender;
use App\Models\ShopShip;
use App\Services\Business\KuaiTuanTuan\FaceSheet;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use App\Services\Business\BusinessFactory;
use Illuminate\Validation\Rule;
use App\Models\BusinessOrderItem;

class ShopsController extends Controller
{
    public function index(Request $request)
    {
        $shops = Shop::query()->filter()->paginate($request->get('per_page'));
        $time = time();
        foreach ($shops as $shop) {
            $shop->authUrl = '';
            if ('已授权' === $shop->status && ($shop->expires_at - time()) / 3600 <= 72) {
                $shop->status = '重新授权';
            }
            if ('妙选' !== $shop->plat_id && ('未授权' === $shop->status || '重新授权' === $shop->status)) {
                $shop->authUrl = BusinessFactory::init()->make($shop->plat_id)->getAuthUrl($shop->id, $shop->getOriginal('plat_id'));
            }
            if ($shop->expires_at && $time >= $shop->expires_at) {
                Shop::query()->where('id', $shop->id)->update(['status' => Shop::$STATUS_UNAUTHORIZED]);
            }
        }

        return ShopsResource::collection($shops);
    }

    public function getPlatList()
    {
        $shop = new Shop();

        return new ShopsResource($shop->getPlatList());
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:191|unique:shops,name',
            'plat_id' => 'required|integer',
            'ratio' => 'sometimes',
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        if(empty($request->ratio)){
            $request->ratio = "*1";
        }
        $operator = substr($request->ratio, 0, 1);
        if (!in_array($operator, ['+', '-', '*', '/'])) {
            $this->res->errorMessage = '运算符号仅允许+,-,*,/';
            return response($this->res, $this->res['httpCode']);
        }
        $shop = new Shop();
        $shop->name = $request->name;
        $shop->plat_id = $request->plat_id;
        $shop->ratio = $request->ratio;
        if (0 == $request->plat_id) {
            $shop->status = 2;
        }
        $shop->save();

        return response($this->res, $this->res['httpCode']);
    }

    public function update(Request $request, $id)
    {
        $operator = substr($request->ratio, 0, 1);
        if (!in_array($operator, ['+', '-', '*', '/'])) {
            $this->res->errorMessage = '运算符号仅允许+,-,*,/';
            return response($this->res, $this->res['httpCode']);
        }
        $shop = Shop::query()->find($id);
        $shop->ratio = $request->ratio;
        $shop->save();

        return response($this->res, $this->res['httpCode']);
    }

    public function authBind(Request $request)
    {
        [$shopId, $platId] = explode('_', $request->get('state'));
        $shop = new Shop();
        $platList = $shop->getPlatList();
        $shop = $shop->find($shopId);
        if ($platList[$platId] === $shop->plat_id) {
            BusinessFactory::init()->make($shop->plat_id)->authCallback($request->get('code'), $shop);
        } else {
            $this->res = [
                'httpCode' => 403,
                'errorCode' => 403400,
                'errorMessage' => '信息不匹配',
            ];
        }

        return response($this->res, $this->res['httpCode']);
    }

    public function business(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'type' => ['required', 'string', Rule::in(['goods', 'orders'])],
            'erp_shop_id' => ['required', 'integer', 'exists:shops,id'],
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $shop = new Shop();
        $shop = $shop->find($request->get('erp_shop_id'));
        $business = BusinessFactory::init()->make($shop->plat_id);
        $business->setShop($shop);
        if ('goods' === $request->get('type')) {
            $business->bindGoods($request->get('data'));
        }
        if ('orders' === $request->get('type')) {
            Log::info('秒选order',[$request->get('data')]);
            $business->saveOrders($request->get('data'));
        }

        return response(['Code' => 10000, 'Message' => 'SUCCESS']);
    }

    public function countOrdersNumWithSkuCode(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'sku_code' => ['required', 'array'],
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $fields = implode(',', [
            'shop_id',
            'external_sku_id',
            'sum(goods_number) as num',
        ]);
        $res = BusinessOrderItem::query()
            ->select(DB::raw($fields))
            ->whereIn('external_sku_id', $request->get('sku_code'))
            ->groupBy(['shop_id', 'external_sku_id'])
            ->with(['shop:id,name'])
            ->get();
        $data = [];
        foreach ($res as $item) {
            $sku = GoodsSku::query()
                ->where('external_sku_id', $item['external_sku_id'])
                ->first();
            if (empty($sku)) {
                continue;
            }
            $sku = $sku->toArray();
            if (!isset($data[$sku['id']]['total'])) {
                $data[$sku['id']]['total'] = 0;
            }
            $data[$sku['id']]['total'] += $item->num;
            $data[$sku['id']]['items'][] = [
                'shop_name' => $item->shop->name,
                'num' => $item->num,
            ];
        }

        return $data;
    }

    public function downloadGoods($id, Request $request)
    {
        $shop = Shop::query()->find($id);
        $business = BusinessFactory::init()->make($shop->plat_id);
        $business->setShop($shop);
        $res = $business->queryGroup();
        if (isset($res['ktt_group_query_list_response'])) {
            foreach ($res['ktt_group_query_list_response']['activity_list'] as $activity) {
                if (0 === $activity['is_help_sell']) {
                    $business->downloadGoodsListAndBind($activity['activity_no'], $activity['title']);
                }
            }
        }

        return response($this->res, $this->res['httpCode']);
    }

    public function syncStock(Request $request)
    {
        $shopId = $request->get('shop_id');
        $builder = Shop::query()->where('expires_at', '>', time());
        if ('all' === $shopId) {
            $shops = $builder->get();
        } else {
            $shops = $builder->where('id', $shopId)->get();
        }
        //同步三方的是在售库存
        $skus = GoodsSku::query()
            ->where('updated_at', '>', date('Y-m-d 07:01:00'))
            ->whereNotNull('external_sku_id')
            ->pluck('sale_stock', 'external_sku_id')
            ->toArray();
        foreach ($shops as $shop) {
            $business = BusinessFactory::init()->make($shop->plat_id);
            $business->setShop($shop);
            foreach ($skus as $externalSkuId => $stock) {
                $businessGoodsSkus = BusinessGoodsSku::query()
                    ->select(['goods_id', 'sku_id', 'external_sku_id'])
                    ->where('shop_id', $shop->id)
                    ->where('is_sync', 1)
                    ->where('external_sku_id', $externalSkuId)
                    ->get()
                    ->toArray();
                $business->batchIncrQuantity($businessGoodsSkus, $stock, false);
                usleep(10);
            }
        }

        return response($this->res, $this->res['httpCode']);
    }

    public function pddPrintAuth(Request $request)
    {
        [$shopId, $platId] = explode('_', $request->get('state'));
        $faceSheet = new FaceSheet();
        $faceSheet->setCode($request->get('code'));
        $faceSheet->setShopWithId($shopId);
        $faceSheet->auth('ship');
        $shopShip = ShopShip::query()
            ->where('shop_id', $shopId)
            ->first();
        if (empty($shopShip)) {
            exit();
        }
        $faceSheet->setShop($shopShip);
        $resp = $faceSheet->searchWayBill();
        if (!isset($resp['pdd_waybill_search_response']['waybill_apply_subscription_cols'])) {
            exit();
        }
        foreach ($resp['pdd_waybill_search_response']['waybill_apply_subscription_cols'] as $subCols) {
            foreach ($subCols['branch_account_cols'] as $accountCols) {
                foreach ($accountCols['shipp_address_cols'] as $item) {
                    $item['wp_code'] = $subCols['wp_code'];
                    ShopSender::query()->updateOrCreate(
                        ['shop_id' => $shopId, 'shop_ship_id' => $shopShip->id, 'detail' => $item['detail']],
                        $item
                    );
                }
            }
        }
    }

    public function orderReset(Request $request)
    {
        DeveloperConfig::query()->updateOrCreate([
            'key' => DeveloperConfig::$ORDER_RESET_TIME,
        ], [
            'value' => date('Y-m-d H:i:s')
        ]);

        return response($this->res, $this->res['httpCode']);
    }
}
