<?php

namespace App\Admin\Forms;

use App\Command\Log;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
use App\Models\Covenant as ModelsCovenant;
use App\Models\CovenantReceivePayment as ModelsCovenantReceivePayment;

class CovenantInvoiceForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $cid = $this->payload['cid']; //合同ID
        DB::beginTransaction();
        try {
            $invoiced_at = trim($input['invoiced_at']);
            $invoiced_money = trim($input['invoiced_money']);
            $datearr = explode('-', $invoiced_at);
            $year = $datearr[0];
            $month = $datearr[1];

            $cObj = ModelsCovenant::find($cid);
            if (!$cObj) {
                throw new Exception('该合同不存在!');
            }
            $receivePaymentObj = new ModelsCovenantReceivePayment();
            $receivePaymentObj->invoiced_money = $invoiced_money;
            $receivePaymentObj->year = $year;
            $receivePaymentObj->month = $month;
            $receivePaymentObj->rtype = 2;
            $receivePaymentObj->cid = $cid;
            $receivePaymentObj->lawyer_id = $cObj->lawyer_id;
            $receivePaymentObj->principal = $cObj->principal;
            $receivePaymentObj->invoiced_at = $invoiced_at;
            $receivePaymentObj->save();

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->response()->error($exception->getMessage())->refresh();
        }
        return $this->response()->success('提交成功')->refresh();
    }


    /**
     * Build a form here.
     */
    public function form()
    {
        $this->date('invoiced_at', '开票时间')->format('YYYY-MM-DD')->default(date("Y-m-d"))->required();
        $this->text('invoiced_money', '开票金额')->required();
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        // 获取外部传递参数
        return [];
    }
}