<?php

namespace App\Imports;

use App\Commodity;
use App\OracleBasSKU;
use App\OracleInvLotAtt;
use App\Owner;
use App\Services\InventoryCompareService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

HeadingRowFormatter::default('none');

class InventoryCompareImport implements ToCollection, WithHeadingRow, WithMultipleSheets
{
    protected $owner_id=null;
    protected $ownerCode=null;
    protected $customLocationArrs=[];
    protected $ownerArr=[];
    public function __construct()
    {
            app()->singleton('InventoryCompareService',InventoryCompareService::class);
    }

    public function Collection(Collection $collection)
    {
        $array = $collection->toArray();
        $skuName=(function()use($array){
            if($array[0]['物料编号']??false) return '物料编号';
            if($array[0]['SKU']??false) return 'SKU';
            if($array[0]['产品编码']??false) return '产品编码';
        })();
        $amountName=(function()use($array){
            if($array[0]['物料库存量']??false) return '物料库存量';
            if($array[0]['库存量']??false) return '库存量';
            if($array[0]['数量']??false) return '数量';
        })();
        $customLocationName=(function()use($array){
            if($array[0]['仓库']??false) return '仓库';
            if($array[0]['属性仓']??false) return '属性仓';
        })();
        $sku=$array[0][$skuName] ?? null;
        $amount=$array[0][$amountName] ?? null;
        $customLocation=$array[0][$customLocationName] ?? null;

        $endIS = false;
        if (!isset($sku) || !isset($amount) || !isset($customLocation)) {
            Cache::put('error', '请检查您第一行标题是否存在产品编号，数量，属性仓');
        } else {
            $endIS = true;
        }
        foreach ($collection as $row) {
            $customLocationArr=[
                'custom_location'=>$row[$customLocationName] ?? null,
            ];
            array_push($this->customLocationArrs,$customLocationArr);
        }
        $this->customLocationArrs=array_column($this->customLocationArrs,'custom_location');
        $this->customLocationArrs=array_unique($this->customLocationArrs);
        foreach ($this->customLocationArrs as $customLocation){
            $ownerCode=OracleInvLotAtt::query()->where('lotatt05',$customLocation)->value('customerid');
            if ($ownerCode){
                $owner_id=Owner::query()->where('code',$ownerCode)->value('id');
            }else{
                $owner_id=null;
            }
            $owners=[
                'owner_id'=>$owner_id,
                'owner_code'=>$ownerCode,
                'custom_location'=>$customLocation,
            ];
            $this->ownerArr = array_merge($this->ownerArr,[$owners['custom_location']=>$owners]);
        }
        $skuAndWarehouseArr=[];
        $inventoryCompares=[];
        $exception = [];
        $sum = 2;
        if ($endIS) {
            foreach ($collection as $row) {
                if (!$row[$skuName]) {
                    array_push($exception, ['第' . $sum . '行产品编号为空!']);
                    $sum++;
                    continue;
                } else if (!$row[$amountName]) {
                    array_push($exception, ['第' . $sum . '行数量为空!']);
                    $sum++;
                    continue;
                } else if (!$row[$customLocationName]) {
                    array_push($exception, ['第' . $sum . '行属性仓为空!']);
                    $sum++;
                    continue;
                }
                if ($this->ownerArr["$row[$customLocationName]"]['owner_id']){
                    $this->owner_id=$this->ownerArr["$row[$customLocationName]"]['owner_id'];
                    $this->ownerCode=$this->ownerArr["$row[$customLocationName]"]['owner_code'];
                }

                if (!$this->ownerArr["$row[$customLocationName]"]['owner_id']){
                $ownerCode=OracleInvLotAtt::query()->where('lotatt05',$row[$customLocationName])->value('customerid');
                if (!$ownerCode){
                    array_push($exception, ['第' . $sum . '行货主不存在!']);
                    $sum++;
                    continue;
                }
                if (!$this->ownerCode) {
                    $this->ownerCode=$ownerCode;
                    $this->owner_id=Owner::query()->where('code',$this->ownerCode)->value('id');
                }elseif ($this->ownerCode!=$ownerCode){
                    $this->owner_id=Owner::query()->where('code',$ownerCode)->value('id');
                    }
                }

                $skuAndWarehouse=$row[$skuName].$row[$customLocationName];
                array_push($skuAndWarehouseArr,$skuAndWarehouse);
                $uniqueArr=array_unique($skuAndWarehouseArr);
                if (count($uniqueArr)!=count($skuAndWarehouseArr)){
                    array_push($exception, ['第' . $sum . '行产品编号+属性仓不能同时重复!']);
                    $sum++;
                    continue;
                }
                $commodityInWMS=Commodity::where('owner_id',$this->owner_id)->where('sku',$row[$skuName])->first();
                $owner=Owner::find($this->owner_id);
                if(!$commodityInWMS) {
                    $commodityInWMS = OracleBasSKU::query()->where('sku', "$row[$skuName]")->where('customerid', "$owner->code")->first();
                    $commodity=Commodity::query()->firstOrCreate([
                        'owner_id'=>$this->owner_id,
                        'sku'=>$row[$skuName],
                        'name'=>$commodityInWMS['descr_c'],
                        'length'=>$commodityInWMS['skulength'],
                        'width'=>$commodityInWMS['skuwidth'],
                        'height'=>$commodityInWMS['skuhigh'],
                        'volumn'=>$commodityInWMS['skulength']*$commodityInWMS['skuwidth']*$commodityInWMS['skuhigh']]);
                    $barcode = $commodityInWMS['alternate_sku1']??$commodityInWMS['alternate_sku2']??$commodityInWMS['alternate_sku3'];
                    if($barcode)
                        $commodity->newBarcode($barcode);
                }
                if (!$commodityInWMS){
                    array_push($exception, ['该货主下不存在产品编号:'.$row[$skuName]]);
                    $sum++;
                    continue;
                }
                $inventoryCompare=[
                    'owner_name'=>$owner['name'],
                    'owner_code'=>$owner['code'],
                    'owner_id'=>$this->owner_id,
                    'sku'=>"$row[$skuName]",
                    'custom_location'=>$row[$customLocationName],
                    'amount'=>$row[$amountName],
                ];
                array_push($inventoryCompares,$inventoryCompare);
                $sum++;
            }
                /** @var InventoryCompareService $service */
                $service = app('InventoryCompareService');
                $inventoryCompare= $service->createInventoryCompares($inventoryCompares);
                if (!$inventoryCompare) array_push($exception, ['创建库存对比失败！']);
        }
        Cache::put('exception', $exception, 86400);
    }

    /**
     * 该方法是实现上传文件只选中 第一个表
     * ExcelImprot 默认是有多少个分表就执行多少次的分表
     * @return OrderIssueImport[]|array
     */
    public function sheets(): array
    {
        return [0 => new InventoryCompareImport()];
    }


}
