<?php namespace Goods\Lib;
use Dever;
use Place;
class Stock
{
    public function update($db, $data)
    {
        $info = explode(',', $data['info']);
        $where = array();
        $where['info_id'] = $data['info_id'] = $info[0];
        if (isset($info[1])) {
            $where['sku_id'] = $data['sku_id'] = $info[1];
        }
        if (!is_numeric($data['num'])) {
            Dever::error('数量必须为数字');
        }
        if ($data['num'] <= 0) {
            Dever::error('数量必须大于0');
        }
        $info = Dever::db('stock', 'goods')->find($where);
        if ($info) {
            $stock_id = $info['id'];
            $yue = $info['total'] - $info['sell'] - $info['out'];
            if ($data['type'] == 1) {
                $data['yue'] = $yue + $data['num'];
                $state = Dever::db('stock', 'goods')->update($info['id'], array('total' => array('+', $data['num'])));
            } elseif ($data['type'] == 2) {
                if ($num > $yue) {
                    Dever::error('库存不足，出库失败');
                } else {
                    $data['yue'] = $yue - $data['num'];
                    $state = Dever::db('stock', 'goods')->update($info['id'], array('out' => array('+', $data['num'])));
                }
            }
        } else {
            if ($data['type'] == 2) {
                Dever::error('库存不足，出库失败');
            } else {
                $data['yue'] = $data['total'] = $data['num'];
            }
            $stock_id = $state = Dever::db('stock', 'goods')->insert($data);
        }
        
        if ($state) {
            $data['stock_id'] = $stock_id;
            $state = Dever::db('stock_log', 'goods')->insert($data);
        }
        return 'end';
    }

    # 获取当前库存
    public function yue($info_id, $sku_id)
    {
        $where['info_id'] = $info_id;
        if ($sku_id) {
            $where['sku_id'] = $sku_id;
        }
        $info = Dever::db('stock', 'goods')->find($where);
        if ($info) {
            return Dever::number($info['total'] - $info['sell'] - $info['out'], 2);
        }
        return false;
    }

    # 售出
    public function sell($info_id, $sku_id, $num)
    {
        $where = array();
        $where['info_id'] = $info_id;
        $where['sku_id'] = $sku_id;
        $info = Dever::db('stock', 'goods')->find($where);
        if ($info) {
            return Dever::db('stock', 'goods')->update(' id = ' . $info['id'] . ' and `total`-`sell`-`out` >=' . $num, array('sell' => array('+', $num)));
        }
        return false;
    }

    # 退款
    public function refund($info_id, $sku_id, $num)
    {

    }
}