<?php

namespace App\Http\Controllers;

use App\Models\Campaign;
use App\Models\Classify;
use App\Models\CompanyInfo;
use App\Models\HouseApplianceCleanOrder;
use App\Models\HouseCleanOrder;
use App\Models\HousekeeperOrder;
use App\Models\MaternityMatronOrder;
use App\Models\Product;
use App\Models\ProductClassify;
use App\Models\Reward;
use App\Models\OptionOrder;
use App\Models\ProductOrder;
use App\Models\ServerInfo;
use App\Models\WechatInfo;
use App\Models\Comment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

class CommonController extends Controller
{

    /**
     * 登陆
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $code = $request->input("code");

        $miniProgram = app("wechat.mini_program");

        $auth = $miniProgram->auth->session($code);
        if(array_key_exists("openid", $auth)) {
            // 保存用户信息操作
            if(WechatInfo::where("openid", $auth["openid"])->count() == 0) {
                $wechatInfo = new WechatInfo;
                $wechatInfo->openid = $auth["openid"];
                $wechatInfo->session_key = $auth["session_key"];
                $wechatInfo->save();
            }
            return response()->json([
                "status" => 0,
                "data" => [
                    "openid" => $auth["openid"],
                    "token" => sha1($auth["openid"] . $auth["session_key"])
                ]]);
        } else if(array_key_exists("errcode", $auth)){
            return response()->json([
                "status" => $auth["errcode"],
                "message" => $auth["errmsg"]]);
        } else {
            return response()->json([
                "status" => -1,
                "data" => $auth
            ]);
        }
    }

    /**
     * 上传图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload(Request $request)
    {
        try {
            if ($request->hasFile('file') && $request->file('file')->isValid()) {
                $photo = $request->file('file');
                $extension = $photo->extension();
                //$store_result = $photo->store('photo');
                $name = "photos" . $extension;

                $store_result = Storage::putFile('public', $photo, 'public');
                $http_path = asset(str_replace('public', 'storage', $store_result));
                return response()->json([
                    'status' => 0,
                    'location' => $http_path
                ]);
            } else {
                return response()->json([
                    'status' => -1,
                    'message' => "error, photo is not valid!"
                ]);
            }
        } catch (Exception $e) {
            return response()->json([
                'status' => -2,
                'message' => "error," . $e->getCode() . ": " . $e->getMessage()
            ]);
        }

    }


    /**
     * 添加评论， 一个订单只能评价一次
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addComment(Request $request, $order_id, $order_type)
    {
        $order_id = $request->route("order_id");
        $order_type = $request->route("order_type");
        $title = $request->input("title");
        $content = $request->input("content");
        //$user = session('wechat.oauth_user.default');
        //$wechat_id = $user->getId();
        $wechat_id = $request->header("openid");
        if ($wechat_id && $order_id && $content) {
            $comment = new Comment;
            $comment->order_id = $order_id;
            $comment->order_type = $order_type;
            $comment->title = "";
            $comment->content = $content;
            $comment->show = 0;
            $comment->wechat_id = $wechat_id;
            $comment->save();

            $record = $this->getRecord($order_type, $order_id);
            $record->comment_id = $comment->id;
            $record->comment = $content;
            $record->status = 4;
            $record->save();

            return Response()->json([
                "status" => 0,
                "message" => "保存成功!"
            ]);
        } else {
            return Response()->json([
                "status" => -1,
                "message" => "信息不能为空!"
            ]);
        }
    }

    /**
     * 分页获取订单评论
     * @param Request $request
     * @return mixed
     */
    public function comments(Request $request, $order_type, $order_id)
    {
        $order_id = $request->route("order_id");
        $order_type = $request->route("order_type");
        if ($order_id && $order_type) {
            return Comment::where("order_id", $order_id)->where("order_type", $order_type)->orderBy('id', 'desc')->paginate(20);
        }
    }

