<?php

namespace App\Http\Controllers\Settlement;

use App\Consts\BaseConst;
use App\Consts\ErrorConst;
use App\Libs\ApiResponse;
use App\Libs\Utils;
use App\Services\Settlement\SettlementService;
use App\Transformer\Settlement\SettlementTransformer;
use App\Exceptions\ApiException;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;

class SettlementController extends BaseController
{
    use ApiResponse;

    private $settlementService;

    public function __construct(
        SettlementService $settlementService
    )
    {
        $this->settlementService = $settlementService;
    }

    /**
     * 结算信息-汇总数据
     *
     * @return mixed
     */
    public function billsStat()
    {
        $result = $this->settlementService->billsStat();
        return $this->success($result);
    }

    /**
     * 结算列表
     *
     * @param Request $request
     * @return mixed
     * @throws ApiException
     */
    public function bills(Request $request)
    {
        $all = $request->only('date_range', 'export');

        // 时间判断
        $dateRange = getProp($all, 'date_range');
        if ($dateRange) {
            [$startDate, $endDate] = explode(',', $dateRange);

            // 开始日期不能大于结束日期
            if ($startDate > $endDate) {
                Utils::throwError(ErrorConst::DATE_START_GREATER_THAN_END);
            }

            // 不能选择近七日时间
            if ($endDate > date('Y-m-d', strtotime('-' . BaseConst::DATE_RANGE_DAYS . ' days'))) {
                Utils::throwError(ErrorConst::DATE_RANGE_LESS_THAN_7DAY);
            }
        }

        $result = $this->settlementService->bills($all);
        return $this->success($result, [new SettlementTransformer(), 'buildBills']);
    }

    /**
     * 结算单-订单明细
     *
     * @param Request $request
     * @return mixed
     * @throws ApiException
     */
    public function billOrders(Request $request)
    {
        $date = trim($request->get('date'));
        if (empty($date)) {
            Utils::throwError(ErrorConst::PARAM_ERROR_CODE);
        }

        $result = $this->settlementService->billOrders($date);
        return $this->paginate($result, [new SettlementTransformer(), 'buildBillOrders']);
    }

    /**
     * 提现列表
     *
     * @param Request $request
     * @return mixed
     */
    public function withdrawCashes(Request $request)
    {
        $all    = $request->only('date_range', 'status');
        $result = $this->settlementService->withdrawCashes($all);

        return $this->success($result, [new SettlementTransformer(), 'buildWithdrawCashes']);
    }

    /**
     * 提现
     *
     * @param Request $request
     * @return mixed
     * @throws ApiException
     */
    public function applyWithDraw(Request $request)
    {
        $all    = $request->only('amount', 'card_id', 'is_company');
        $result = $this->settlementService->applyWithDraw($all);

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