<?php

namespace app\models\system;

use app\admin\model\store\StoreProduct;
use app\admin\model\store\StoreProductAttrValue;
use app\models\store\StoreOrderCartInfo;
use crmeb\basic\BaseModel;
use crmeb\services\PHPExcelService;
use crmeb\traits\ModelTrait;

class SystemStoreStock extends BaseModel
{
    use ModelTrait;

    public static function lst($where)
    {
        $model = new self;
        $model = $model->alias("a")->join("store_product b", "a.product_id=b.id", "right");
        if ($where['store_id'] > 0) $model = $model->where('a.store_id', $where['store_id']);
        if ($where['key']) $model = $model->wherelike('b.store_name', "%" . $where['key'] . "%");
        if (isset($where['is_warn']) && $where['is_warn'] == 1) $model = $model->where('a.in_stock', '<=', sys_config('warn_stock'));
        $model = $model->where('a.id', '>', 0);
        $model = $model->field('a.product_id,b.store_name,b.image,b.is_show,b.is_del,a.store_id,a.in_stock,a.store_sales,a.repair_sales,a.in_last_time,a.bar_code,a.price,a.is_consumer');
        $count = $model->count();
        if ($where['excel']) {
            $data = $model->order("product_id desc")->select()->toarray();
            $export = [];
            foreach ($data as &$value) {
                $export[] = [
                    SystemStore::where('id', $value['store_id'])->value('name'),
                    $value['store_name'],
                    $value['price'],
                    $value['in_stock'],
                    $value['repair_sales'],
                    $value['store_sales'],
                ];
            }
            PHPExcelService::setExcelHeader(['门店', '商品名称', '价格', '库存', '待补货', '销量'])
                ->setExcelTile('门店库存', '门店库存' . time(), ' 生成时间：' . date('Y-m-d H:i:s', time()))
                ->setExcelContent($export)
                ->ExcelSave();

        }
        $data = $model->page($where['page'], $where['limit'])->order("product_id desc")->select()->toarray();
        foreach ($data as &$v) {
            $v['store'] = SystemStore::where('id', $v['store_id'])->value('name');
        }
        return compact('count', 'data');
    }

    /**
     * 店铺初始商品库存
     * @param int $num
     */
    public static function store_init($store_id, $num = 100)
    {
        $store = SystemStore::get($store_id);
        $where['store_id'] = 0;
        if ($store['is_triple']) $where['store_id'] = $store_id;
        $list = StoreProduct::where('is_del', 0)->where('is_show', 1)->where($where)->column('id,is_consumer', 'id');
        $data['store_id'] = $store_id;
        $data['in_stock'] = $num;
        $all = [];
        $rs = StoreProductAttrValue::where('product_id', 'in', array_keys($list))->where('type', 0)->field('product_id,unique,image,bar_code,price')->select()->toArray();
        foreach ($rs as $v) {
            $data['product_id'] = $v['product_id'];
            $data['in_last_time'] = time();
            $data['unique'] = $v['unique'];
            $data['price'] = $v['price'];
            $data['image'] = $v['image'];
            $data['bar_code'] = $v['bar_code'];
            $data['is_consumer'] = $list[$v['product_id']]['is_consumer'];
            $all[] = $data;
        }
        self::insertAll($all);
        return true;
    }

