<?php namespace Goods\Api;
use Dever;
use Manage\Lib\Auth;
class Manage extends Auth
{
    # 将sku中的key解析成前端可以读取的格式
    public function keyToField($key)
    {
        if ($key != -1) {
            $result = array();
            $array = explode(',', $key);
            $result['key']['set'] = array();
            foreach ($array as $k => $v) {
                $value = Dever::db('info_spec_value', 'goods')->find($v);
                $spec = Dever::db('info_spec', 'goods')->find($value['spec_id']);
                $result['key']['set']['s_' . $spec['id']] = array($spec['name'], $value['value']);
            }
            return $result;
        }
    }

    # 获取多选规格
    public function getMulSku($value = false)
    {
        $result = $this->sku($value);
        $result['sku_id']['value'] = array();
        if (isset($result['sku_id']['option'][0]) && $result['sku_id']['option'][0]['name'] == '无') {
            $result['sku_id']['option'] = array();
        }
        return $result;
    }

    # 获取规格
    public function getSku($value = false)
    {
        return $this->sku($value);
    }

    # 获取全部规格
    public function getAllSku($value = false)
    {
        $set[0] = array
        (
            'id' => -1,
            'name' => '全部规格',
        );
        return $this->sku($value, $set);
    }

    private function sku($value, $set = array())
    {
        if (is_array($value)) {
            $value = end($value);
        }
        $result = array();
        $result['sku_id']['value'] = '';
        if (!$value) {
            $result['sku_id']['option'] = array();
            return $result;
        }
        $result['goods_id']['value'] = (float) $value;
        $sku = Dever::db('info_sku', 'goods')->select(array('info_id' => $value));
        if ($sku) {
            $option = $set;
            if ($set) {
                $result['sku_id']['value'] = -1;
            }
            foreach ($sku as $k => $v) {
                if ($v['key'] != -1) {
                    $spec = Dever::db('info_spec_value', 'goods')->find(array('id' => array('in', $v['key'])), array('col' => 'id,group_concat(value) as name', 'group' => 'info_id'));
                    if ($spec) {
                        $spec['id'] = $v['id'];
                        if (!$set) {
                            $result['sku_id']['value'] = $v['id'];
                        }
                        $option[] = $spec;
                    }
                } else {
                    $result['sku_id']['value'] = $v['id'];
                    $option[0] = array
                    (
                        'id' => $v['id'],
                        'name' => '无',
                    );
                }
            }
            $result['sku_id']['option'] = $option;
        }
        
        return $result;
    }
}