<?php

namespace app\repository;

use app\exception\RepositoryException;
use app\model\Business;
use app\model\BusinessFlow;
use app\model\CouponBill;
use app\model\CouponMain;
use app\model\Deduction;
use app\model\Recharge;
use app\service\Repository;
use think\Collection;
use think\Model;

/**
 * 流水相关
 *
 * Class BusinessRepository
 * @package app\repository
 * @method self getInstance(Model $model = null) static
 */
class BillRepository extends Repository

{
    /**
     * 流水列表
     * @param $page
     * @param $size
     * @param $keyword
     * @param null $startTime
     * @param null $endTime
     * @param array $orders
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function billList($page, $size, $keyword = null, $startTime = null, $endTime = null,  $orders = ["id" => "desc"])
    {
        $failData = [
            'total' => 0,
            'current' => $page,
            'size' => $size,
            'list' => new Collection(),
        ];
        $rep = CouponBill::with([
            "business" => function ($query) use ($keyword) {
                $query->field(["code", "business_name"])->when(empty($keyword), function ($q) use ($keyword) {
                    $q->where("business_name", "like", "%$keyword%");
                });
            },
            "account" => function ($q) {
                $q->field(["user_code", "nick_name"]);
            },
            "couponMain" => function ($q) {
                $q->field(["id", "name"]);
            },
        ])
            ->when(!empty($startTime), function ($q) use ($startTime) {
                $q->whereTime("create_time", ">=", $startTime);
            })
            ->when(!empty($endTime), function ($q) use ($endTime) {
                $q->whereTime("create_time", "<=", $endTime);
            });

        $failData ['total'] = $rep->count();
        $failData ['list'] = $rep
            ->page($page, $size)
            ->order($orders)
            ->select();
        return $failData;
    }


    /**
     * 总收益
     * @param $field
     * @param null $start_time
     * @param null $end_time
     * @return float
     */
    public function getAgencyMoneySum($field, $start_time = null, $end_time = null)
    {
        return CouponBill::when(!empty($start_time), function ($q) use ($start_time) {
            $q->whereTime("create_time", ">=", $start_time);
        })->when(!empty($end_time), function ($q) use ($end_time) {
            $q->whereTime("create_time", "<=", $end_time);
        })
            ->sum($field);
    }

}