<?php

namespace App\Domains\Virtual\Http\Controllers;

use Carbon\Carbon;
use App\Core\Controller;
use Illuminate\Http\Request;
use App\Exceptions\InvalidArgumentException;
use App\Domains\Virtual\Services\OrderService;

class RefundController extends Controller
{
    protected $request;
    protected $orderService;

    /**
     * 构造函数，自动注入.
     */
    public function __construct(Request $request, OrderService $orderService)
    {
        $this->request = $request;
        $this->orderService = $orderService;
    }

    /**
     * 列表.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $conditions = $this->request->all();
        $conditions['limit'] = $this->request->get('limit', 20);

        $refunds = $this->orderService->refundedList($conditions);

        return res($refunds, '退货列表', 201);
    }

    /**
     * 检查退货.
     *
     * @return \Illuminate\Http\Response
     */
    public function check()
    {
        $sim = $this->request->get('sim');

        if (empty($sim)) {
            throw new InvalidArgumentException('sim卡号不能为空');
        }

        $sim = array_map('intval', array_map('trim', str_to_array($sim, "\n")));

        $refunded_at = $this->request->get('refunded_at', date('Y-m-d H:i:s'));

        $refunded_at = Carbon::parse($refunded_at);

        $res = $this->orderService->refundedCheck($sim, $refunded_at);

        return res($res, '检查退货', 201);
    }

    /**
     * 添加退货.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $sim = $this->request->get('sim');

        if (empty($sim)) {
            throw new InvalidArgumentException('sim卡号不能为空');
        }

        $sim = array_map('intval', array_map('trim', str_to_array($sim, "\n")));

        $refunded_at = $this->request->get('refunded_at', date('Y-m-d H:i:s'));

        $refunded_at = Carbon::parse($refunded_at);

        $this->orderService->refundedCreate($sim, $refunded_at);

        return res(true, '退货成功');
    }
}
