<?php

namespace App\Services;

use App\OracleBasCustomer;
use App\Owner;
use App\Services\common\BatchUpdateService;
use App\Shop;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use App\Traits\ServiceAppAop;


class ShopService
{
    use ServiceAppAop;
    protected $modelClass=Shop::class;
    /** @var CacheService $cacheService */
    private $cacheService;
    function __construct(){
        $this->instant($this->cacheService,'CacheService');
    }

    public function getSelection(array $column = ['id', 'name'])
    {
        return Shop::query()->select($column)->get();
    }

    function firstOrCreate(array $param, array $values = null){
        $shop = Shop::query();
        if ($values) return $shop->firstOrCreate($param,$values);
        return $shop->firstOrCreate($param);
    }

    public function batchUpdate(array $params)
    {
        return app(BatchUpdateService::class)->batchUpdate('shops',$params);
    }

    public function getByWmsOrders($orderHeaders)
    {
        $maps = []; //issuepartyname
        foreach ($orderHeaders as $orderHeader) {
            $value = ['owner_code'=>$orderHeader->customerid,'issuepartyname'=>$orderHeader->issuepartyname];
            if(!in_array($value,$maps))
                $maps[] = $value;
        }
        $issuepartynames = array_diff(array_unique(data_get($maps,'*.issuepartyname')),['','*',null]);
        $owner_codes = array_diff(array_unique(data_get($maps,'*.owner_code')),['','*',null]);
        $shops = Shop::query()->with('owner')
            ->whereHas('owner',function($query)use($owner_codes){
                $query->whereIn('code',$owner_codes);
            })->whereIn('name',$issuepartynames)->get();
        if($shops->count() < count($issuepartynames)){
            $shops_code = data_get($shops,'*.name');
            $names = array_diff($issuepartynames,$shops_code);
            $params = [];
            foreach ($maps as $item){
               if(in_array($item['issuepartyname'],$names))
                   $params[] = $item;
            }
            $shops_list = $this->createByNameAndOwnerCode($params);
            $shops = $shops->concat($shops_list??[]);
        }
        return $shops;
    }

    public function createByNameAndOwnerCode(array $params){
        $owners = Owner::query()->whereIn('code',data_get($params,'*.owner_code'))->get();
        $owners_map = [];
        foreach ($owners as $owner) {
            $owners_map[$owner->code] = $owner;
        }
        $insert_params = [];
        $created_at = Carbon::now()->format('Y-m-d H:i:s');
        foreach ($params as $param) {
            $owner = $owners_map[$param['owner_code']] ?? '';
            $insert_params[] = [
                'name' => $param['issuepartyname'] ?? '',
                'owner_id' => $owner['id'] ?? '',
                'created_at' => $created_at,
            ];
        }
        try {
            if (count($insert_params) > 0) {
                $this->insert($insert_params);
                app('LogService')->log(__METHOD__, __FUNCTION__, '批量创建 shop ' . count($insert_params) . json_encode($insert_params));
            }
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__, 'Error '.__FUNCTION__, '批量创建 shop Error' . json_encode($insert_params) .'||'.$e->getMessage().'||'.$e->getTraceAsString());
        } finally {
            return Shop::query()->whereIn('name',data_get($params,'*.issuepartyname'))->get();
        }
    }

    public function getShopByCodeMap($map)
    {
        /** @var OwnerService $ownerService */
        $ownerService = app('OwnerService');
        $owner_codes = [];
        foreach ($map as $item) {
            $owner_codes[$item['owner_code']]= $item['owner_code'];
        }
        $owners = $ownerService->getOwnerByCodes($owner_codes);
        $owner_map  = [];
        $owners->each(function($owner)use(&$owner_map){
            $owner_map[$owner['code']] = $owner;
        });
        $collect = collect();
        if(count($map)==0)return $collect;
        foreach ($map as $item) {
            $collect->push(Cache::remember("getShopByCodeMap_{$item['owner_code']}_{$item['issuepartyname']}", config('cache.expirations.rarelyChange'), function()use($item,$owner_map){
                $owner = $owner_map[$item['owner_code']] ;
                $shop = Shop::query()->where('owner_id',$owner['id'])->where('name',$item['issuepartyname'])->first();
                if($shop)return $shop;
                return Shop::query()->create(['owner_id'=>$owner['id'],'name'=>$item['issuepartyname']]);
            }));
        }
        return $collect;
    }

}