    /**
     * 获取某订单评论
     * @param Request $request
     * @return mixed
     */
    public function type_comments(Request $request, $order_type)
    {
        $order_type = $request->route("order_type");
        if ($order_type) {
            $records = Comment::where("order_type", $order_type)->get();
            return Response()->json([
                "status" => 0,
                "data" => $records
            ]);
        }
    }

    /**
     * 获取我的订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function orders(Request $request)
    {
        //$user = session('wechat.oauth_user.default');
        //$wechat_id = $user->getId();

        $wechat_id = $request->header("openid");
        if(!$wechat_id) {
            $wechat_id = $request->input("openid");
        }
        if($wechat_id) {
            $os = array();
            /*$houseApplianceCleanOrder = HouseApplianceCleanOrder::where("wechat_id", $wechat_id)
                ->orderBy('id', 'desc')->get();
            $houseCleanOrder = HouseCleanOrder::where("wechat_id", $wechat_id)
                ->orderBy('id', 'desc')->get();
            $housekeeperOrder = HousekeeperOrder::where("wechat_id", $wechat_id)
                ->orderBy('id', 'desc')->get();*/
            $maternityMatronOrder = MaternityMatronOrder::where("wechat_id", $wechat_id)
                ->orderBy('id', 'desc')->get();

            $productOrder = ProductOrder::with("products")->where("wechat_id", $wechat_id)
                ->orderBy('id', 'desc')->get();