    /**
     * 补货
     * @param $store_id
     * @param $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function replenish($store_id, $data)
    {
        if ($data['product_id'] > 0 && $data['in_stock'] > 0) {
            $info = self::where(['store_id' => $store_id, 'product_id' => $data['product_id'], 'bar_code' => $data['bar_code']])->find();
            if ($info) {
                if ($data['type'] == 1) {
                    $add = bcsub($data['in_stock'], $info['repair_sales']);
                    if ($add > 0) {
                        self::where(['store_id' => $store_id, 'product_id' => $data['product_id'], 'bar_code' => $data['bar_code']])->update(['in_stock' => bcadd($info['in_stock'], $add), 'repair_sales' => 0]);
                    } else {
                        self::where(['store_id' => $store_id, 'product_id' => $data['product_id'], 'bar_code' => $data['bar_code']])->update(['repair_sales' => bcsub($info['repair_sales'], $data['in_stock'])]);
                    }
                    @file_put_contents("stock.txt", self::getlastsql());
                } else {
                    if ($info['in_stock'] < $data['in_stock']) {
                        return self::setErrorInfo('库存不足');
                    }
                    self::where(['store_id' => $store_id, 'product_id' => $data['product_id'], 'bar_code' => $data['bar_code']])->update(['in_stock' => bcsub($info['in_stock'], $data['in_stock'])]);
                    @file_put_contents("stock.txt", self::getlastsql());
                }
                return true;
            } else {
                if ($data['type'] == 2) {
                    return self::setErrorInfo('库存无法减少');
                }
                $data1['product_id'] = $data['product_id'];
                $data1['in_last_time'] = time();
                $data1['in_stock'] = $data['in_stock'];
                $data1['unique'] = StoreProductAttrValue::where('product_id', $data['product_id'])->value('unique');
                $data1['price'] = $data['price'];
                $data1['image'] = $data['image'];
                $data1['bar_code'] = $data['bar_code'];
                $data1['is_consumer'] = $data['is_consumer'];
                $data1['store_id'] = $store_id;
                self::create($data1);
                return true;
            }
        }
        return self::setErrorInfo('参数异常');
    }

    public static function Refund($orderInfo, $data)
    {
        $reg_store_id = $orderInfo['reg_store_id'];
        if ($orderInfo['create_store_id'] > 0) {
            $reg_store_id = $orderInfo['create_store_id'];
        }
        $store_id = $orderInfo['store_id'];
        $field = "store_sales";
        if (intval($reg_store_id) > 0 && intval($reg_store_id) != $store_id) {
            $field = "repair_sales";
        }
        self::where("product_id", $data['product_id'])->where('unique', $data['product_attr_unique'])->where('store_id', $store_id)->inc('in_stock', $data['cart_num'])->dec($field, $data['cart_num'])->update();
        return true;
    }

    /**
     * 门店销量
     * @param $order
     */
    public static function add_store_sales($orderInfo)
    {
        if ($orderInfo['suit']) return;
        $cartId = is_string($orderInfo['cart_id']) ? json_decode($orderInfo['cart_id'], true) : $orderInfo['cart_id'];
        $cartInfo = StoreOrderCartInfo::whereIn('cart_id', $cartId)->column('cart_info');
        $reg_store_id = $orderInfo['reg_store_id'];
        if ($orderInfo['create_store_id'] > 0) {
            $reg_store_id = $orderInfo['create_store_id'];
        }
        $store_id = $orderInfo['store_id'];
        $field = "store_sales";
        if (intval($reg_store_id) > 0 && intval($reg_store_id) != $store_id) {
            $field = "repair_sales";
        }
        foreach ($cartInfo as $value) {
            $product = json_decode($value, true);
            $cartNum = $product['cart_num'] ?? 0;
            $is_consumer = $product['is_consumer'] ?? 0;
            $unique = $product['product_attr_unique'];
            $product_id = $product['product_id'];
            $bar_code = $product['productInfo']['attrInfo']['bar_code'];
            $price = $product['productInfo']['attrInfo']['price'];
            $image = $product['productInfo']['attrInfo']['image'];
            if (self::be(compact('product_id', 'unique', 'is_consumer', 'store_id'))) {
                self::where(compact('product_id', 'unique', 'is_consumer', 'store_id'))->inc($field, $cartNum)->dec('in_stock', $cartNum)->update();
            } else {
                $in_stock = 0 - intval($cartNum);
                self::create(compact('product_id', 'unique', 'is_consumer', 'store_id', 'bar_code', 'price', 'image', 'in_stock'));
            }
        }
    }

}