<?php

namespace App\Http\Controllers;

use App\Components\AsyncResponse;
use App\Filters\ProcurementCheckSheetFilters;
use App\Filters\ProcurementFilters;
use App\Http\Requests\Procurement\EnquiryRequest;
use App\Http\Requests\Procurement\ProcurementAmountRequest;
use App\Http\Requests\Procurement\ProcurementRequest;
use App\Http\Requests\Procurement\ProofRequest;
use App\Jobs\ProcurementConfirmInform;
use App\Jobs\ProcurementEnquiry;
use App\Jobs\ProcurementReceive;
use App\Jobs\ProcurementWaitConfirmInform;
use App\Material;
use App\Owner;
use App\Procurement;
use App\ProcurementCheckSheet;
use App\ProcurementDeliverie;
use App\ProcurementTotalBill;
use App\Services\common\ExportService;
use App\Services\ConfigurationService;
use App\Services\LogService;
use App\Services\OwnerMaterialService;
use App\Services\ProcurementService;
use App\Services\ProcurementTotalBillService;
use App\Services\SupplierService;
use App\Supplier;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Matrix\Builder;

class ProcurementController extends Controller
{
    use AsyncResponse;

    private function newProcurement($param,$userId,$type=0,$status=0): Procurement
    {
        $procurement=new Procurement([
            'owner_material_id'=>$param['owner_material_id'],
            'quantity'=>$param['quantity'],
            'amount'=>$param['amount'],
            'unit_price'=>$param['unit_price'],
            'initiator'=>$userId,
            'type'=>$type,
            'status'=>$status,
        ]);
        $procurement->save();
        $number_id=$procurement['id'];
        $procurement_code='BSHC';
        $procurement_code .= date ("ymd").str_pad($number_id>99999?$number_id%99999:$number_id,4,"0",STR_PAD_LEFT);
        /** @var ProcurementService $procurementService*/
        $procurementService=app(ProcurementService::class);
        $deadline=$procurementService->computeDeadline(Carbon::now()->toDateTimeString());
        $procurement->update(['code'=>$procurement_code,'deadline'=>$deadline]);
        if ($procurement->type==0)  dispatch(new ProcurementEnquiry($procurement))->delay(Carbon::parse($deadline)); //采购单创建时 推送到队列中
        dispatch(new ProcurementConfirmInform($procurement));  //推送发送订单通知消息模板  队列
        return $procurement;
    }


    public function index(Request $request,ProcurementFilters $filters)
    {
        if(!Gate::allows('采购管理-采购-查询')){ return redirect(url('/'));  }
        $paginateParams=$request->input();
        $owner_ids=app('UserService')->getPermittingOwnerIds(auth()->user());
        $procurements = Procurement::query()
            ->orderByDesc('id')
            ->filter($filters)
            ->withCount('procurementQuotations')
            ->with(['initiator','ownerMaterial.file','ownerMaterial.material','supplier','ownerMaterial.owner'=>function($query)use($owner_ids){
                $query->with('customer')->whereIn('id',$owner_ids);
            },'procurementDeliveries','procurementQuotations.supplier'])
            ->whereHas('ownerMaterial',function($builder)use($owner_ids){
                $builder->whereHas('owner',function ($build)use($owner_ids){
                    $build->whereIn('id',$owner_ids);
                });
            })
            ->paginate($param['paginate'] ?? 50);
        foreach ($procurements as $procurement){
            if ($procurement->procurement_quotations_count>0 && $procurement->status==0) $procurement->status=1;
            if (empty($procurement->procurementDeliveries))continue;
            if (Carbon::now()->gt($procurement['deadline'])){
                $procurement->isFinishEnquiry=true;
            }else{
                $procurement->isFinishEnquiry=false;
            }
            $procurement->deliver_amount=$procurement->procurementDeliveries->sum('amount');
        }
        /** @var OwnerMaterialService $ownerMaterialService*/
        $ownerMaterialService=app(OwnerMaterialService::class);
        $owners=$ownerMaterialService->getOwnerPermittingWithMaterial();
        $materials=Material::query()->select('id','name')->get();
        $date=date('Y-m-d');
        $countReceive=ProcurementDeliverie::query()->where('signed_at',$date)->count();
        $countProcurement=Procurement::query()->where('type',0)->where('created_at','like',$date.'%')->count();
        return view('procurement/procurement/index',compact('procurements','owners','materials','paginateParams','countReceive','countProcurement'));
    }