            $optionOrder = OptionOrder::where("wechat_id", $wechat_id)
                ->orderBy('id', 'desc')->get();
/*
            array_push($os, $houseApplianceCleanOrder);
            array_push($os, $houseCleanOrder);
            array_push($os, $housekeeperOrder);*/
            array_push($os, $maternityMatronOrder);
            array_push($os, $optionOrder);
            //array_push($os, $productOrder);
            $orders = array();
            for ($i = 0; $i < sizeof($os); $i++) {
                foreach ($os[$i] as $order) {
                    $data = [];
                    $data["id"] = $order->id;
                    $data["classify1"] = $order->classify1;
                    $data["classify2"] = $order->classify2;
                    $data["status"] = $order->status;
                    $data["price"] = $order->price;
                    $data["order_type"] = $order->order_type;
                    $data["photo"] = $order->photo;
                    $data["created_at"] = $order->created_at->toDateTimeString();
                    if($order->comment_id) {
                        $data["comment"] = true;
                    } else {
                        $data["comment"] = false;
                    }
                    // 未支付订单1小时后过期
                    /*if($order->status === 1) {
                        if(Carbon::now()->subHour()->gt($order->created_at)) {
                            $order->status = 3;
                            $order->save();
                            continue;
                        }
                    }*/
                    if($order->status === 3) {
                        continue;
                    }
                    array_push($orders, $data);
                }
            }
            $productData = [];
            foreach ($productOrder as $order) {
                $data = [];
                $data["id"] = $order->id;
                $data["status"] = $order->status;
                $data["price"] = $order->price;
                $data["order_type"] = "product_order";
                $data["created_at"] = $order->created_at->toDateTimeString();
                $data["products"] = [];
                foreach ($order["products"] as $prd) {
                    $productTmp = [];
                    $productTmp["id"] = $prd["id"];
                    $productTmp["name"] = $prd["name"];
                    $productTmp["classify"] = $prd["classify"];
                    $productTmp["color"] = $prd["color"];
                    $productTmp["price"] = $prd["price"];
                    $productTmp["photo"] = $prd["photo"];
                    $productTmp["amount"] = $prd["pivot"]["product_amount"];
                    array_push($data["products"], $productTmp);
                }

                if($order->comment_id) {
                    $data["comment"] = true;
                } else {
                    $data["comment"] = false;
                }

                // 未支付订单1小时后过期
                if($order->status === 0) {
                    if(Carbon::now()->subHour()->gt($order->created_at)) {
                        $order->status = 3;
                        $order->save();
                        continue;
                    }
                } else if($order->status === 3) {
                    continue;
                }
                array_push($productData, $data);
            }
            return Response()->json([
                "status" => 0,
                "data" => [
                    "others" => $orders,
                    "product_orders" => $productData
                ]
            ]);
        }


    }


    /**
     * 修改状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function status(Request $request, $order_type)
    {
        $id = $request->input("id");
        $status = $request->input("status");
        $order_type = $request->route("order_type");
        if ($id && $order_type) {
            $record = $this->getRecord($order_type, $id);
            if ($record) {
                $record->status = $status;
                $record->save();
                return Response()->json([
                    "status" => 0,
                    "message" => "保存成功!"
                ]);
            }
            return Response()->json([
                "status" => -2,
                "message" => "不存在的记录！"
            ]);
        } else {
            return Response()->json([
                "status" => -1,
                "message" => "信息不能为空!"
            ]);
        }
    }

    /**
     * 修改状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function price(Request $request, $order_type)
    {
        $id = $request->input("id");
        $price = $request->input("price");
        $order_type = $request->route("order_type");
        if ($id && $order_type) {
            $record = $this->getRecord($order_type, $id);
            if ($record) {
                $record->price = $price;
                $record->status = 1;
                $record->save();
                return Response()->json([
                    "status" => 0,
                    "message" => "保存成功!"
                ]);
            }
            return Response()->json([
                "status" => -2,
                "message" => "不存在的记录！"
            ]);
        } else {
            return Response()->json([
                "status" => -1,
                "message" => "金额不能为空!"
            ]);
        }
    }

    /**
     * 删除记录
     * @param Request $request
     * @param $type
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request, $order_type, $id)
    {
        $id = $request->route("id");
        $order_type = $request->route("order_type");
        if ($id && $order_type) {
            $record = $this->getRecord($order_type, $id);
            if ($record) {
                $record->delete();
                return Response()->json([
                    "status" => 0,
                    "message" => "删除成功!"
                ]);
            }
            return Response()->json([
                "status" => -2,
                "message" => "不存在的记录！"
            ]);
        } else {
            return Response()->json([
                "status" => -1,
                "message" => "信息不能为空!"
            ]);
        }
    }


    /**
     * 获取某个记录
     * @param Request $request
     * @param $type
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function get(Request $request, $order_type, $id)
    {
        $id = $request->route("id");
        $order_type = $request->route("order_type");
        if ($id && $order_type) {
            $record = $this->getRecord($order_type, $id);
            //$comment = Comment::where("order_type", $order_type)->where("order_id", $id)->first();
            if ($record) {
                $ret = [
                    "status" => 0,
                    "data" => $record
                ];
                //$ret["data"]["comment"] = $comment->content;
                return Response()->json($ret);
            }
            return Response()->json([
                "status" => -2,
                "message" => "不存在的记录！"
            ]);
        } else {
            return Response()->json([
                "status" => -1,
                "message" => "id不能为空!"
            ]);
        }
    }

    /**
     * 根据type和id获取记录
     * @param $type
     * @param $id
     * @return null
     */
    public static function getRecord($type, $id)
    {
        $record = null;
        switch ($type) {
            case "product":
                $record = Product::find($id);
                break;
            case "option_order":
                $record = OptionOrder::find($id);
                break;
            case "campaign":
                $record = Campaign::find($id);
                break;
            case "house_appliance_clean_order":
                $record = HouseApplianceCleanOrder::find($id);
                break;
            case "house_clean_order":
                $record = HouseCleanOrder::find($id);
                break;
            case "housekeeper_order":
                $record = HousekeeperOrder::find($id);
                break;
            case "maternity_matron_order":
                $record = MaternityMatronOrder::find($id);
                break;
            case "product_order":
                $record = ProductOrder::find($id);
                break;
            case "server_info":
                $record = ServerInfo::find($id);
                break;
            case "company_info":
                $record = CompanyInfo::find($id);
                break;
            case "classify":
                $record = Classify::find($id);
                break;
            case "reward":
                $record = Reward::find($id);
                break;
            case "product_classify":
                $record = ProductClassify::find($id);
                break;
            default:
                return null;
        }
        return $record;
    }


}
