<?php

namespace app\api\service\statistics;

use app\api\model\OrderRefund;
use app\common\enum\order\refund\RefundStatus;
use app\common\service\BaseService;

class RefundData extends BaseService
{
    protected OrderRefund $refundModel;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->refundModel = new OrderRefund();
    }

    public function getRefundData($startDate = null, $endDate = null): array
    {
        return [
            'refundCount' => $this->getRefundCount($startDate, $endDate),
            'refundTotalMoney' => $this->getRefundTotalMoney($startDate, $endDate)
        ];
    }

    /**
     * 退款总数
     */
    public function getRefundCount($startDate = null, $endDate = null): int
    {
        $query = $this->refundModel;
        $filter = [];
        if (!is_null($startDate) && !is_null($endDate)) {
            $filter[] = ['create_time', '>=', strtotime($startDate)];
            $filter[] = ['create_time', '<', strtotime($endDate) + 86400];
        }
        return $query->where($filter)->where('status', '=', RefundStatus::COMPLETED)->count();
    }

    /**
     * 退款总金额
     */
    public function getRefundTotalMoney($startDate = null, $endDate = null): float {
        $query = $this->refundModel;
        $filter = [];
        if (!is_null($startDate) && !is_null($endDate)) {
            $filter[] = ['create_time', '>=', strtotime($startDate)];
            $filter[] = ['create_time', '<', strtotime($endDate) + 86400];
        }
        // 总销售额
        return $query->where($filter)->where('status', '=', RefundStatus::COMPLETED)->sum('refund_money');
    }
}