<?php

namespace App\Admin\Repositories;

use App\Models\Covenant as ModelsCovenant;
use App\Models\LawyerCost as ModelsLawyerCost;
use App\Models\CovenantReceivePayment as ModelCovenantReceivePayment;
use App\Models\Principal;
use Dcat\Admin\Repositories\EloquentRepository;
use Dcat\Admin\Grid;
use Illuminate\Support\Facades\DB;

class LawyerCollect 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('number');
        $lname = $model->filter()->input('name');
        $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'   => ['number' => $number, 'lname' => $lname, '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;
        $number = $param['search']['number'] ?? '';
        $lname = $param['search']['lname'] ?? '';
        $invoiced_at = $param['search']['invoiced_at'] ?? [];
        $received_at = $param['search']['received_at'] ?? [];
        $list = [];
        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.*', 'l.name as lname', 'l.number as lnumber', 'l.commission_rate'])
                        ->leftJoin('lawyer as l', 'rp.lawyer_id', '=', 'l.id')
                        ->whereBetween('rp.received_at', [$re_start, $re_end])
                        ->whereBetween('rp.invoiced_at', [$in_start, $in_end])
                        ->groupBy('rp.lawyer_id');
                } else {
                    if ($in_end) {
                        $note_monitor = DB::table('covenant_receive_payment AS rp')
                            ->select(['rp.*', 'l.name as lname', 'l.number as lnumber', 'l.commission_rate'])
                            ->leftJoin('lawyer as l', 'rp.lawyer_id', '=', 'l.id')
                            ->whereDate('rp.received_at', '>', $re_start)
                            ->whereBetween('rp.invoiced_at', [$in_start, $in_end])
                            ->groupBy('rp.lawyer_id');
                    } elseif ($re_end) {
                        $note_monitor = DB::table('covenant_receive_payment AS rp')
                            ->select(['rp.*', 'l.name as lname', 'l.number as lnumber', 'l.commission_rate'])
                            ->leftJoin('lawyer as l', 'rp.lawyer_id', '=', 'l.id')
                            ->whereDate('rp.invoiced_at', '>', $in_start)
                            ->whereBetween('rp.received_at', [$re_start, $re_end])
                            ->groupBy('rp.lawyer_id');
                    } else {
                        $note_monitor = DB::table('covenant_receive_payment AS rp')
                            ->select(['rp.*', 'l.name as lname', 'l.number as lnumber', 'l.commission_rate'])
                            ->leftJoin('lawyer as l', 'rp.lawyer_id', '=', 'l.id')
                            ->whereDate('rp.invoiced_at', '>', $in_start)
                            ->whereDate('rp.received_at', '>', $re_start)
                            ->groupBy('rp.lawyer_id');
                    }
                }
            }
            // 计算列表总数
            $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.*', 'l.name as lname', 'l.number as lnumber', 'l.commission_rate'])
                        ->leftJoin('lawyer as l', 'rp.lawyer_id', '=', 'l.id')
                        ->whereBetween('rp.received_at', [$start, $end])
                        ->groupBy('rp.lawyer_id');
                } else {
                    $note_monitor = DB::table("covenant_receive_payment as rp")
                        ->select(['rp.*', 'l.name as lname', 'l.number as lnumber', 'l.commission_rate'])
                        ->leftJoin('lawyer as l', 'rp.lawyer_id', '=', 'l.id')
                        ->whereDate('rp.received_at', '>', $start)
                        ->groupBy('rp.lawyer_id');
                }
                // 计算列表总数
                $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.*', 'l.name as lname', 'l.number as lnumber', 'l.commission_rate'])
                        ->leftJoin('lawyer as l', 'rp.lawyer_id', '=', 'l.id')
                        ->whereBetween('rp.received_at', [$start, $end])
                        ->groupBy('rp.lawyer_id');
                } else {
                    $note_monitor = DB::table("covenant_receive_payment as rp")
                        ->select(['rp.*', 'l.name as lname', 'l.number as lnumber', 'l.commission_rate'])
                        ->leftJoin('lawyer as l', 'rp.lawyer_id', '=', 'l.id')
                        ->whereDate('rp.received_at', '>', $start)
                        ->groupBy('rp.lawyer_id');
                }
                // 计算列表总数
                $count = $note_monitor->count();
                // 获取列表
                $data = [];
                $list = $note_monitor->limit($prePage)->offset($start)->orderBy('rp.cid', 'desc')->get()->toArray();
            }
        } else { //关键词搜索
            $note_monitor = DB::table('lawyer as ly')->select(['id as lawyer_id', 'number as lnumber', 'name as lname', 'commission_rate']);
            if ($number) {
                $note_monitor = $note_monitor->where("number", $number);
            }
            if ($lname) {
                $note_monitor = $note_monitor->where("name", $lname);
            }
            // 计算列表总数
            $count = $note_monitor->count();

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

        foreach ($list as $key => $item) {
            $tmp = [];
            //$tmp['id'] = $item->id;
            $tmp['lnumber'] = $item->lnumber;
            $tmp['lname'] = $item->lname;
            $tmp['commission_ratio'] = $item->commission_rate;
            $tmp['receipt_money'] = ModelCovenantReceivePayment::getReceivedMoney($item->lawyer_id);
            $tmp['commission_amount'] = self::getCommissionAmount($item->lawyer_id, $item->commission_rate);
            $tmp['receipt_noinvoice'] = ModelCovenantReceivePayment::getReceiptNoinvoice($item->lawyer_id);
            $tmp['invoice_noreceipt'] = ModelCovenantReceivePayment::getInvoiceNoreceipt($item->lawyer_id);
            $tmp['cost'] = '7';
            $tmp['basic_salary'] = ModelsLawyerCost::getBasiSalary($item->lawyer_id);
            $tmp['special_additional'] = ModelsLawyerCost::getSpecialAdditional($item->lawyer_id);
            $tmp['social'] = ModelsLawyerCost::getSocial($item->lawyer_id);
            $tmp['accumulation_fund'] = ModelsLawyerCost::getAccumulationFund($item->lawyer_id);
            $tmp['posting_tickets_fee'] = '9';
            $tmp['advance_fee'] = ModelsLawyerCost::getAdvanceFee($item->lawyer_id);
            $tmp['payable_commission'] = self::getPayableAmount($item->lawyer_id, $item->commission_rate);
            array_push($data, $tmp);
        }

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

    public static function getPayableAmount($lawyer_id, $commission_rate)
    {
        $received_money = ModelCovenantReceivePayment::getReceivedMoney($lawyer_id); //创收已收款
        $paid_amount =  ModelsLawyerCost::getPaidAmount($lawyer_id); //已支付款项
        $result = $received_money * ($commission_rate / 100) - $paid_amount;
        return sprintf('%.2f', $result);
    }
    //提成金额
    public static function getCommissionAmount($lawyer_id, $commission_rate)
    {
        $received_money = ModelCovenantReceivePayment::getReceivedMoney($lawyer_id); //创收已收款
        $result = $received_money * ($commission_rate / 100);
        return sprintf('%.2f', $result);
    }
}