<?php

namespace App\Http\Controllers\Admin;

use App\Exports\FoodExport;
use App\Exports\OperateStockExport;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\Food;
use App\Models\OperateStockLog;
use App\Models\Order;
use App\Models\S2ShopSpu;
use App\Models\Shop;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class FoodController extends Controller
{
    use ResponseJson;

    public function foodList(Request $request)
    {
        $no_page = $request->get('no_page');
        $query = Food::query()->keyword()->type()->orderByDesc('id');
        if ($no_page) {
            $foods = $query->get();
        } else {
            $foods = $query->paginate();
        }
        return $this->success('ok', $foods);
    }

    public function foodListV2(Request $request)
    {
        $export = $request->input('export');
        $query = S2ShopSpu::with('shopFood')->keyword()->foodType()->orderByDesc('id');
        if ($export) {
            $foods = $query->get();
            return Excel::download(new FoodExport($foods), '食物列表.xlsx');
        }
        $foods = $query->paginate();
        return $this->success('ok', $foods);
    }

    public function foodExport(Request $request)
    {
        return Excel::download(new FoodExport(), '食物列表.xlsx');
    }

    public function storeFood(Request $request)
    {
        $area = $request->input('area');
        if (empty($area))
            return $this->failure("请选择地区");
        $name = $request->input("name");
        if (empty($name))
            return $this->failure("请输入食物名称");
        $type = $request->input('type');
        if (empty($type))
            return $this->failure("请输入食物类型");
        $icon = $request->input('icon');
        if (empty($icon))
            return $this->failure("请上传食物图片");
        $unit = $request->input('unit');
        $price = $request->input('price');
        $have_goods = $request->input('have_goods');
        $quantity = $request->input('quantity');
        $is_sale = $request->get('is_sale');

        $config = $request->get('config');
        //库存
        $stock = $request->input('stock', 0);
        $food = Food::create(['name' => $name, 'type' => $type, 'icon' => $icon, 'unit' => $unit, 'area' => $area, 'price' => $price, 'have_goods' => $have_goods, 'quantity' => $quantity, 'stock' => $stock, 'is_sale' => $is_sale, 'config' => json_encode($config)]);

        return $this->success('ok', $food);
    }

    public function storeFoodV2(Request $request)
    {
        $shop_id = $request->input("shop_id");
        if (empty($shop_id))
            return $this->failure("请选择商品");
        $shop = S2ShopSpu::find($shop_id);
        $area = $request->input('area');
        if (empty($area))
            return $this->failure("请选择地区");
        $type = $request->input('type');
        if (empty($type))
            return $this->failure("请输入食物类型");
        $unit = $request->input('unit');
        $quantity = $request->input('quantity');
        $is_sale = $request->get('is_sale');
        $config = $request->get('config');
        //库存
        $stock = $request->input('stock', 0);
        $food = Food::create(['shop_id' => $shop_id, 'name' => $shop->title, 'type' => $type, 'icon' => $shop->icon, 'unit' => $unit, 'area' => $area, 'quantity' => $quantity, 'stock' => $stock, 'is_sale' => $is_sale, 'config' => json_encode($config)]);
        return $this->success('ok', $food);
    }

    public function food(Request $request, Food $food)
    {
        $food->config = json_decode($food->config, true);
        return $this->success('ok', $food);
    }

    public function foodV2(Request $request, Food $food)
    {
        $food->shop;
        $food->config = json_decode($food->config, true);
        return $this->success('ok', $food);
    }

    public function updateFood(Request $request, Food $food)
    {
        $area = $request->input('area');
        if ($area) {
            $food->area = $area;
        }
        $name = $request->input("name");
        if ($name) {
            $food->name = $name;
        }
        $type = $request->input('type');
        if ($type) {
            $food->type = $type;
        }
        $icon = $request->input('icon');
        if ($icon) {
            $food->icon = $icon;
        }
        $price = $request->input('price');
        if (strlen($price) > 0) {
            $food->price = $price;
        }
        $weight = $request->input('weight');
        if ($weight) {
            $food->weight = $weight;
        }
        $have_goods = $request->input('have_goods');
        if (isset($have_goods)) {
            $food->have_goods = $have_goods;
        }
        $quantity = $request->input('quantity');
        if (isset($quantity)) {
            $food->quantity = $quantity;
        }
        $unit = $request->input('unit');
        $stock = $request->input('stock');

        $is_sale = $request->get('is_sale');
        if (isset($is_sale)) {
            $food->is_sale = $is_sale;
        }

        if (isset($stock)) {
            $food->stock = $stock;
        }
        $config = $request->get('config');
        if (isset($config)) {
            $food->config = json_encode($config);
        }

        $food->unit = $unit;
        $food->save();
        return $this->success('ok');
    }

    public function updateFoodV2(Request $request, Food $food)
    {
        $data = $request->all();
        $shop = S2ShopSpu::find($data['shop_id']);
        // $data['name'] = $shop->title;
        $data['icon'] = $shop->icon;
        $data['config'] = json_encode($data['config']);
        $food->update($data);
        return $this->success('ok');
    }

    public function deleteFood(Request $request, Food $food)
    {
        $food->delete();
        return $this->success('ok');
    }

    /**
     * 操作出库入库
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function updateFoodNum(Request $request)
    {
        DB::beginTransaction();
        $type = $request->get('type');
        $id = $request->get('id');
        $num = $request->get('num');
        $contract = $request->get('contract');
        if (!is_numeric($num)) {
            return $this->failure('请输入整数');
        }
        $images = $request->get('images');
        $food = Food::where('id', $id)->first();
        if (empty($food)) {
            return $this->failure('食物不存在');
        }

        if ($type == OperateStockLog::OPERATE_TYPE_OUT && $food->stock < $num) {
            return $this->failure('库存不足');
        }
        $after_num = $food->stock + $num;
        if ($type == OperateStockLog::OPERATE_TYPE_OUT) {
            $after_num = $food->stock - $num;
        }
        $remark = $request->get('remark');
        //增加库存记录
        $admin = auth()->user();

        $map = [];
        $map['name'] = $food->name;
        $map['id'] = $food->id;
        $map['stock'] = $food->stock;
        $map['num'] = $num;
        $map['after_num'] = $after_num;
        $map['type'] = OperateStockLog::TYPE_ADMIN;
        $map['remark'] = !empty($remark) ? $remark : "管理员:{$admin->name}修改了商品库存,商品名:{$food->name},数量:{$num}";
        $map['operate_type'] = $type;
        $map['status'] = OperateStockLog::OPERATE_STATUS_APPLY;
        $map['images'] = json_encode($images);
        $map['goods_type'] = OperateStockLog::GOODS_TYPE_FOOD;
        $map['contract'] = $contract;
        OperateStockLog::addLog($admin, $map);

        DB::commit();
        return $this->success('ok', $food);
    }

    /**
     * 获取操作库存记录
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getOperateStockLog(Request $request)
    {
        try {
            $keyword = $request->get('keyword');
            $food_id = $request->get('food_id');
            $operate_type = $request->get('operate_type');
            $is_export = $request->get('is_export');
            $start_time = $request->get('start_time');
            $end_time = $request->get('end_time');
            $status = $request->get('status');
            $query = OperateStockLog::query()->orderBydesc('id')->when($keyword, function ($query) use ($keyword) {
                $query->where('name', 'like', '%' . $keyword . "%")->orWhere('operate_name', 'like', '%' . $keyword . "%");
            })->when(!empty($food_id), function ($sql) use ($food_id) {
                $sql->where('food_id', $food_id);
            })->when(isset($operate_type), function ($sql) use ($operate_type) {
                $sql->where('operate_type', $operate_type);
            })->when(isset($status), function ($sql) use ($status) {
                $sql->where('status', $status);
            })->when(!empty($end_time), function ($sql) use ($start_time, $end_time) {
                $sql->where('created_at', '>=', $start_time)->where('created_at', '<=', $end_time . " 23:59:59");
            });

            if ($is_export) {
                $list = $query->get();
                if ($list->isEmpty()) {
                    return $this->failure('暂无数据');
                }
                return Excel::download(new OperateStockExport($list), 'operate_stock.xlsx');
            }

            $logs = $query->paginate();
            foreach ($logs as $log) {
                $log->images = json_decode($log->images, true);
                if (!empty($log->order_id)) {
                    $order = Order::findOrFail($log->order_id);
                }
                $log->order_user_name = $order->name ?? '';
                $log->order_user_mobile = $order->mobile ?? '';
                $log->order_trade_no = $order->trade_no ?? '';
            }
            return $this->success('ok', $logs);
        } catch (\Exception $e) {
            return $this->failure($e->getMessage());
        }
    }

    public function checkStockLog(Request $request)
    {
        DB::beginTransaction();
        //        try {
        $ids = $request->input('ids');
        if (!is_array($ids)) {
            return $this->failure('参数格式不正确');
        }
        foreach ($ids as $id) {
            $detail = OperateStockLog::findOrFail($id);
            $status = $request->input('status');
            $check_remark = $request->input('check_remark');
            $num = $detail->num;
            if ($detail->operate_type == OperateStockLog::OPERATE_TYPE_OUT) {
                $num = -$detail->num;
            }
            if ($status == OperateStockLog::OPERATE_STATUS_PASS) {
                if ($detail->goods_type == OperateStockLog::GOODS_TYPE_FOOD) {
                    $food = Food::find($detail->food_id);
                    if ($detail->operate_type == OperateStockLog::OPERATE_TYPE_OUT && $food->stock < $detail->num) {
                        return $this->failure('库存不足');
                    }
                    $food->stock = $food->stock + $num;
                    $food->save();
                } else {
                    //                        $params = [];
//                        $params['num'] = $detail->num;
//                        $params['sku_id']  = $detail->sku_id;
//
//                        //添加操作记录
//                        $params['type'] = "INCREMENT";
//                        if($detail->operate_type == OperateStockLog::OPERATE_TYPE_OUT){
//                            $params['type'] = "DECREMENT";
//                        }
//                        $shop = new ShopController();
//                        $list = $shop->postData(config("app.shop_url")."admin/shops/{$detail->food_id}/stock",$params);
//                        if($list['code'] == 1){
//                            return $this->failure($list['message']);
//                        }
                    $type = "INCREMENT";
                    if ($detail->operate_type == OperateStockLog::OPERATE_TYPE_OUT) {
                        $type = "DECREMENT";
                    }
                    $shop = Shop::find($detail->food_id);
                    Log::info("出入库状态 {$type}");
                    if ($type == 'INCREMENT') {
                        $shop->incrementShopStock($detail->sku_id, $num);
                    } else {
                        $shop->decrementShopStock($detail->sku_id, $num);
                    }
                }
            }
            $admin = auth()->user();
            $detail->check_user_id = $admin->id;
            $detail->check_name = $admin->name;
            $detail->check_mobile = $admin->mobile;
            $detail->check_remark = $check_remark;
            $detail->status = $status;
            $detail->save();
        }
        DB::commit();
        return $this->success('ok');
        //        }catch (\Exception $e){
//            DB::rollBack();
//            return $this->failure($e->getMessage());
//        }
    }

    public function postData($url, $params)
    {
        $headers = [
            'Key' => config('app.shop_key'), // 自定义头部参数（示例）
        ];

        $client = new Client();
        $response = $client->post($url, [
            'headers' => $headers,
            'json' => $params
        ]);
        $code = $response->getStatusCode();
        if ($code != 200) {
            return ['message' => '请求失败', 'code' => 1];
        }
        $body = $response->getBody()->getContents(); // 获取响应内容
        $list = json_decode($body, true);
        return $list;
    }
}