    public function create()
    {
        if(!Gate::allows('采购管理-采购-新建')){ return ["success"=>false,"data"=>"您无此权限操作!"];  }
        /** @var OwnerMaterialService $ownerMaterialService*/
        $ownerMaterialService=app(OwnerMaterialService::class);
        $owners=$ownerMaterialService->getOwnerPermittingWithMaterial();
        return view('procurement/procurement/create',compact('owners'));
    }

    public function store(Request $request)
    {
        $this->gate('采购管理-采购-新建');
        $param=$request->all(['owner_material_id','quantity','amount','unit_price']);
        $procurement=$this->newProcurement($param,Auth::user()['id']);
        return redirect('procurement/procurement/index')->with('successTip','新采购单“'.$procurement->code.'”添加成功');
    }
    public function createProcurement(ProcurementRequest $request): array
    {

        $this->gate('采购管理-采购-新建');
        $request->validated();
        $param=$request->all(['owner_material_id','quantity','amount','unit_price']);
        $procurement=$this->newProcurement($param,Auth::user()['id']);
        $procurement = $procurement->loadMissing(['initiator','ownerMaterial.material','ownerMaterial.owner.customer','ownerMaterial.file','supplier']);
        if ($procurement) return ['success' => true,'data' => $procurement];
        else return ['success' => false, 'message' => '添加失败'];

    }
    //新增询价
    public function createEnquiry(EnquiryRequest $request): array
    {
        $this->gate('采购管理-采购-新建');
        $request->validated();
        $param=$request->all(['owner_material_id']);
        $procurement=new Procurement([
            'owner_material_id'=>$param['owner_material_id'],
            'quantity'=>0,
            'amount'=>0,
            'unit_price'=>0,
            'initiator'=>Auth::user()['id'],
            'type'=>1,
            'status'=>0,
        ]);
        $procurement->save();
        $number_id=$procurement['id'];
        $procurement_code='BSHC';
        $procurement_code .= date ("ymd").str_pad($number_id>99999?$number_id%99999:$number_id,4,"0",STR_PAD_LEFT);
        /** @var ProcurementService $procurementService*/
        $procurementService=app(ProcurementService::class);
        $deadline=$procurementService->computeDeadline($procurement->created_at);
        $procurement->update(['code'=>$procurement_code,'deadline'=>$deadline]);
        dispatch(new ProcurementConfirmInform($procurement));  //推送发送订单通知消息模板  队列
        $procurement = $procurement->loadMissing(['initiator','ownerMaterial.material','ownerMaterial.owner.customer','ownerMaterial.file','supplier']);
        if ($procurement) return ['success' => true,'data' => $procurement];
        else return ['success' => false, 'message' => '添加失败'];

    }
    //新增打样
    public function createProof(ProofRequest $request): array
    {
        $this->gate('采购管理-采购-新建');
        $request->validated();
        $param=$request->all(['owner_material_id']);
        $procurement=new Procurement([
            'owner_material_id'=>$param['owner_material_id'],
            'quantity'=>1,
            'amount'=>0,
            'unit_price'=>0,
            'initiator'=>Auth::user()['id'],
            'type'=>2,
            'status'=>2,
        ]);
        $procurement->save();
        $number_id=$procurement['id'];
        $procurement_code='BSHC';
        $procurement_code .= date ("ymd").str_pad($number_id>99999?$number_id%99999:$number_id,4,"0",STR_PAD_LEFT);
        /** @var ProcurementService $procurementService*/
        $procurementService=app(ProcurementService::class);
        $deadline=$procurementService->computeDeadline($procurement->created_at);
        $procurement->update(['code'=>$procurement_code,'deadline'=>$deadline]);
        dispatch(new ProcurementConfirmInform($procurement));  //推送发送订单通知消息模板  队列
        $procurement = $procurement->loadMissing(['initiator','ownerMaterial.material','ownerMaterial.owner.customer','ownerMaterial.file','supplier']);
        if ($procurement) return ['success' => true,'data' => $procurement];
        else return ['success' => false, 'message' => '添加失败'];

    }
    //取消采购单
    public function cancel($id): array
    {
        $this->gate('采购管理-采购-编辑');
        $procurement=Procurement::query()->find($id);
        $procurement->update(['status'=>10]);
        $procurement = $procurement->loadMissing(['initiator','ownerMaterial.material','ownerMaterial.owner.customer']);
        if ($procurement) return ['success' => true,'data' => $procurement];
        else return ['success' => false, 'message' => '取消失败'];

    }
    //询价单提交采购申请
    public function submitProcurement(ProcurementAmountRequest $request): array
    {
        $this->gate('采购管理-采购-编辑');
        $request->validated();
        $param=$request->all();
        /**@var ConfigurationService $configurationService */
        $configurationService=app(ConfigurationService::class);
        $receive_time=$configurationService->getReceiveTime();
        $priceCoefficient=$configurationService->getPriceCoefficient();
        /** @var Procurement $procurement */
        $procurement=Procurement::query()->find($param['id']);
        $unit_price=$param['unit_price'];
        if (!$unit_price) $unit_price=$priceCoefficient*$param['offer'];
        $procurement->update([
            'type'=>0,
            'status'=>2,
            'quantity'=>$param['quantity'],
            'amount'=>$param['amount'],
            'unit_price'=>$unit_price,
            'cost_price'=>$param['offer'],
            'supplier_id'=>$param['supplier_id'],
            'deadline'=>Carbon::parse(Carbon::now()->toDateTimeString())->subHours(-$receive_time)->toDateTimeString(),
        ]);
        dispatch(new ProcurementReceive($procurement))->delay(now()->addHours($receive_time)); //可从系统配置获取
        dispatch(new ProcurementWaitConfirmInform($procurement));
        $procurement = $procurement->loadMissing(['initiator','ownerMaterial.material','ownerMaterial.owner.customer','ownerMaterial.file','supplier']);
        if ($procurement) return ['success' => true,'data' => $procurement];
        else return ['success' => false, 'message' => '发起采购失败'];
    }
    public function initiateProcurement(Request $request): array
    {
        $this->gate('采购管理-采购-编辑');
        $id=$request->input('id');
        /** @var ProcurementService $procurementService*/
        $procurementService=app(ProcurementService::class);
        $procurementQuotation=$procurementService->screenLowestQuotation($id);
        if ($procurementQuotation) return ['success' => true,'data' => $procurementQuotation];
        else return ['success' => false, 'message' => '暂无供应商报价!'];

    }
    public function costPrice(Request $request): array
    {
        $this->gate('采购管理-财务-采购账单');
        $id=$request->input('id');
        $cost_price=$request->input('cost_price');
        $procurement=Procurement::query()->find($id);
        if ($procurement->cost_price!=$cost_price)$procurement->update(['cost_price'=>$cost_price]);
        $procurement = $procurement->loadMissing(['initiator','supplier','ownerMaterial.material','ownerMaterial.owner.customer','ownerMaterial.file','supplier']);
        if ($procurement) return ['success' => true,'data' => $procurement];
        else return ['success' => false, 'message' => '修改采购单价失败!'];

    }
    public function createAnew(Request $request): array
    {
        $this->gate('采购管理-采购-新建');
        $ids=$request->input('checkData');
        if (empty($ids)) return ['success' => false, 'message' => '当前未勾选指定订单!'];
        $collect=collect();
        $procurements=Procurement::query()->whereIn('id',$ids)->get();
        foreach ($procurements as $procurement){
            if ($procurement->type==2){
                $pro=$this->newProcurement($procurement,Auth::user()['id'],$procurement->type,2);
            }else{
                $pro=$this->newProcurement($procurement,Auth::user()['id'],$procurement->type);
            }
            $pro->loadMissing(['initiator','ownerMaterial.material','ownerMaterial.owner.customer','ownerMaterial.file','supplier']);
            $collect->add($pro);
        }
        if (!empty($collect)) return ['success' => true,'data' => $collect];
    }

