<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ProductOrder;
use App\Models\Product;

class ProductOrderController extends Controller
{

    /**
     * 创建产品订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $id = $request->input('id');
        $product_id = $request->input('product_id');

        //$user = session('wechat.oauth_user.default');
        //$wechat_id = $user->getId();
        $wechat_id = $request->header("openid");
        if(!$wechat_id) {
            $wechat_id = $request->input("openid");
        }
        $amount = $request->input('amount');
        $remark = $request->input('remark');
        $info = $request->input('info');
        $address = $request->input('address');
        $contact = $request->input('contact');
        $phone = $request->input('phone');
        $status = $request->input('status');
        $photo = $request->input('photo');
        if ($id) {
            $productOrder = ProductOrder::find($id);
            $productOrder->status = $status;

        } else {
            $productOrder = new ProductOrder;
            $productOrder->status = 0;
        }
        if ($wechat_id && $product_id && $amount
            && $address && $contact && $phone) {

            $product = Product::find($product_id);
            $unit = $product->price;
            $product_name = $product->name;
            $color = $product->color;
            $productOrder->product_id = $product_id;
            $productOrder->product_name = $product_name;
            $productOrder->wechat_id = $wechat_id;
            $productOrder->price = $unit * $amount;
            $productOrder->unit = $unit;
            $productOrder->amount = $amount;
            $productOrder->remark = $remark;
            $productOrder->color = $color;
            $productOrder->info = $info;
            $productOrder->address = $address;
            $productOrder->contact = $contact;
            $productOrder->phone = $phone;
            $productOrder->photo = "https://wechat.sotype.com/storage/gOtuHM3GvKva6x68N340DJuN6cX1oIfaAhWi8yoq.jpeg";
            $productOrder->wechat_id = $wechat_id;
            $productOrder->save();
            return Response()->json([
                "status" => 0,
                "message" => "保存成功!",
                "data" => $productOrder
            ]);
        } else {
            return Response()->json([
                "status" => -1,
                "message" => "信息不能为空!"
            ]);
        }
    }

    /**
     * 每页20进行分页
     * @param Request $request
     * @return mixed
     */
    public function list(Request $request)
    {
        return ProductOrder::paginate(20);
    }
}
