<?php

namespace Modules\Mall\Http\Controllers\Api;

use App\Api\Controllers\Controller;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Jason\Api\Api;
use Modules\Mall\Facades\Refund;
use Modules\Mall\Http\Resources\Api\Order\LogisticResource;
use Modules\Mall\Http\Resources\Api\Order\OrderCollection;
use Modules\Mall\Http\Resources\Api\Order\OrderItemResource;
use Modules\Mall\Http\Resources\Api\Order\OrderLogisticResource;
use Modules\Mall\Http\Resources\Api\Order\OrderResource;
use Modules\Mall\Models\Order;
use Modules\Mall\Models\OrderItem;
use Modules\Mall\Models\Reason;
use Modules\Mall\Models\Refund as RefundModel;
use MrwangTc\Kuaidi100\Exceptions\HttpException;
use MrwangTc\Kuaidi100\Express\Synquery;

class OrderController extends Controller
{

    /**
     * Notes   : 订单列表
     *
     * @Date   : 2021/5/13 5:17 下午
     * @Author : <Jason.C>
     * @param  Request  $request
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        $state = $request->state ?? '';
        $type  = $request->type ?? '';// score sample

        #todo 类别筛选
        #todo 商品名称搜索
        #todo 订单编号搜索

        $list = Order::byUser(Api::user())
            ->when($state, function ($query) use ($state) {
                switch ($state) {
                    case 'unpay':
                        $query->unPay();
                        break;
                    case 'paid':
                        $query->paid();
                        break;
                    case 'delivered':
                        $query->Delivered();
                        break;
                    case 'signed':
                        $query->signed();
                        break;
                    case 'completed':
                        $query->completed();
                        break;
                }
            }, function ($query) {
                $query->common();
            })
//            ->when($type, function ($q) use ($type) {
//                if ($type == 'score') {
//                    $q->TypeScore();
//                }
//
//                if ($type == 'sample') {
//                    $q->TypeSample();
//                }
//            })
            ->paginate();

        return $this->success(new OrderCollection($list));
    }

    /**
     * Notes   : 订单详情
     *
     * @Date   : 2021/5/13 5:17 下午
     * @Author : <Jason.C>
     * @param  Order  $order
     * @return mixed
     */
    public function show(Order $order)
    {
        if ($order->user()->isNot(Api::user())) {
            return $this->failed('', 404);
        }

        return $this->success(new OrderResource($order));
    }

    /**
     * Notes   : 查看物流
     *
     * @Date   : 2021/5/14 16:52
     * @Author : Mr.wang
     * @param  Order  $order
     * @return mixed
     * @throws HttpException
     */
    public function logistic(Order $order)
    {
        if ($order->user()->isNot(Api::user())) {
            return $this->failed('', 404);
        }
        if (! $order->is_logistic_show) {
            return $this->failed('', 404);
        }

        $express  = new Synquery();
        $synQuery = $express->pollQuery($order->express->express->slug, $order->express->express_no);
        if (isset($synQuery->result) && $synQuery->result === false) {
            return $this->failed($synQuery->message);
        }
        $logistics = $synQuery->data;

        return $this->success([
            'orderExpress' => new OrderLogisticResource($order->express),
            'logistics'    => LogisticResource::collection($logistics),
        ]);
    }

    /**
     * Notes   : 签收成功
     *
     * @Date   : 2021/5/17 16:52
     * @Author : Mr.wang
     * @param  Order  $order
     * @return mixed
     * @throws \Exception
     */
    public function sign(Order $order)
    {
        if ($order->user()->isNot(Api::user())) {
            return $this->failed('', 404);
        }
        if ($order->sign() === true) {
            return $this->success('操作成功');
        } else {
            return $this->failed();
        }
    }

    /**
     * Notes   : 取消订单
     *
     * @Date   : 2021/5/19 11:35
     * @Author : Mr.wang
     * @param  Order  $order
     * @return mixed
     */
    public function cancel(Order $order)
    {
        if ($order->user()->isNot(Api::user())) {
            return $this->failed('', 404);
        }
        try {
            $order->cancel();

            return $this->success('操作成功');
        } catch (Exception $e) {
            return $this->failed($e->getMessage());
        }
    }

    /**
     * Notes   : 删除订单（对订单进行软删除操作）
     *
     * @Date   : 2021/5/19 11:35
     * @Author : Mr.wang
     * @param  Order  $order
     * @return mixed
     */
    public function destroy(Order $order)
    {
        if ($order->user()->isNot(Api::user())) {
            return $this->failed('', 404);
        }
        if ($order->canDelete() === false) {
            return $this->failed('订单不允许删除');
        }
        try {
            $order->delete();

            return $this->success('操作成功');
        } catch (Exception $e) {
            return $this->failed($e->getMessage());
        }
    }

    /**
     * Notes: 订单商品
     *
     * @Author: 玄尘
     * @Date  : 2021/5/18 8:47
     * @param  Order  $order
     * @return mixed
     */
    public function goods(Order $order)
    {
        $user = Api::user();

        if ($order->user()->isNot($user)) {
            return $this->failed('', 404);
        }
        $data = [
            'order' => new OrderResource($order),
            'title' => Reason::query()->pluck('title'),
        ];

        return $this->success($data);
    }

    /**
     * Notes: 退款/退货
     *
     * @Author: 玄尘
     * @Date  : 2021/5/19 9:11
     * @param  Order  $order
     * @param  Request  $request
     * @return mixed
     */
    public function refund(Order $order, Request $request)
    {
        $user = Api::user();

        if (! $order->type == Order::TYPE_SAMPLE) {
            return $this->failed('操作失败，提货单不可退货');
        }

        if (! $order->can('refund')) {
            return $this->failed('操作失败，此订单不可退货');
        }

        if ($order->user()->isNot($user)) {
            return $this->failed('您没有权限进行此操作');
        }

        $remark   = $request->remark ?? '';
        $title    = $request->title;//退款原因
        $pictures = $request->pictures;//图片 many

        if (! $order->isPay()) {
            return $this->failed('退款失败，未找到支付信息');
        }

        try {
            (new Refund)->user($user)
                ->remark($remark)
                ->order($order)
                ->logs([
                    'remark'   => $remark,
                    'title'    => $title,
                    'pictures' => $pictures,
                ])
                ->create();

            return $this->success('提交成功，请等待审核。');
        } catch (Exception $e) {
            return $this->failed($e->getMessage());
        }

    }

    /**
     * Notes   : 个人中心对订单的总数
     *
     * @Date   : 2021/6/3 13:36
     * @Author : Mr.wang
     * @return mixed
     */
    public function counts()
    {
        $orderCount  = Order::byUser(Api::user())->common()->count();
        $refundCount = RefundModel::byUser(Api::user())->count();

        return $this->success([
            'orderCount'  => $orderCount,
            'refundCount' => $refundCount,
        ]);
    }

}
