<?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)
    {
        // 获取当前页数
        $currentPage = $model->getCurrentPage();
        // 获取每页显示行数
        $perPage = $model->getPerPage();

        $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,
            'search'   => [
                'lnum' => $number,
                'lname' => $lname,
                'cnum' => $cnum,
                'ctype' => $ctype,
                'principal' => $principal,
                'invoiced_at' => $invoiced_at,
                'received_at' => $received_at,
            ]
        ];

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

        return $model->makePaginator(
            $data['total'] ?? 0, // 传入总记录数
            $data['subjects'] ?? [] // 传入数据二维数组
        );
    }

    // 获取列表数据
    public function getList(array $param)
    {
        $prePage = $param['per_page'] ?? 20;
        $offset_start = $param['start'] ?? 0;
        $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');
        if ($lnum) {
            $note_monitor = $note_monitor->where("l.number", $lnum);
        }
        if ($lname) {
            $note_monitor = $note_monitor->where("l.name", $lname);
        }
        if ($cnum) {
            $note_monitor = $note_monitor->where("c.number", $cnum);
        }
        if ($ctype) {
            $note_monitor = $note_monitor->where("c.ctype", $ctype);
        }
        if ($principal) {
            $note_monitor = $note_monitor->where("c.principal", $principal);
        }
        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])
                        ->whereBetween('rp.invoiced_at', [$in_start, $in_end]);
                } else {
                    if ($in_end) {
                        $note_monitor = $note_monitor->whereDate('rp.received_at', '>', $re_start)
                            ->whereBetween('rp.invoiced_at', [$in_start, $in_end]);
                    } elseif ($re_end) {
                        $note_monitor = $note_monitor->whereDate('rp.invoiced_at', '>', $in_start)
                            ->whereBetween('rp.received_at', [$re_start, $re_end]);
                    } else {
                        $note_monitor = $note_monitor->whereDate('rp.invoiced_at', '>', $in_start)
                            ->whereDate('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);
                }
            }
        }
        // 计算列表总数
        $count = 0;
        $cObj = $note_monitor->groupBy('rp.cid')->get();
        if ($cObj->toArray()) {
            $count = count($cObj->toArray());
        }

        // 获取列表
        $data = [];
        $list = $note_monitor->groupBy('rp.cid')
            ->limit($prePage)
            ->offset($offset_start)
            ->get()
            ->toArray();
        //$queries = DB::getQueryLog();


        foreach ($list as $key => $item) {
            $tmp = [];
            //$tmp['id'] = $item->id;
            $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'] = $item->invoiced_money;
            $tmp['receipt_money'] = $item->received_amount;
            $receipt_noinvoice = $item->received_amount - $item->invoiced_money;
            $tmp['receipt_noinvoice'] = $receipt_noinvoice > 0 ? $receipt_noinvoice : '-';
            $invoice_noreceipt = $item->invoiced_money - $item->received_amount;
            $tmp['invoice_noreceipt'] = $invoice_noreceipt > 0 ? $invoice_noreceipt : '-';
            array_push($data, $tmp);
        }

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