<?php

namespace App\Admin\Extensions;

use App\Command\Log;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use App\Models\CovenantReceivePayment as ModelsCovenantReceivePayment;


class ReceivedInvoicedExport implements FromCollection, WithHeadings
{
    private $row;
    private $data;
    private $headings;

    /**
     * TaskDataExcelExpoter constructor.
     * @param array $param 筛选条件
     * @param array $data 数据
     * @param array $headings 表头
     */
    public function __construct($param = [], $data = [], $headings = [])
    {
        $param = json_decode(json_encode($param), true);
        $year = $param['search']['year'] ?? date("Y");
        $nowyear = date("Y");
        $monthNum = ($year && $year < $nowyear)  ? 12 : date('m');
        //表头设定
        for ($i = 1; $i <= $monthNum; $i++) {
            $tmp[$i] = $i . '月';
        }
        $header = $tmp;
        $headings = [$header];

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

        $this->headings = $headings;
        $this->data = $data;
    }

    public function headings(): array
    {
        return $this->headings;
    }

    public function collection()
    {
        return collect($this->data);
    }


    // 获取列表数据
    public function getList($param)
    {
        $param = json_decode(json_encode($param), true);
        $lawyer_id = $param['search']['lawyer_id'] ?? 0;
        $rtype = $param['search']['rtype'] ?? 1;
        $year = $param['search']['year'] ?? date("Y");
        $data = [];
        $nowyear = date("Y");
        $monthNum = ($year && $year < $nowyear)  ? 12 : date('m');

        for ($i = 1; $i <= $monthNum; $i++) {
            if ($rtype == 1) { //已收款
                $amount = ModelsCovenantReceivePayment::where(['rtype' => $rtype, 'lawyer_id' => $lawyer_id, 'year' => $year, 'month' => $i])->sum('received_amount');
            } else { //已开票
                $amount = ModelsCovenantReceivePayment::where(['rtype' => $rtype, 'lawyer_id' => $lawyer_id, 'year' => $year, 'month' => $i])->sum('invoiced_money');
            }
            $data[$i] = $amount;
        }

        return [$data];


        return $data;
    }
}