<?php

namespace App\Admin\Repositories;

use App\Command\Log;
use App\Models\Covenant as ModelsCovenant;
use App\Models\Principal as ModelsPrincipal;
use App\Models\CovenantReceivePayment;
use Dcat\Admin\Repositories\EloquentRepository;
use Dcat\Admin\Grid;
use Illuminate\Support\Facades\DB;

class CovenantReceivePaymentCollect extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = ModelsCovenant::class;


    public function get(Grid\Model $model)
    {
        // 获取当前页数,如果为空则默认为第1页
        $currentPage = $model->getCurrentPage() ?: 1;
        // 获取每页显示行数,如果为空则默认为20条
        $perPage = $model->getPerPage() ?: 20;

        $start = ($currentPage - 1) * $perPage;

        // 获取排序参数, 格式例如['id', 'asc', null]
        $sort = $model->getSort();

        // 获取筛选条件
        $number = $model->filter()->input('lnum');
        $lname = $model->filter()->input('lname');
        $cnum = $model->filter()->input('cnum');
        $ctype = $model->filter()->input('ctype');
        $principal = $model->filter()->input('principal');
        $received_at = $invoiced_at = [];
        $received_at['start'] = $_GET['received_at']['start'] ?? '';
        $received_at['end'] = $_GET['received_at']['end'] ?? '';
        $invoiced_at['start'] = $_GET['invoiced_at']['start'] ?? '';
        $invoiced_at['end'] = $_GET['invoiced_at']['end'] ?? '';

        $param = [
            'sort'     => $sort,
            'start'     => $start,
            'per_page'  => $perPage,
            'current_page' => $currentPage,
            'search'   => [
                'lnum' => $number,
                'lname' => $lname,
                'cnum' => $cnum,
                'ctype' => $ctype,
                'principal' => $principal,
                'invoiced_at' => $invoiced_at,
                'received_at' => $received_at,
            ]
        ];

        $data = $this->getList($param);

        // 确保total和数据都是有效的
        $items = $data['subjects'] ?? [];
        $total = count($items); // 直接使用实际的数据数量作为总数
        
        Log::add('Pagination data:', [
            'total' => $total,
            'items_count' => count($items),
            'current_page' => $currentPage,
            'per_page' => $perPage
        ]);

        // 确保分页参数有效
        if ($perPage <= 0) {
            $perPage = 20;
        }

        return $model->makePaginator(
            $total,
            $items
        );
    }

    // 获取列表数据
    public function getList(array $param)
    {
        $currentPage = max((int)($param['current_page'] ?? 1), 1); // 确保当前页码至少为1
        $prePage = max((int)($param['per_page'] ?? 20), 1);  // 确保每页至少显示1条记录
        $offset_start = ($currentPage - 1) * $prePage;  // 使用currentPage重新计算offset
        $lnum = $param['search']['lnum'] ?? '';
        $lname = $param['search']['lname'] ?? '';
        $cnum = $param['search']['cnum'] ?? '';
        $ctype = $param['search']['ctype'] ?? '';
        $principal = $param['search']['principal'] ?? '';
        $invoiced_at = $param['search']['invoiced_at'] ?? [];
        $received_at = $param['search']['received_at'] ?? [];
        $list = [];
        DB::enableQueryLog();
        $note_monitor = DB::table("covenant_receive_payment as rp")
            ->select(DB::raw('rp.cid, c.cname,c.ctype,c.number as cnum,c.principal,c.principal_id,l.number as lnum,l.name as lname,sum(invoiced_money) as invoiced_money,sum(received_amount) as received_amount'))
            //->select(['rp.cid', 'c.cname', 'c.ctype', 'c.number as cnum', 'c.principal', 'l.number as lnum', 'l.name as lname', 'sum(invoiced_money) as invoiced_money'])
            ->leftJoin('covenant as c', 'rp.cid', '=', 'c.id')
            ->leftJoin('lawyer as l', 'rp.lawyer_id', '=', 'l.id')
            ->whereNull('rp.deleted_at');

        if ($invoiced_at['start'] && $received_at['start']) {
            $in_start = $invoiced_at['start'] ?? '';
            $in_end = $invoiced_at['end'] ?? '';
            $re_start = $received_at['start'] ?? '';
            $re_end = $received_at['end'] ?? '';
            if ($in_start && $re_start) {
                if ($in_end && $re_end) {
                    $note_monitor = $note_monitor->whereBetween('rp.received_at', [$re_start, $re_end])
                        ->orWhereBetween('rp.invoiced_at', [$in_start, $in_end]);
                } else {
                    if ($in_end) {
                        $note_monitor = $note_monitor->whereDate('rp.received_at', '>', $re_start)
                            ->orWhereBetween('rp.invoiced_at', [$in_start, $in_end]);
                    } elseif ($re_end) {
                        $note_monitor = $note_monitor->whereDate('rp.invoiced_at', '>', $in_start)
                            ->orWhereBetween('rp.received_at', [$re_start, $re_end]);
                    } else {
                        $note_monitor = $note_monitor->whereDate('rp.invoiced_at', '>', $in_start)
                            ->orWhereDate('rp.received_at', '>', $re_start);
                    }
                }
            }
        } elseif ($invoiced_at['start'] && !$received_at['start']) { //开票日期
            $start = $invoiced_at['start'] ?? '';
            $end = $invoiced_at['end'] ?? '';

            if ($start) {
                if ($end) {
                    $note_monitor = $note_monitor->whereBetween('rp.received_at', [$start, $end]);
                } else {
                    $note_monitor = $note_monitor->whereDate('rp.received_at', '>', $start);
                }
            }
            //
        } elseif ($received_at['start'] && !$invoiced_at['start']) { //收款日期
            $start = $received_at['start'] ?? '';
            $end = $received_at['end'] ?? '';

            if ($start) {
                if ($end) {
                    $note_monitor = $note_monitor->whereBetween('rp.received_at', [$start, $end]);
                } else {
                    $note_monitor = $note_monitor->whereDate('rp.received_at', '>', $start);
                }
            }
        }
        if ($lnum) {
            $note_monitor = $note_monitor->having("lnum", $lnum);
        }
        if ($lname) {
            $note_monitor = $note_monitor->having("lname", $lname);
        }
        if ($cnum) {
            $note_monitor = $note_monitor->having("cnum", $cnum);
        }
        if ($ctype) {
            $note_monitor = $note_monitor->having("ctype", $ctype);
        }
        if ($principal) {
            $note_monitor = $note_monitor->having("principal", $principal);
        }
        // 计算列表总数
        $count = 0;
        try {
            $cObj = clone $note_monitor;  // 克隆查询构建器以避免影响后续查询
            $count = $cObj->groupBy('rp.cid')->get()->count();  // 使用实际的记录数
        } catch (\Exception $e) {
            Log::add('Count error:', ['message' => $e->getMessage()]);
            $count = 0;
        }

        // 获取列表
        $data = [];
        try {
            $list = $note_monitor->groupBy('rp.cid')
                ->when($prePage > 0, function($query) use ($prePage, $offset_start) {
                    return $query->limit($prePage)->offset($offset_start);
                })
                ->get();

            foreach ($list as $key => $item) {
                $tmp = [];
                $tmp['lnum'] = $item->lnum;
                $tmp['lname'] = $item->lname;
                $tmp['covenant_num'] = $item->cnum;
                $tmp['covenant_name'] = $item->cname;
                $tmp['covenant_type'] = $item->ctype ? ModelsCovenant::CTYPE[$item->ctype] : '';

                $tmp['principal'] = $item->principal;
                $tmp['invoice_amount'] = number_format($item->invoiced_money, 2);
                $tmp['receipt_money'] = number_format($item->received_amount, 2);
                $receipt_noinvoice = $item->received_amount - $item->invoiced_money;
                $tmp['receipt_noinvoice'] = $receipt_noinvoice > 0 ? number_format($receipt_noinvoice, 2) : '-';
                $invoice_noreceipt = $item->invoiced_money - $item->received_amount;
                $tmp['invoice_noreceipt'] = $invoice_noreceipt > 0 ? number_format($invoice_noreceipt, 2) : '-';
                array_push($data, $tmp);
            }
        } catch (\Exception $e) {
            Log::add('List error:', ['message' => $e->getMessage()]);
            $data = [];
        }

        return [
            'total' => $count,
            'subjects' => $data
        ];
    }
}