    public function checkBill(Request $request,ProcurementCheckSheetFilters $filters)
    {
        if(!Gate::allows('采购管理-财务-对账单')){ return redirect(url('/'));  }
        $paginateParams=$request->input();
        /**@var SupplierService $supplierService*/
        $supplierService=app(SupplierService::class);
        $supplier_ids=$supplierService->screenSupplierIds();
        $procurementCheckSheets=ProcurementCheckSheet::query()
            ->orderByDesc('id')
            ->filter($filters)
            ->with(['procurementDelivery.procurement.supplier','procurementDelivery.procurement.ownerMaterial.material','procurementDelivery.receiver'])
            ->whereHas('procurementDelivery',function($builder)use($supplier_ids){
                $builder->whereHas('procurement',function ($build)use($supplier_ids){
                    $build->whereHas('supplier',function ($build)use($supplier_ids){
                        $build->whereIn('id',$supplier_ids);
                    });
                });
            })
            ->paginate($param['paginate'] ?? 50);
        $suppliers=Supplier::query()->select('id','name')->get();
        $materials=Material::query()->select('id','name')->get();
        return view('procurement/finance/checkBill',compact('procurementCheckSheets','suppliers','paginateParams','materials'));
    }
    public function fillInvoice(Request $request): array
    {
        $this->gate('采购管理-财务-对账单');
        $id=$request->input('procurementCheckSheetId');
        $invoice_number=$request->input('invoice_number');
        $procurementCheckSheet=ProcurementCheckSheet::query()->find($id);
        $procurementTotalBill=null;
        $procurementCheckSheet->update([
                'invoice_number'=>$invoice_number,
                'status'=>3,//3 已完结
            ]);
        $supplier_id = $procurementCheckSheet->procurementDelivery->procurement->supplier_id ?? null;
        $ProcurementQuery = Procurement::query()->select("id")
            ->where('supplier_id',$supplier_id);
        $procurementDeliveryQuery= ProcurementDeliverie::query()->select('id')
            ->whereIn("procurement_id",$ProcurementQuery)
            ->where("created_at","like",Carbon::parse($procurementCheckSheet['procurementDelivery']['created_at'])->format('Y-m')."%");
        $count=ProcurementCheckSheet::query()
            ->with(['procurementDelivery.procurement.ownerMaterial.material','procurementDelivery.procurement.supplier'])
            ->whereIn('procurement_delivery_id',$procurementDeliveryQuery)->where('status','!=',3)->count();
        if($count==0){
            $procurementTotalBill=ProcurementTotalBill::query()
                ->where('counting_month','like',Carbon::parse($procurementCheckSheet['procurementDelivery']['created_at'])->format('Y-m')."%")
                ->where('supplier_id',$supplier_id)
                ->update(['status'=>2]);
        }
        if ($procurementTotalBill) {
            return ['success' => true,'data' => $invoice_number,'status'=>3,'totalStatus'=>2];
        }
        elseif ($procurementCheckSheet){
            return ['success' => true,'data' => $invoice_number,'status'=>3];
        }else return ['success' => false, 'message' => '添加失败'];

    }

