<?php

namespace app\queue\redis;

use app\admin\logic\store_product\StoreProductLogic;
use app\common\model\store_branch_product\StoreBranchProduct;
use app\common\model\store_branch_product_attr_value\StoreBranchProductAttrValue;
use app\common\model\store_branch_product_exchange\StoreBranchProductExchange;
use app\common\model\store_product\StoreProduct;
use app\common\model\store_product_attr_value\StoreProductAttrValue;
use app\common\model\system_store_storage\SystemStoreStorage;
use Webman\RedisQueue\Consumer;
use support\Log;
use think\facade\Db;

/**
 * 门店库存记录商品
 */
class StoreStorageSend implements Consumer
{
    // 要消费的队列名
    public $queue = 'store-storage';

    // 连接名,对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    // 消费
    public function consume($data)
    {
        $product_arr = $data['product_arr'];
        $store_id = $data['store_id'];
        $stock_type = $data['stock_type'];
        $admin_id = $data['admin_id'];
        $find = StoreProduct::where('id', $product_arr['id'])->findOrEmpty()->toArray();
        if($stock_type == 1){
            $this->ordinary($product_arr,$store_id,$admin_id,$find);
        }elseif($stock_type == 2){
            $this->exchange($product_arr,$store_id,$admin_id,$find);
        }
    }

    /**普通 */
    public function ordinary($product_arr,$store_id,$admin_id,$find){
        $store_find = StoreBranchProduct::where(['product_id' => $product_arr['id'], 'store_id' => $store_id])->findOrEmpty()->toArray();
        if ($find && !$store_find) {
            $attr_value = StoreProductAttrValue::where('product_id', $product_arr['id'])->findOrEmpty();
            Db::startTrans();
            try {
                $product = [
                    'product_id' => $find['id'],
                    'image' => $find['image'],
                    'store_name' => $find['store_name'],
                    'store_info' => $find['store_info'],
                    'keyword' => $find['keyword'],
                    'bar_code' => $find['bar_code'],
                    'cate_id' => $find['cate_id'],
                    'price' => $find['price'],
//                    'cost' => $find['cost'], //v1.0
                    'cost' => $find['cost'],
                    'purchase' => $find['purchase'],
                    'vip_price' => $find['vip_price'],
                    'unit' => $find['unit'],
                    'batch' => $find['batch'],
                    'store_id' => $store_id,
                    'sales' => 0,
                    'stock' => 0,
                ];
                $branch = StoreBranchProduct::create($product);
                $arr = [
                    'product_id' => $product_arr['id'],
                    'store_id' => $store_id,
                    'unique' => setUnique($branch['id'], '', 0),
                    'sales' => 0,
                    'type' => 0,
                    'bar_code' => $attr_value['bar_code']
                ];
                StoreBranchProductAttrValue::create($arr);
                if ($product_arr['stock'] > 0) {
                    $this->storage($find, $store_id, $admin_id, $product_arr);
                }
                StoreProductLogic::updateGoodsclass($find['cate_id'],$store_id);
                Db::commit();
                return true;
            } catch (\Exception $e) {
                Db::rollback();
                Log::error('store-storage队列消费失败: ' . $e->getMessage() . ',line:' . $e->getLine() . ',file:' . $e->getFile());
                return false;
            }
        } else {
            Db::startTrans();
            try {
                if ($product_arr['stock'] > 0) {
                    $this->storage($find, $store_id, $admin_id, $product_arr,1);
                }
                Db::commit();
                return true;
            } catch (\Exception $e) {
                Db::rollback();
                Log::error('store-storage队列消费失败: ' . $e->getMessage() . ',line:' . $e->getLine() . ',file:' . $e->getFile());
                return false;
            }
        }
    }

    /**兑换 */
    public function exchange($product_arr,$store_id,$admin_id,$find){
        $store_find = StoreBranchProductExchange::where(['product_id' => $product_arr['id'], 'store_id' => $store_id])->findOrEmpty()->toArray();
        if ($find && !$store_find) {
            Db::startTrans();
            try {
                $product = [
                    'product_id' => $find['id'],
                    'image' => $find['image'],
                    'store_name' => $find['store_name'],
                    'store_info' => $find['store_info'],
                    'keyword' => $find['keyword'],
                    'bar_code' => $find['bar_code'],
                    'cate_id' => $find['cate_id'],
                    'price' => $find['price'],
                    'cost' => $find['cost'],
                    'purchase' => $find['purchase'],
                    'vip_price' => $find['vip_price'],
                    'unit' => $find['unit'],
                    'store_id' => $store_id,
                    'sales' => 0,
                    'stock' => 0,
                ];
                StoreBranchProductExchange::create($product);
                if ($product_arr['stock'] > 0) {
                    $this->storage($find, $store_id, $admin_id, $product_arr);
                }
                // StoreProductLogic::updateGoodsclass($find['cate_id'],$store_id);
                Db::commit();
                return true;
            } catch (\Exception $e) {
                Db::rollback();
                Log::error('store-storage队列消费失败: ' . $e->getMessage() . ',line:' . $e->getLine() . ',file:' . $e->getFile());
                return false;
            }
        } else {
            Db::startTrans();
            try {
                if ($product_arr['stock'] > 0) {
                    $this->storage($find, $store_id, $admin_id, $product_arr,2);
                }
                Db::commit();
                return true;
            } catch (\Exception $e) {
                Db::rollback();
                Log::error('store-storage队列消费失败: ' . $e->getMessage() . ',line:' . $e->getLine() . ',file:' . $e->getFile());
                return false;
            }
        }
    }
    public function storage($find, $store_id, $admin_id, $product_arr,$stock_type=1)
    {
        $storage = [
            'product_id' => $product_arr['id'],
            'store_id' => $store_id,
            'nums' => $product_arr['stock'],
            'admin_id' => $admin_id,
            'type' => $stock_type,
        ];
        if ($find['stock'] < $product_arr['stock']) {
            $storage['status'] = -1;
            $storage['mark'] = '库存不足,主库存为:' . $find['stock'];
            SystemStoreStorage::create($storage);
        } else {
            SystemStoreStorage::create($storage);
            StoreProduct::where('id', $product_arr['id'])->dec('stock', $product_arr['stock'])->update();
        }
    }

    public function onConsumeFailure(\Throwable $e, $package)
    {
        $package['max_attempts'] = 0;
        Log::error('store-storage队列消费失败: ' . $e->getMessage() . ',line:' . $e->getLine() . ',file:' . $e->getFile());
        return $package;
    }
}