<?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;

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

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

    //结算方式
    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();
        // 获取每页显示行数
        $perPage = $model->getPerPage();

        $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,
            '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'] ?? 20;
        $start = $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['rp.lawyer_id'] = $lawyer_id;
        }
        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 = DB::table('covenant_receive_payment AS rp')
                        ->select(['rp.*', 'c.cname', 'c.ctype'])
                        ->leftJoin('covenant as c', 'rp.cid', '=', 'c.id')
                        ->whereBetween('rp.received_at', [$re_start, $re_end])
                        ->whereBetween('rp.invoiced_at', [$in_start, $in_end])
                        ->where($condition)
                        ->groupBy('rp.cid');
                } else {
                    if ($in_end) {
                        $note_monitor = DB::table('covenant_receive_payment AS rp')
                            ->select(['rp.*', 'c.cname', 'c.ctype'])
                            ->leftJoin('covenant as c', 'rp.cid', '=', 'c.id')
                            ->whereDate('rp.received_at', '>', $re_start)
                            ->whereBetween('rp.invoiced_at', [$in_start, $in_end])
                            ->where($condition)
                            ->groupBy('rp.cid');
                    } elseif ($re_end) {
                        $note_monitor = DB::table('covenant_receive_payment AS rp')
                            ->select(['rp.*', 'c.cname', 'c.ctype'])
                            ->leftJoin('covenant as c', 'rp.cid', '=', 'c.id')
                            ->whereDate('rp.invoiced_at', '>', $in_start)
                            ->whereBetween('rp.received_at', [$re_start, $re_end])
                            ->where($condition)
                            ->groupBy('rp.cid');
                    } else {
                        $note_monitor = DB::table('covenant_receive_payment AS rp')
                            ->select(['rp.*', 'c.cname', 'c.ctype'])
                            ->leftJoin('covenant as c', 'rp.cid', '=', 'c.id')
                            ->whereDate('rp.invoiced_at', '>', $in_start)
                            ->whereDate('rp.received_at', '>', $re_start)
                            ->where($condition)
                            ->groupBy('rp.cid');
                    }
                }
            }
            // 计算列表总数
            $count = $note_monitor->count();
            // 获取列表
            $data = [];
            $list = $note_monitor->limit($prePage)->offset($start)->orderBy('rp.cid', 'desc')->get()->toArray();
        } elseif ($invoiced_at['start'] && !$received_at['start']) { //开票日期
            $start = $invoiced_at['start'] ?? '';
            $end = $invoiced_at['end'] ?? '';

            if ($start) {
                if ($end) {
                    $note_monitor = DB::table('covenant_receive_payment AS rp')
                        ->select(['rp.*', 'c.cname', 'c.ctype'])
                        ->leftJoin('covenant as c', 'rp.cid', '=', 'c.id')
                        ->whereBetween('rp.received_at', [$start, $end])
                        ->where($condition)
                        ->groupBy('rp.cid');
                } else {
                    $note_monitor = DB::table("covenant_receive_payment as rp")
                        ->select(['rp.*', 'c.cname', 'c.ctype'])
                        ->leftJoin('covenant as c', 'rp.cid', '=', 'c.id')
                        ->whereDate('rp.received_at', '>', $start)
                        ->where($condition)
                        ->groupBy('rp.cid');
                }
                // 计算列表总数
                $count = $note_monitor->count();
                // 获取列表
                $data = [];
                $list = $note_monitor->limit($prePage)->offset($start)->orderBy('rp.cid', 'desc')->get()->toArray();
            }
            //
        } elseif ($received_at['start'] && !$invoiced_at['start']) { //收款日期
            $start = $received_at['start'] ?? '';
            $end = $received_at['end'] ?? '';

            if ($start) {
                if ($end) {
                    $note_monitor = DB::table('covenant_receive_payment AS rp')
                        ->select(['rp.*', 'c.cname', 'c.ctype'])
                        ->leftJoin('covenant as c', 'rp.cid', '=', 'c.id')
                        ->whereBetween('rp.received_at', [$start, $end])
                        ->where($condition)
                        ->groupBy('rp.cid');
                } else {
                    $note_monitor = DB::table("covenant_receive_payment as rp")
                        ->select(['rp.*', 'c.cname', 'c.ctype'])
                        ->leftJoin('covenant as c', 'rp.cid', '=', 'c.id')
                        ->whereDate('rp.received_at', '>', $start)
                        ->where($condition)
                        ->groupBy('rp.cid');
                }
                // 计算列表总数
                $count = $note_monitor->count();
                // 获取列表
                $data = [];
                $list = $note_monitor->limit($prePage)->offset($start)->orderBy('rp.cid', 'desc')->get()->toArray();
            }
        } else { //关键词搜索
            $note_monitor = DB::table('covenant')->select(['id as cid', 'number', 'cname', 'principal', 'ctype']);
            if ($lawyer_id) {
                $note_monitor = $note_monitor->where("lawyer_id", $lawyer_id);
            }
            if ($number) {
                $note_monitor = $note_monitor->where("number", $number);
            }
            if ($cname) {
                $note_monitor = $note_monitor->where("cname", $cname);
            }
            if ($principal) {
                $note_monitor = $note_monitor->where("principal", $principal);
            }
            // 计算列表总数
            $count = $note_monitor->count();

            // 获取列表
            $data = [];
            $list = $note_monitor->limit($prePage)->offset($start)->get()->toArray();
        }

        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;
            //开票金额
            $invoiced_money = ModelsCovenantReceivePayment::where(['cid' => $cid, 'rtype' => 2])->sum('invoiced_money');
            //已收款
            $receipt_money = ModelsCovenantReceivePayment::where(['cid' => $cid, 'rtype' => 1])->sum('received_amount');

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

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