    public function procurementBill(Request $request,ProcurementFilters $filters)
    {
        if(!Gate::allows('采购管理-财务-采购账单')){ return redirect(url('/'));  }
        $paginateParams=$request->input();
        $owner_ids=app('UserService')->getPermittingOwnerIds(auth()->user());
        $owners=app("OwnerService")->getIntersectPermitting();
        $materials=Material::query()->select('id','name')->get();
        $suppliers=Supplier::query()->select('id','name')->get();
        $procurements = Procurement::query()
            ->orderByDesc('id')
            ->filter($filters)
            ->with(['initiator','supplier','ownerMaterial.material','ownerMaterial.owner'=>function($query)use($owner_ids){
                /** @var Builder $query */
                $query->with('customer')->whereIn('id',$owner_ids);
            },'procurementDeliveries'])
            ->whereHas('ownerMaterial',function($builder)use($owner_ids){
                $builder->whereHas('owner',function ($build)use($owner_ids){
                   $build->whereIn('id',$owner_ids);
                });
            })
            ->where('type',0) //只取采购单
            ->paginate($param['paginate'] ?? 50);
        foreach ($procurements as $procurement){
            if (empty($procurement->procurementDeliveries))continue;
            $procurement->receive_amount=$procurement->procurementDeliveries->sum('amount');
            $procurement->signed_at=$procurement->procurementDeliveries->first()['signed_at'];
        }
        return view('procurement/finance/procurementBill',compact('suppliers','materials','owners','paginateParams','procurements'));
    }

