<?php

namespace App\Admin\Repositories;

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

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

    //合同类型
    public const CTYPE = [
        1 => '民事诉讼代理',
        2 => '刑事诉讼辩护及代理',
        3 => '行政诉讼代理',
        4 => '非诉讼法律事务',
        5 => '咨询和代写法律文书',
        6 => '仲裁业务',
        7 => '法律援助',
        8 => '其它',
    ];

    //结算方式
    public const PAYMENT_METHOD = [
        1 => '开票付款',
        2 => '付款开票'
    ];

    // public function covenant()
    // {
    //     return  $this->belongsTo(ModelsCovenant::class, 'cid', 'id');
    // }

    public function get(Grid\Model $model)
    {
        // 获取当前页数
        $currentPage = $model->getCurrentPage();
        // 获取每页显示行数,从请求参数中获取,默认50
        $perPage = $model->filter()->input('per_page', 50);

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

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

        // 获取筛选条件
        $lawyerID = $model->filter()->input('no') ?? 0;
        $number = $model->filter()->input('number') ?? ''; //合同编号
        $cname = $model->filter()->input('cname');
        $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, // 添加这行
            'search'   => ['lawyer_id' => $lawyerID, 'number' => $number, 'cname' => $cname, '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'] ?? 50;
        $stepstart = $param['start'] ?? 0;
        $lawyer_id = $param['search']['lawyer_id'] ?? 0;
        $number = $param['search']['number'] ?? '';
        $cname = $param['search']['cname'] ?? '';
        $invoiced_at = $param['search']['invoiced_at'] ?? [];
        $principal = $param['search']['principal'] ?? '';
        $received_at = $param['search']['received_at'] ?? [];
        $list = $condition = [];
        if ($lawyer_id) {
            $condition['c.lawyer_id'] = $lawyer_id;
        }
        if ($number) {
            $condition['c.number'] = $number;
        }
        if ($principal) {
            $condition['c.principal'] = $principal;
        }
        if ($cname) {
            $condition['c.cname'] = $cname;
        }

        DB::enableQueryLog();
        $note_monitor = DB::table('covenant as c')
            ->select(['rp.*', 'c.id as cid', 'c.cname', 'c.ctype', 'c.number', 'c.lawyer_id', 'c.principal'])
            ->leftJoin('covenant_receive_payment AS rp', 'rp.cid', '=', 'c.id')
            ->where($condition)
            ->whereNull('c.deleted_at')  // 添加软删除条件
            ->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])
                        ->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; //$note_monitor->count();
        $cObj = $note_monitor->groupBy('c.id')->get();
        if ($cObj->toArray()) {
            $count = count($cObj->toArray());
        }
        // 获取列表
        $data = [];
        $list = $note_monitor->limit($prePage)->offset($stepstart)->orderBy('c.id', 'desc')->get()->toArray();
        $queries = DB::getQueryLog();
        // echo "<pre>";
        // print_r($queries);
        // die;

        foreach ($list as $key => $item) {
            $tmp = [];
            $tmp['cid'] = $item->cid;
            $tmp['number'] = $item->number;
            $tmp['cname'] = $item->cname;
            $tmp['ctype'] = $item->ctype;
            $tmp['principal'] = $item->principal;
            $cid = $item->cid;
            $lawyer_id = $item->lawyer_id;
            //开票金额
            $invoiced_money = ModelsCovenantReceivePayment::where(['cid' => $cid,'lawyer_id' => $lawyer_id, 'rtype' => 2])->whereNull('deleted_at')->sum('invoiced_money');
            //Log::add("debug: ",'invoiced_money:'.$invoiced_money.';lawyer_id:'.$lawyer_id.';cid:'.$item->cid);

            //已收款
            $receipt_money = ModelsCovenantReceivePayment::where(['cid' => $cid,'lawyer_id' => $lawyer_id, 'rtype' => 1])->whereNull('deleted_at')->sum('received_amount');

            $tmp['invoice_amount'] = number_format($invoiced_money, 2);
            $tmp['receipt_money'] = number_format($receipt_money, 2);
            //已收款未开票
            $receipt_noinvoice = ($receipt_money - $invoiced_money) > 0 ? number_format($receipt_money - $invoiced_money, 2) : '-';
            $tmp['receipt_noinvoice'] = $receipt_noinvoice;
            //已开票未收款
            $invoice_noreceipt = ($invoiced_money - $receipt_money) > 0 ? number_format($invoiced_money - $receipt_money, 2) : '-';
            $tmp['invoice_noreceipt'] = $invoice_noreceipt;
            array_push($data, $tmp);
        }

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