<?php

namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class DealRecord extends Base
{
    //表名声明
    protected $table = 'yh_deal_record';
    use SoftDeletes;

    //主键声明
    protected $primaryKey = 'id';
    protected $dates = ['deleted_at'];

    public function getList($where, $field, $pagesize, $order, $sort, $orderWhereIn, $userInfo, $specialSearch)
    {
//        DB::enableQueryLog();
        if (empty($order)) {
            $order = $this->primaryKey;
        }

        $tmpOrm = $this->where($where);

        if (count($orderWhereIn) > 0) {
            foreach($orderWhereIn as $k => $v){
                $tmpOrm = $tmpOrm ->whereIn($k, $v);
            }
        }

        // 能看到 所有已提交 + 自己的待提交
        if ($specialSearch) {
            $tmpOrm = $tmpOrm->where(function ($query) use ($userInfo) {
                $query->where('check_status', '>', 0)
                    ->orWhere(function ($query) use ($userInfo) {
                        $query->where('check_status', 0)->where('created_by', $userInfo['id']);
                    });
            });
        }

        // 获取总数
        $total = $tmpOrm->sum('deduction_money');

        // "select `id`, `user_name`, `class_phone`, `deduction_money`, `remain_money`, `repay_money`, `deal_goods`, `reception_name`, `deal_date`, `department`, `province_name`, `status`, `is_set_express`, `status_remark`, `check_status`, `check_remark` from `yh_deal_record` where (`check_status` > 0 or (`check_status` = 0 and `created_by` = 1)) and `yh_deal_record`.`deleted_at` is null order by `id` desc limit 20 offset 0"

        $data = $tmpOrm->select($field)
            ->orderBy($order, $sort)
            ->paginate($pagesize);

        // 获取法院总数
        $courtOrm = $tmpOrm;
        $courtTotal = $courtOrm->where(['is_court' => 1])->sum('deduction_money');

//        var_dump(DB::getQueryLog());die;

        if (empty($data)) {
            return [
                'data' => [],
                'total' => 0,
                'court_total' => 0,
            ];
        } else {
            return [
                'data' => $data->toArray(),
                'total' => $total,
                'court_total' => $courtTotal ?? 0,
            ];
        }
    }

}
