<?php

namespace App\Services;

use App\Services\common\BatchUpdateService;
use App\Services\common\DataHandlerService;
use App\Services\common\QueryService;
use App\Store;
use App\ValueStore;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;


Class StoreService
{
    private function conditionQuery(array $params)
    {
        $stores = Store::query()->with(['storeItems.store', 'warehouse', 'owner'])->where('is_fast_stored', '无')->orderBy('id', 'DESC');
        $columnQueryRules = [
            'asn_code' => ['like' => ''],
            'created_at_start' => ['alias' => 'created_at', 'startDate' => ' 00:00:00'],
            'created_at_end' => ['alias' => 'created_at', 'endDate' => ' 23:59:59'],
            'owner_id' => ['multi' => ','],
            'warehouse_id' => ['multi' => ','],
            'status' => ['multi' => ','],
            'stored_method' => ['multi' => ','],
            'id' => ['multi' => ',']
        ];
        $stores = app(QueryService::class)->query($params, $stores, $columnQueryRules, 'stores');
        return $stores;
    }

    public function paginate(array $params)
    {
        return $this->conditionQuery($params)->paginate($params['paginate'] ?? 50);
    }

    public function create(array $params)
    {
        return Store::query()->create($params);
    }

    public function storeCreateByWms()
    {
        $created_at = config('sync.asn_sync.created_at');
        $create_set = config('sync.asn_sync.cache_prefix.create_set');
        $create_keys = config('sync.asn_sync.cache_prefix.create_keys');
        $create_key = config('sync.asn_sync.cache_prefix.create');

        /** @var OracleDocAsnHerderService $oracleDocAsnHerderService */
        $oracleDocAsnHerderService = app(OracleDocAsnHerderService::class);
        $last_time = $this->getAsnLastSyncAt($created_at, 'create');
        $asnHerders = $oracleDocAsnHerderService->getWmsAsnOnStartDateCreate($last_time);
        $last_time = $asnHerders->first()['addtime'];
        $last_records = $asnHerders->where('addtime', $last_time);
        if (!$asnHerders) return;
        $this->createStore($asnHerders);
        $this->deleteCacheKey($create_set, $create_keys);
        $this->setLastRecordsByRedis($create_key, $create_set, $create_keys, $last_records);
        $this->setAsnLastSyncAt($created_at, $last_time);
    }

    public function storeUpdateByWms()
    {
        $updated_at = config('sync.asn_sync.updated_at');
        $update_set = config('sync.asn_sync.cache_prefix.update_set');
        $update_keys = config('sync.asn_sync.cache_prefix.update_keys');
        $update_key = config('sync.asn_sync.cache_prefix.update');

        /** @var OracleDocAsnHerderService $oracleDocAsnHerderService */
        $oracleDocAsnHerderService = app(OracleDocAsnHerderService::class);
        $last_time = $this->getAsnLastSyncAt($updated_at, 'update');
        $asnHerders = $oracleDocAsnHerderService->getWmsAsnOnStartDateEdit($last_time);
        $last_time = $asnHerders->first()['edittime'];
        $last_records = $asnHerders->where('edittime', $last_time);
        if (!$asnHerders) return;
        $this->createStore($asnHerders);
        $this->updateStore($asnHerders);
        $this->deleteCacheKey($update_set, $update_keys);
        $this->setLastRecordsByRedis($update_key, $update_set, $update_keys, $last_records);
        $this->setAsnLastSyncAt($updated_at, $last_time);
    }

    public function createStore($asnHerders)
    {
        if (!$asnHerders) return null;
        /**
         * @var OwnerService $ownerService
         * @var WarehouseService $wareHouseService
         */
        $ownerService = app(OwnerService::class);
        $wareHouseService = app(WarehouseService::class);
        $owner_codes = [];
        $warehouse_codes = [];
        foreach ($asnHerders as $asnHerder) {
            if (!empty($asnHerder['customerid']))
                $owner_codes[$asnHerder['customerid']] = $asnHerder['customerid'];
            if (!empty($asnHerder['warehouseid']))
                $warehouse_codes[$asnHerder['warehouseid']] = $asnHerder['warehouseid'];
        }
        $owners = $ownerService->getOwnerByCodes($owner_codes);
        $warehouses = $wareHouseService->getWareHouseByCodes($warehouse_codes);
        foreach ($owners as $owner) {
            $owners_code_map[$owner->code] = $owner;
        }
        foreach ($warehouses as $warehouse) {
            $warehouses_code_map[$warehouse->code] = $warehouse;
        }
        $params = $this->getParamsByAsnHeader($asnHerders, $owners_code_map, $warehouses_code_map);
        if (count($params) > 0) $this->insertStore($params);
        /** @var StoreItemService $storeItemService */
        $storeItemService = app(StoreItemService::class);
        $storeItemService->storeItemCreateByWms($asnHerders);
        /** @var RejectedBillService $rejectedBillService */
        $rejectedBillService = app(RejectedBillService::class);
        $rejectedBillService->syncLoadedStatusByAsnHerder($asnHerders);
        unset($asnHerders, $owners_code_map, $warehouses_code_map);
    }

    public function getParamsByAsnHeader($asnHerders, $owners_code_map, $warehouses_code_map)
    {
        $params = [];
        $stores = Store::query()->whereIn('asn_code', data_get($asnHerders, '*.asnno'))->get();
        $store_asn_code_map = [];
        foreach ($stores as $store) {
            $store_asn_code_map[$store->asn_code] = $store;
        }
        foreach ($asnHerders as $asnHerder) {
            if ($store_asn_code_map[$asnHerder->asnno] ?? false) continue;
            $owner = $owners_code_map[$asnHerder->customerid] ?? null;
            $warehouse = $warehouses_code_map[$asnHerder->warehouseid] ?? null;
            $status = null;
            if ($asnHerder->asnStatus && $asnHerder->asnStatus->codename_c == '完全收货') $status = '已入库';
            if ($asnHerder->asnStatus && $asnHerder->asnStatus->codename_c == '订单创建') $status = '未入库';
            $params[] = [
                'asn_code' => $asnHerder->asnno,
                'warehouse_id' => $warehouse->id ?? null,
                'owner_id' => $owner->id ?? null,
                'stored_method' => $asnHerder->asnType ? $asnHerder->asnType->codename_c : '',
                'status' => $status ? $status : $asnHerder->asnStatus->codename_c,
                'remark' => $asnHerder->notes ?? null,
                'created_at' => $asnHerder->addtime ?? null,
                'updated_at' => $asnHerder->edittime ?? null,
            ];
        }
        return $params;
    }

    public function insertStore(array $params)
    {
        if (count($params) === 0) return;
        foreach (array_chunk($params, 1000) as $item) {
            try {
                $bool = $this->insert($item);
                if ($bool) {
                    app('LogService')->log(__METHOD__, __FUNCTION__, "批量创建 store success " . count($item) . ' || ' . json_encode($item));
                } else app('LogService')->log(__METHOD__, __FUNCTION__, "批量添加 store FAILED " . ' || ' . json_encode($item));
            } catch (\Exception $e) {
                app('LogService')->log(__METHOD__, __FUNCTION__, "批量添加 store ERROR " . ' || ' . json_encode($params) . ' || ' . json_encode($e->getMessage()) . ' || ' . json_encode($e->getTraceAsString()));
            }
        }
    }

    public function updateStore($asnHerders)
    {
        if (!$asnHerders || $asnHerders->count() == 0) return null;
        /**
         * @var DataHandlerService $dataHandlerService
         * @var OwnerService $ownerService
         * @var WarehouseService $wareHouseService
         */
        $ownerService = app(OwnerService::class);
        $wareHouseService = app(WarehouseService::class);
        $dataHandlerService = app(DataHandlerService::class);
        $stores = $this->getByWms($asnHerders);
        $store_asn_code_map = $dataHandlerService->dataHeader(['asn_code'], $stores);
        $owners = $ownerService->getOwnerByCodes(array_unique(data_get($asnHerders,'*.customerid')));
        $warehouses = $wareHouseService->getWareHouseByCodes(array_unique(data_get($asnHerders,'*.warehouseid')));
        $owner_code_map = $dataHandlerService->dataHeader(['code'], $owners);
        $warehouses_map = $dataHandlerService->dataHeader(['code'], $warehouses);
        $updateParams = [[
            'id', 'asn_code', 'warehouse_id', 'owner_id', 'stored_method', 'status', 'remark', 'updated_at'
        ]];
        foreach ($asnHerders as $asnHerder) {
            $store = $dataHandlerService->getKeyValue(['asn_code' => $asnHerder->asnno], $store_asn_code_map);
            if (!$store) continue;
            $owner = $dataHandlerService->getKeyValue(['code' => $asnHerder->customerid], $owner_code_map);
            $warehouse = $dataHandlerService->getKeyValue(['code' => $asnHerder->warehouseid], $warehouses_map);
            $owner_id = $owner->id ?? null;
            $warehouse_id = $warehouse->id ?? null;
            $status = null;
            if ($asnHerder->asnStatus && $asnHerder->asnStatus->codename_c == '完全收货') $status = '已入库';
            if ($asnHerder->asnStatus && $asnHerder->asnStatus->codename_c == '订单创建') $status = '未入库';
            if ($store->asn_code != $asnHerder->asnno ||
                $store->warehouse_id != $warehouse_id ||
                $store->owner_id != $owner_id ||
                $store->stored_method != $asnHerder->asnType->codename_c ||
                $store->status != $asnHerder->asnStatus->codename_c ||
                $store->remark != $asnHerder->notes) {
                $updateParams[] = [
                    'id' => $store->id,
                    'asn_code' => $asnHerder->asnno,
                    'warehouse_id' => $warehouse_id,
                    'owner_id' => $owner_id,
                    'stored_method' => $asnHerder->asnType ? $asnHerder->asnType->codename_c : '',
                    'status' => $status ? $status : $asnHerder->asnStatus->codename_c,
                    'remark' => $asnHerder->notes,
                    'updated_at' => $asnHerder->edittime,
                ];
            }
        }
        if (count($updateParams) > 1) {
            foreach (array_chunk($updateParams, 1000) as $item) {
                try {
                    $bool=$this->batchUpdate($item);
                    if ($bool) {
                        app('LogService')->log(__METHOD__, __FUNCTION__, "批量修改 store success " . count($item) . ' || ' . json_encode($item));
                    } else app('LogService')->log(__METHOD__, __FUNCTION__, "批量修改 store FAILED " . ' || ' . json_encode($item));
                } catch (\Exception $e) {
                    app('LogService')->log(__METHOD__, __FUNCTION__, "批量修改 store ERROR " . ' || ' . json_encode($updateParams) . ' || ' . json_encode($e->getMessage()) . ' || ' . json_encode($e->getTraceAsString()));
                }
            }
        }
        /** @var StoreItemService $storeItemService */
        $storeItemService = app(StoreItemService::class);
        $storeItemService->storeItemUpdateByWms($asnHerders);
        /** @var RejectedBillService $rejectedBillService */
        $rejectedBillService = app(RejectedBillService::class);
        $rejectedBillService->syncLoadedStatusByAsnHerder($asnHerders);
        unset($updateParams, $asnHerders);
    }

    public function insert($params)
    {
        return Store::query()->insert($params);
    }

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

    public function getByWms($asnHerders)
    {
        if (!$asnHerders) {
            return null;
        }
        $asn_nos = array_unique(data_get($asnHerders, '*.asnno'));
        return Store::query()->whereIn('asn_code', $asn_nos)->get();
    }

    public function getAsnLastSyncAt($key, $type)
    {
        $last_time = ValueStore::query()->where('name', $key)->value('value');
        if ($last_time) return $last_time;
        if ($type == 'create') {
            $store = Store::query()->orderByDesc('created_at')->first();
            if ($store) return $store->created_at;
        } else {
            $store = Store::query()->orderByDesc('updated_at')->first();
            if ($store) return $store->updated_at;
        }
        return Carbon::now()->subSeconds(65);
    }

    public function setAsnLastSyncAt($key, $last_time)
    {
        $asnLastSyncAt = ValueStore::query()->updateOrCreate([
            'name' => $key,
        ], [
            'name' => $key,
            'value' => $last_time,
        ]);
        LogService::log(__METHOD__, __FUNCTION__, '修改或更新' . $key . json_encode($asnLastSyncAt));
        return $asnLastSyncAt;
    }

    public function deleteCacheKey($set, $keys)
    {
        if (Cache::get($set)) {
            $cacheKeys = Cache::get($keys);
            if (!$cacheKeys) return;
            foreach ($cacheKeys as $cacheKey) {
                Cache::forget($cacheKey);
            }
            Cache::forget($keys);
        }
    }

    public function setLastRecordsByRedis($prefixKey, $set, $keys, $last_records)
    {
        $cacheKeys = [];
        foreach ($last_records as $last_record) {
            Cache::put($prefixKey . $last_record->customerid . '_' . $last_record->asnno, true);
            array_push($cacheKeys, $prefixKey . $last_record->customerid . '_' . $last_record->asnno);
        }
        Cache::put($keys, $cacheKeys);
        Cache::put($set, true);
    }

    public function createInstantBill(Store $store): bool
    {
        if (!$store || $store->status != "已入库") return false;
        $store->loadMissing("storeItems");

        /** @var OwnerPriceOperationService $service */
        $service = app("OwnerPriceOperationService");

        $mapping = ["packages" => "storeItems", "商品名称" => "name", "订单类型" => "stored_method"];

        $work_fee = $service->matchRule($store, $mapping, $store->owner_id, "入库");
        if ($work_fee < 0) $work_fee = null;

        if (app("OwnerFeeDetailService")->create([
            "owner_id" => $store->owner_id,
            "worked_at" => $store->created_at,
            "type" => "收货",
            "operation_bill" => $store->asn_code,
            "commodity_amount" => array_sum(array_column($store->storeItems->toArray(), "amount")),
            "work_fee" => $work_fee,
            "created_at" => date('Y-m-d H:i:s'),
            "outer_id" => $store->id,
            "outer_table_name" => "stores",
        ])) return true;
        return false;
    }
}
