<?php

namespace App\Http\Controllers\Business;

use App\Events\BusinessOrdersUpdate;
use App\Http\Controllers\Controller;
use App\Http\Resources\BusinessGoodsSkuResource;
use App\Imports\TodayPriceImport;
use App\Models\BusinessGoodsSku;
use App\Models\BusinessOrderItem;
use App\Models\Goods;
use App\Models\GoodsSku;
use App\Models\Log as LogModel;
use App\Models\Shop;
use App\Models\TodayPrice;
use App\Services\Business\BusinessFactory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\DiffTodayPriceGoodsExport;

class BusinessGoodsSkusController extends Controller
{
    public function __construct(Request $request)
    {
        $this->log = new LogModel([
            'module' => 'plat',
            'action' => $request->getMethod(),
            'target_type' => 'goods',
        ]);
    }

    public function index(Request $request)
    {
        $businessGoodsSkus = BusinessGoodsSku::query()
            ->filter()
            ->where('quantity_type', 0)
            ->with(['shop:id,name'])
            ->paginate($request->get('per_page'));

        return BusinessGoodsSkuResource::collection($businessGoodsSkus);
    }

    public function update($id, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'is_sync' => ['required', Rule::in([0, 1])]
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $sku = BusinessGoodsSku::query()->find($id);
        $this->setBeforeUpdateForLog($sku->is_sync);
        $sku->is_sync = $request->input('is_sync');
        $sku->save();
        $this->setAfterUpdateForLog($sku->is_sync);
        $this->addLog($id, 'status');

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

    public function destroy($id, Request $request)
    {
        DB::beginTransaction();
        try {
            $sku = BusinessGoodsSku::query()->find($id);
            $this->setBeforeUpdateForLog($sku->toArray());
            BusinessOrderItem::query()->where('goods_id', $sku->goods_id)->where('sku_id', $sku->sku_id)->delete();
            $sku->delete();
            $this->setAfterUpdateForLog('');
            $this->addLog($id, '');
            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            // 返回错误
            $this->setValidatorFailResponse($exception->getMessages());
        }

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

    public function syncStock($id, Request $request)
    {
        $businessGoodsSku = BusinessGoodsSku::query()->where('is_sync', 1)->find($id);
        $sku = GoodsSku::query()
            ->where('external_sku_id', $businessGoodsSku->external_sku_id)
            ->first();
        if (empty($sku)) {
            $this->setValidatorFailResponse('未找到对应的商品,请核实后再次同步或删除此平台商品');
        } else {
            event(new BusinessOrdersUpdate($businessGoodsSku, 0));
            $this->res['message'] = '库存同步请求发送成功,具体结果查看日志';
        }
        return response($this->res, $this->res['httpCode']);
    }

    public function todayPriceImport(Request $request)
    {
        if (!$request->hasFile('today_price')) {
            $this->res = [
                'httpCode' => 404,
                'errorCode' => 404404,
                'errorMessage' => 'not found file',
            ];
        }
        try {
            $import = new TodayPriceImport();
            $path = $request->file('today_price');
            Excel::import($import, $path);
        } catch (ValidationException $exception) {
            $this->setValidatorFailResponse($exception->validator->getMessageBag()->getMessages());
        }

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

    public function exportTodayPrice(Request $request)
    {
        $todayPrice = TodayPrice::query()
            ->with([
                'goodsSku:id,goods_id,title,external_sku_id',
                'goodsSku.goods:id,title',
            ])
            ->where('day', date('Y-m-d'))
            ->get();
        if ($todayPrice->isEmpty()) {
            exit('今日价格数据未找到,请先上传');
        }
        $todayGoodsPrice = [];
        foreach ($todayPrice as $item) {
            $todayGoodsPrice[$item['external_sku_id']] = [
                'today_price' => $item['price'],
                'goods_name' => $item['goodsSku']['goods']['title'] . $item['goodsSku']['title'],
                'external_sku_id' => $item['external_sku_id'],
                'shop_price' => json_decode($item['shop_price'], true),
            ];
        }
        $shops = Shop::query()
            ->where('plat_id', Shop::$PLAT_KTT)
            ->where('expires_at', '>', time())
            ->get();
        $data = [];
        foreach ($shops as $shop) {
            $business = BusinessFactory::init()->make($shop->plat_id);
            $business->setShop($shop);
            $res = $business->queryGroup();
            if (!isset($res['ktt_group_query_list_response'])) {
                continue;
            }
            $activityNos = $activities = [];
            foreach ($res['ktt_group_query_list_response']['activity_list'] as $activity) {
                if (0 === $activity['is_help_sell'] && '补款勿拍' !== $activity['title']) {
                    $activityNos[] = $activity['activity_no'];
                    $activities[$activity['activity_no']] = $activity['title'];
                }
            }
            $businessGoodsSkus = BusinessGoodsSku::query()
                ->where('shop_id', $shop->id)
                ->whereIn('activity_no', $activityNos)
                ->orderBy('activity_no')
                ->get(['shop_id', 'title', 'activity_no', 'goods_name', 'price_in_fen', 'external_sku_id']);
            if ($businessGoodsSkus->isEmpty()) {
                continue;
            }
            $data[$shop->name] = $this->diffTodayPrice($businessGoodsSkus, $todayGoodsPrice, $activities, $shop->name);
        }

        ob_end_clean();
        return Excel::download(new DiffTodayPriceGoodsExport($data), date('Y-m-d') . '今日差价商品.xlsx');
    }

    private function diffTodayPrice($businessGoodsSkus, $todayPrice, $activities, $shopName)
    {
        $data = [];
        foreach ($businessGoodsSkus as $item) {
            // 记录团购下商品id
            $data[$item['activity_no']]['ids'][] = $item['external_sku_id'];
            // 团购中有,表格没有
//            if (!isset($todayPrice[$item['external_sku_id']])) {
//                $data[$item['activity_no']]['in_group'][] = $item->toArray();
//            }
            // 价格不一样
            if (isset($todayPrice[$item['external_sku_id']]) && $item['price_in_fen'] != $todayPrice[$item['external_sku_id']]['shop_price'][$shopName]) {
                $item['today_price'] = $todayPrice[$item['external_sku_id']]['shop_price'][$shopName];
                $data[$item['activity_no']]['diff_price'][] = $item->toArray();
            }
        }
        $todayIds = array_keys($todayPrice);
        foreach ($data as $no => &$arr) {
            foreach ($arr as $key => $value) {
                if ('ids' === $key) {
                    $ids = array_unique($value);
                    $ids = array_diff($todayIds, $ids);
                    foreach ($ids as $id) {
                        $todayPrice[$id]['title'] = $activities[$no];
                        $arr['not_in_group'][] = $todayPrice[$id];
                    }
                }
            }
            unset($arr['ids']);
        }

        return $data;
    }
}