    public function monthlyBillReport(Request $request)
    {
        if(!Gate::allows('采购管理-财务-月账单报表')){ return redirect(url('/'));  }
        $paginateParams=$request->input();
        /** @var ProcurementTotalBillService $procurementTotalBillService*/
        $procurementTotalBillService=app(ProcurementTotalBillService::class);
        $procurementTotalBills=$procurementTotalBillService->paginate($paginateParams);
        $suppliers=Supplier::query()->select('id','name')->get();
        return view('procurement/finance/monthlyBillReport',compact('suppliers','procurementTotalBills','paginateParams'));
    }
    public function getCheckBillMonth(Request $request)
    {
        if(!Gate::allows('采购管理-财务-月账单报表')){ return ["success"=>false,"data"=>"您无此权限操作!"];  }
        $procurementTotalBill=ProcurementTotalBill::query()->find($request->input('procurement_total_bill_id'));
        /** @var  ProcurementTotalBill $procurementTotalBill */
        $procurementTotalBill->setCurrentMothProcurements();
        return ["success"=>true,"data"=>$procurementTotalBill->procurementCheckSheets??[]];
    }
    //采购导出
    public function procurementExport(Request $request,ProcurementFilters $filters){
        $this->gate('采购管理-采购-查询');
        $owner_ids=app('UserService')->getPermittingOwnerIds(auth()->user());
        $procurements = Procurement::query()
            ->filter($filters)
            ->withCount('procurementQuotations')
            ->with(['initiator','ownerMaterial.material','ownerMaterial.owner'=>function($query)use($owner_ids){
                $query->with('customer')->whereIn('id',$owner_ids);
            },'procurementDeliveries'])
            ->whereHas('ownerMaterial',function($builder)use($owner_ids){
                $builder->whereHas('owner',function ($build)use($owner_ids){
                    $build->whereIn('id',$owner_ids);
                });
            })
            ->get();
        foreach ($procurements as $procurement){
            if ($procurement->procurement_quotations_count>0 && $procurement->status==0) $procurement->status=1;
            if (empty($procurement->procurementDeliveries))continue;
            $procurement->deliver_amount=$procurement->procurementDeliveries->sum('amount');
        }
        $procurementStatus=Procurement::status;
        $procurementType=Procurement::type;
        $row = ['采购编号','项目','单据类型','采购公司','耗材编号','耗材','尺寸大小','特殊要求','材质规格','采购数量','销售单价(元)','送货数量','销售总价(元)','采购单状态','联系方式'];
        $list = [];
        foreach ($procurements as $procurement){
            $list[] = [
                $procurement->code,
                $procurement->ownerMaterial->owner ? $procurement->ownerMaterial->owner->name :'',
                is_null($procurement->type) ? '' :$procurementType[$procurement->type],
                $procurement->ownerMaterial->owner->customer ? $procurement->ownerMaterial->owner->customer->company_name :'',
                $procurement->ownerMaterial ? $procurement->ownerMaterial->material_code :'',
                $procurement->ownerMaterial->material ? $procurement->ownerMaterial->material->name :'',
                $procurement->ownerMaterial ? $procurement->ownerMaterial->size :'',
                $procurement->ownerMaterial ? $procurement->ownerMaterial->special :'',
                $procurement->ownerMaterial ? $procurement->ownerMaterial->specification :'',
                $procurement->quantity,
                $procurement->unit_price,
                $procurement->deliver_amount ?  $procurement->deliver_amount :'',//送货数量
                $procurement->unit_price*$procurement->amount,//销售总价=销售数量*销售单价
                is_null($procurement->status) ? '' :$procurementStatus[$procurement->status],
                $procurement->ownerMaterial->owner->customer ? $procurement->ownerMaterial->owner->customer->phone :'',
            ];
        }
        return app(ExportService::class)->json($row,$list,"采购管理-采购报表记录");
    }
    //对账单报表导出
    public function checkBillExport(Request $request,ProcurementCheckSheetFilters $filters){
        $this->gate('采购管理-财务-对账单');
        /**@var SupplierService $supplierService*/
        $supplierService=app(SupplierService::class);
        $supplier_ids=$supplierService->screenSupplierIds();
        $procurementCheckSheets=ProcurementCheckSheet::query()
            ->filter($filters)
            ->with(['procurementDelivery.procurement.supplier','procurementDelivery.procurement.ownerMaterial.material','procurementDelivery.receiver'])
            ->whereHas('procurementDelivery',function($builder)use($supplier_ids){
                $builder->whereHas('procurement',function ($build)use($supplier_ids){
                    $build->whereHas('supplier',function ($build)use($supplier_ids){
                        $build->whereIn('id',$supplier_ids);
                    });
                });
            })
            ->get();
        $procurementCheckSheetStatus=ProcurementCheckSheet::status;
        $row = ['采购编号','采购日期','送货日期','供应商名称','耗材编号','耗材','采购数量','送货数量','签收人','签收日期','应付金额','发票号','状态'];
        $list = [];
        foreach ($procurementCheckSheets as $procurementCheckSheet){
            $list[] = [
                $procurementCheckSheet->procurementDelivery->procurement ? $procurementCheckSheet->procurementDelivery->procurement->code : '',
                $procurementCheckSheet->procurementDelivery->procurement ? $procurementCheckSheet->procurementDelivery->procurement->created_at :'',
                $procurementCheckSheet->procurementDelivery ? $procurementCheckSheet->procurementDelivery->created_at :'',
                $procurementCheckSheet->procurementDelivery->procurement->supplier ? $procurementCheckSheet->procurementDelivery->procurement->supplier->name :'',
                $procurementCheckSheet->procurementDelivery->procurement->ownerMaterial ? $procurementCheckSheet->procurementDelivery->procurement->ownerMaterial->material_code :'',
                $procurementCheckSheet->procurementDelivery->procurement->ownerMaterial->material ? $procurementCheckSheet->procurementDelivery->procurement->ownerMaterial->material->name :'',
                $procurementCheckSheet->procurementDelivery->procurement ? $procurementCheckSheet->procurementDelivery->procurement->quantity :'',
                $procurementCheckSheet->procurementDelivery ? $procurementCheckSheet->procurementDelivery->amount :'',
                $procurementCheckSheet->procurementDelivery->receiver ? $procurementCheckSheet->procurementDelivery->receiver->name :'',
                $procurementCheckSheet->procurementDelivery ? $procurementCheckSheet->procurementDelivery->signed_at :'',
                $procurementCheckSheet->account_payable,
                $procurementCheckSheet->invoice_number,
                is_null($procurementCheckSheet->status) ? '' :$procurementCheckSheetStatus[$procurementCheckSheet->status],
            ];
        }
        return app(ExportService::class)->json($row,$list,"采购管理-对账单报表记录");
    }
    //采购账单导出
    public function procurementBillExport(Request $request,ProcurementFilters $filters){
        $this->gate('采购管理-财务-采购账单');
        $owner_ids=app('UserService')->getPermittingOwnerIds(auth()->user());
        $procurements = Procurement::query()
            ->filter($filters)
            ->with(['supplier','initiator','ownerMaterial.material','ownerMaterial.owner'=>function($query)use($owner_ids){
                /** @var Builder $query */
                $query->with('customer')->whereIn('id',$owner_ids);
            },'procurementDeliveries'])
            ->whereHas('ownerMaterial',function($builder)use($owner_ids){
                $builder->whereHas('owner',function ($build)use($owner_ids){
                    $build->whereIn('id',$owner_ids);
                });
            })
            ->where('type',0) //只取采购单
            ->get();
        foreach ($procurements as $procurement){
            if (empty($procurement->procurementDeliveries))continue;
            $procurement->receive_amount=$procurement->procurementDeliveries->sum('receipt_amount');
            $procurement->signed_at=$procurement->procurementDeliveries->first()['signed_at'];
        }

        $procurementStatus=Procurement::status;
        $row = ['采购编号','采购日期','接单日期','签收日期','项目名称','采购公司','供应商','耗材编号','耗材','尺寸大小','特殊要求',
            '材质规格','采购数量','销售数量','收货数量','采购单价(元)','销售单价(元)','应收金额(元)','应付金额(元)','状态'];
        $list = [];
        foreach ($procurements as $procurement){
            $list[] = [
                $procurement->code,
                $procurement->created_at,
                $procurement->deadline ? $procurement->deadline : '',//接单日期
                $procurement->signed_at ? $procurement->signed_at : '',//签收日期
                $procurement->ownerMaterial->owner ? $procurement->ownerMaterial->owner->name :'',
                $procurement->ownerMaterial->owner->customer ? $procurement->ownerMaterial->owner->customer->company_name :'',
                $procurement->supplier ? $procurement->supplier->name :'',
                $procurement->ownerMaterial ? $procurement->ownerMaterial->material_code :'',
                $procurement->ownerMaterial->material ? $procurement->ownerMaterial->material->name :'',
                $procurement->ownerMaterial ? $procurement->ownerMaterial->size :'',
                $procurement->ownerMaterial ? $procurement->ownerMaterial->special :'',
                $procurement->ownerMaterial ? $procurement->ownerMaterial->specification :'',
                $procurement->quantity,
                $procurement->amount,
                $procurement->receive_amount ? $procurement->receive_amount : '',//收货数量
                $procurement->cost_price,
                $procurement->unit_price,
                $procurement->amount*$procurement->cost_price,//应收金额
                $procurement->quantity*$procurement->unit_price,//应付金额
                is_null($procurement->status) ? '' :$procurementStatus[$procurement->status],
            ];
        }
        return app(ExportService::class)->json($row,$list,"采购账单报表记录");
    }
    //月账单报表导出
    public function procurementTotalBillExport(Request $request){
        $this->gate('采购管理-财务-月账单报表');
        /** @var ProcurementTotalBillService $procurementTotalBillService*/
        $procurementTotalBillService=app(ProcurementTotalBillService::class);
        if ($request->input('checkAllSign')){
            $params = $request->input();
            unset($params["checkAllSign"]);
            $procurementTotalBills=$procurementTotalBillService->get($params);
        }else{
            $procurementTotalBills=$procurementTotalBillService->get(["id"=>$request->data]);
        }
        $procurementTotalBillStatus=ProcurementTotalBill::status;
        $row = ['对账编号','账单日期','提交日期','供应商','总金额','状态'];
        $list = [];
        foreach ($procurementTotalBills as $procurementTotalBill){
            $list[] = [
                $procurementTotalBill->id,
                $procurementTotalBill->counting_month,
                $procurementTotalBill->created_at,
                $procurementTotalBill->supplier ? $procurementTotalBill->supplier :'',
                $procurementTotalBill->total_payable,
                $procurementTotalBill->status ? $procurementTotalBillStatus[$procurementTotalBill->status] :'',
            ];
        }
        return app(ExportService::class)->json($row,$list,"采购管理-月账单报表记录");
    }
}
