<?php

namespace App\Imports;

use App\Commodity;
use App\Http\Controllers\api\jianshang\RejectedController;
use App\Http\Controllers\Controller;
use App\Logistic;
use App\Owner;
use App\Rejected;
use App\RejectedBill;
use App\RejectedBillItem;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class RejectedImport implements ToCollection, WithHeadingRow
{
//    protected $isOverride=false;
//    public function __construct($isOverride)
//    {
//        if($isOverride=='1')
//            $this->isOverride=true;
//    }

    /**
     * @param Collection $collections
     */
    public function collection(Collection $collections)
    {
        foreach ($collections as $row)
        {
            $logistic_number_return = trim($row['logistic_number_return']);
            $mobile_sender = trim($row['mobile_sender']);
            $logistic_name = trim($row['logistic_name']);
            $barcode = trim($row['barcode']);
            $amount = trim($row['amount']);
            $quality_label_name = trim($row['quality_label_name']);
            $remark = trim($row['remark']);
            $id_owner=Session::get('jianshangIdOwner');


            $lastReturnNumber = Session::get('jianshangLastImportedBill');
            if(!$logistic_number_return)$logistic_number_return=$lastReturnNumber;
            $lastMobile = Session::get('jianshangLastImportedMobile');
            if(!$mobile_sender)$mobile_sender=$lastMobile;
            $lastlogistic_name = Session::get('jianshangLastImportedLogisticName');
            if(!$logistic_name)$logistic_name=$lastlogistic_name;


            if(!$id_owner){
                $id_owner=Owner::where('name','like','%笕尚%')->first()['id'];
                Session::put('jianshangIdOwner',$id_owner);
            }
            $id_logistic_return=Logistic::where('name','like',"%{$logistic_name}%")->first()['id'];
            if(!$id_logistic_return){
                $id_logistic_return=Logistic::where('name','like',"%其它%")->first()['id'];
            }
            $id_quality_label=1;
            if(trim($quality_label_name)!='良品'){
                $id_quality_label=2;
            }
            if(!$amount)$amount=1;


            $bill=RejectedBill::where('logistic_number_return',trim($logistic_number_return))->first();
            if($bill){
                $item=RejectedBillItem::where('id_rejected_bill',$bill['id'])
                    ->where('barcode_goods',trim($barcode))->where('id_quality_label',$id_quality_label)->first();
                if($item){
                    $item['amount']+=$amount;
                    $item->update();
                }else{
                    $item=new RejectedBillItem([
                        'id_rejected_bill'=>$bill['id'],
                        'barcode_goods'=>trim($barcode),
                        'amount'=>trim($amount),
                        'id_quality_label'=>$id_quality_label,
                        'remark'=>$remark,
                    ]);
                    $item->save();
                }
            }else{
                $bill=new RejectedBill([
                    'id_owner'=>$id_owner,
                    'mobile_sender'=>$mobile_sender,
                    'logistic_number_return'=>$logistic_number_return,
                    'id_logistic_return'=>$id_logistic_return,
                    'is_loaded'=>0,
                ]);
                $bill->save();
                $item=RejectedBillItem::where('id_rejected_bill',$bill['id'])
                    ->where('barcode_goods',trim($barcode))->where('id_quality_label',$id_quality_label)->first();
                if($item){
                    $item['amount']+=$amount;
                    $item->update();
                }else{
                    $item=new RejectedBillItem([
                        'id_rejected_bill'=>$bill['id'],
                        'barcode_goods'=>trim($barcode),
                        'amount'=>trim($amount),
                        'id_quality_label'=>$id_quality_label,
                        'remark'=>$remark,
                    ]);
                    $item->save();
                }
            }

            $lastBill = Session::get('jianshangLastImportedBill');
            if($lastBill&&$lastBill !=trim($logistic_number_return)){
                $this->submitToApi($bill);
            }
            Session::put('jianshangLastImportedLogisticName',trim($logistic_name));
            Session::put('jianshangLastImportedBill',trim($logistic_number_return));
            Session::put('jianshangLastImportedMobile',trim($mobile_sender));
        }
    }
    private function submitToApi(RejectedBill $bill){
        if(!$bill||$bill->items()->get()->isEmpty())return;
        $havingFail=0;
        if(!config('api.API_FAKING'))
            $bill->items()->get()->each(function(RejectedBillItem $item)use(&$havingFail){
                $rejectedBill=RejectedBill::find($item['id_rejected_bill']);
                if($rejectedBill['is_loaded']!=0){
                    return false;
                }
                $owner = Owner::find($rejectedBill['id_owner']);
                if(strstr($owner->name??'','笕尚')){
                    $rejected=new Rejected();
                    $this->log(__METHOD__,'找不到表','132行');
                    $rejected->fill($rejectedBill->toArray());
                    $rejected->fill($item->toArray());
                    $rejectedJianshang=new RejectedController();
                    $sended=$rejectedJianshang->sendRejected($rejected);
                    if(!$sended){
                        (new Controller())->log(__METHOD__,'error','数据发送给笕尚失败');
                        $havingFail++;
                        return false;
                    }
                }
            });

        (new Controller())->log(__METHOD__,'error',json_encode(['success'=>'false','failure_info'=>"$havingFail/{$bill->items->count()} 条记录没有发送成功"]));
    }
}
