<?php

namespace App\Services\Business;

use App\Events\BusinessOrdersUpdate;
use App\Models\BusinessGoodsSku;
use App\Models\BusinessOrder;
use App\Models\BusinessOrderItem;
use App\Models\GoodsSku;
use App\Models\Log;
use App\Models\Shop;
use GuzzleHttp\Client;

abstract class BusinessClient
{
    protected $redirectUri = 'http://erp.chutang66.com/callback';
    protected $code;
    protected $shop;
    protected $skuId = 0;

    abstract public function auth();

    abstract public function downloadGoodsListAndBind();

    abstract public function downloadGoods($skuId);

    abstract public function bindGoods($goods);

    abstract public function incrQuantity($businessGoodsSku, $num, $incremental);

    abstract public function downloadOrdersAndSave($beginTime, $endTime, $downloadType = 'default', $page = 1);

    public function saveOrders($orders)
    {
        $shopId = $this->getShop()->id;
        foreach ($orders as $order) {
            unset($order['custom_item_list'], $order['logistics_list'], $order['gift_order_list']);
            $order['shop_id'] = $shopId;
            $orderRecord = BusinessOrder::firstOrNew(['shop_id' => $shopId, 'order_sn' => $order['order_sn']], $order);
            if (empty($orderRecord->id)) {
                $orderRecord->save();
            } else {
                $orderRecord->update($order);
            }
            foreach ($order['sub_order_list'] as $item) {
                $item['shop_id'] = $shopId;
                $orderItem = BusinessOrderItem::firstOrNew(['shop_id' => $shopId, 'business_order_id' => $orderRecord->id, 'goods_id' => $item['goods_id'], 'sku_id' => $item['sku_id']], $item);
                $num = 0;
                if (empty($orderItem->id)) {
                    if ($item['cancel_status']) {
                        if ($num = $item['goods_number'] - $item['already_cancel_number']) {
                            // 扣库存 $reduceNum
                            $num = 0 - $num;
                        }
                    } else {
                        // 扣库存
                        $num = 0 - $item['goods_number'];
                    }
                    $orderItem->save();
                } else {
                    if ($item['cancel_status'] !== $orderItem->cancel_status) {
                        if ($item['cancel_status']) {
                            // 加库存
                            $num = $item['already_cancel_number'];
                        } else {
                            // 扣库存
                            $num = 0 - $item['goods_number'];
                        }
                    }
                    $orderItem->update($item);
                }
                // 增量更新库存
                if ($num) {
                    event(new BusinessOrdersUpdate($orderItem, $num));
                }
            }
        }
    }

    public function authCallback($code, $shopId)
    {
        $this->setCode($code);
        $this->setShop($shopId);
        $this->auth();

        return $this;
    }

    public function setShopWithId($shopId)
    {
        $this->shop = Shop::query()->find($shopId);

        return $this;
    }

    public function setShop(Shop $shop)
    {
        $this->shop = $shop;

        return $this;
    }

    public function getShop()
    {
        return $this->shop;
    }

    public function setCode($code)
    {
        $this->code = $code;

        return $this;
    }

    public function getCode()
    {
        return $this->code;
    }

    public function setSkuId($skuId)
    {
        $this->skuId = $skuId;

        return $this;
    }

    public function getSkuId()
    {
        return $this->skuId;
    }

    public function formDataPostRequest($url, $params)
    {
        $method = 'POST';
        $headers = [
            'headers' => ['Content-type' => 'application/x-www-form-urlencoded;charset=UTF-8'],
            'form_params' => $params
        ];
        $res = (new Client())->request($method, $url, $headers);
        $size = $res->getBody()->getSize();
        $res = json_decode($res->getBody()->getContents(), true);
        if ('pdd.ktt.increment.order.query' === $params['type']) {
            $log = Log::query()->where('user_id', $this->getShop()->id)->where('target_field', $params['type'])->first();
        } else {
            $log = new Log();
        }
        $log->module = 'plat';
        $log->action = $method;
        $log->target_type = $this->getShop()->plat_id;
        $log->target_id = $this->getSkuId();
        $log->target_field = $params['type'];
        $log->user_id = $this->getShop()->id;
        if ($size < 64000) {
            $log->message = json_encode($res, 256);
        }
        $log->save();

        return $res;
    }
}
