<?php

# 核心类，数据获取类

namespace Goods\Lib;

use Dever;

class Info
{
    private $table_info = 'goods/info';
    private $table_attr = 'goods/info_attr';
    private $table_sku = 'goods/info_sku';
    /**
     * instance
     *
     * @var string
     */
    protected static $instance;

    /**
     * init
     *
     * @return mixed
     */
    public static function init($top_category = false)
    {
        if (empty(self::$instance[$top_category])) {
            self::$instance[$top_category] = new self($top_category);
        }

        return self::$instance[$top_category];
    }

    public function __construct($top_category = false)
    {
        $this->top_category = $top_category;

        # 必有有分类才能进入到需求中
        if (!$this->top_category) {
            $this->top_category = -1;
            //Dever::alert('错误的分类信息');
        }
    }

    # 根据商品条形码获取商品
    public function getGoodsByCode($type_id = false, $type = 1, $check = true)
    {
        $code = Dever::input('code');

        if (!$code) {
            Dever::alert('错误的条形码');
        }
        $where['code'] = $code;
        $sku = Dever::db('goods/info_sku')->find($where);

        if (!$sku) {
            Dever::alert('商品不存在');
        }

        $goods = Dever::db('goods/info')->find($sku['info_id']);

        if (!$goods) {
            Dever::alert('商品不存在');
        }
        if ($goods['status'] != 1) {
            Dever::alert('商品已下架');
        }

        if ($type_id > 0) {
            if ($type == 1) {
                $table = 'shop/goods_sku';
                $col = 'shop_id';
                $name = '门店';
            } elseif ($type == 2) {
                $table = 'store/goods_sku';
                $col = 'store_id';
                $name = '仓库';
            } elseif ($type == 3) {
                $table = 'factory/goods_sku';
                $col = 'factory_id';
                $name = '工厂';
            }

            $where = array();
            $where[$col] = $type_id;
            $where['goods_id'] = $goods['id'];
            $where['sku_id'] = $sku['id'];
            $data = Dever::db($table)->getOne($where);
            if (!$data) {
                if ($sku['key'] == -1) {
                    $where['sku_id'] = -1;
                    $data = Dever::db($table)->getOne($where);
                    if (!$data) {
                        Dever::alert($name . '商品不存在');
                    }
                } else {
                    Dever::alert($name . '商品不存在');
                }
            }

            if ($check && $data['total'] <= 0) {
                # 验证库存
                Dever::alert($name . '商品库存不足');
            }
        }

        if ($sku['key'] == -1) {
            $sku['id'] = -1;
        }

        $goods['sku'] = $sku;
        return $goods;
    }

    private function setAttr($cate, $order = 'list_reorder')
    {
        if ($order != 'list_reorder') {
            Dever::config('base')->attrOrder = $order;
        }
        
        Dever::setInput('update_category', $cate);
        $attr = Dever::db($this->table_attr, array(), $cate);
        return $attr;
    }

    public function getAttr($cate)
    {
        return Dever::load('attr/api')->getAttrByCate($cate, 'list');
    }

    # 根据分类获取需求列表数据
    public function getData($cate = false, $limit = '0,10', $page = false, $attr = true)
    {
        if (!$limit) {
            $limit = '0,10';
        }
        $where = $data = array();
        if (!$cate) {
            if ($this->top_category > 0) {
                $where['top_category_id'] = $this->top_category;
            }
        } elseif (strstr($cate, ',')) {
            $where['category'] = $this->top_category . ',' . $cate;
        } else {
            $where['second_category_id'] = $cate;
        }
        
        if ($page) {
            $method = 'getPageAll';
        } else {
            $where['limit'] = $limit;
            $method = 'getAll';
        }
        $name = Dever::input('name');
        if ($name) {
            $where['name'] = $name;
        }
        $data = Dever::db($this->table_info)->$method($where);
        if ($data && $attr) {
            foreach ($data as $k => $v) {
                $data[$k] = $this->info($v, 'list_reorder');
            }
        }

        return $data;
    }

    # 根据属性获取需求列表数据 这里带有检索属性的功能 此处还需优化
    public function getDataByAttr($cate = false, $where = array())
    {
        if (!$cate) {
            Dever::alert('错误的分类信息');
        }
        $where_sql = array();
        $name = Dever::input('name');
        if ($name) {
            //$where['name'] = $name;
            $where_sql[] = ' t_2.name = "'.$name.'"';
        }

        $attr = $this->setAttr($this->top_category . ',' . $cate);
        //print_r($attr->config['attr']);

        $where_sql = Dever::load('attr/api')->getSql($attr->config['attr'], $where, $where_sql);
        if (!$where_sql) {
            return array();
        }
        # 这里用pdo的数据绑定，字符串字段的区间查询就是有问题。。。只能用sql了
        //$data = $attr->getPageAll($where);

        $page['template'] = 'list';
        $page['num'] = 10;
        $where_sql = implode(' and ', $where_sql);

        $sql = 'SELECT t_2.* FROM `{project}_goods_'.$attr->config['name'].'` as t_1 Left Join `{project}_goods_info` AS t_2 ON t_1.`info_id`=t_2.`id` WHERE '.$where_sql.' order by t_2.`reorder` desc,t_2.`id` desc';

        $data = $attr->fetchAll($sql, array(), $page);

        if ($data) {
            foreach ($data as $k => $v) {
                $data[$k] = $this->info($v, 'list_reorder');
            }
        }

        return $data;
    }

    # 获取列表页的搜索条件
    public function getSearch($cate = false)
    {
        # 获取搜索条件
        if (!$cate) {
            $search_cate = $cate = $this->top_category;
        } else {
            $search_cate = $cate;
        }
        # 1是当前用户所在的城市，暂时写死
        # 获取搜索条件
        $search = Dever::load('attr/api')->getSearch($search_cate, true, 1, false, 2);
        # 下级分类
        $search['cate'] = Dever::load('category/api')->getList($cate);

        # 上级分类
        $search['parent_cate'] = Dever::load('category/api')->getList($this->top_category);
        return $search;
    }

    # 获取支付信息
    public function getPayState($uid, $id, $category)
    {
        $pay_where['category'] = $category;
        $pay = Dever::db('goods/pay')->one($pay_where);
        $pay_state = 0;
        if ($pay && $pay['num'] > 0) {
            $pay_state = $pay['num'];
        } elseif (strstr($category, ',')) {
            $category = explode(',', $category);
            $category = array_pop($category);
            $pay_state = $this->getPayState($uid, $id, $category);
        }

        //$update['where_id'] = $id;
        //$update['poster_pay_type'] = $pay_state;
        //Dever::db($this->table_info)->update($update);

        return $pay_state;
    }

    # 更新需求
    public function update($top, $cate, $data, $id, $uid)
    {
        if ($cate) {
            $category = $top . ',' . $cate;
        } else {
            $category = $top;
        }
        $attr = $this->setAttr($category);

        $attr_update = Dever::preInput('attr_');
        if ($attr_update) {
            foreach ($attr_update as $k => $v) {
                if (strstr($k, '_s')) {
                    $k = str_replace('_s', '', $k);
                    $attr_update[$k] = $v;
                }
                if (strstr($k, '_e')) {
                    $k = str_replace('_e', '', $k);
                    $attr_update[$k] .= ',' . $v;
                }
            }
        }

        $update = array();
        $update['name'] = $data['name'];
        $update['category'] = $category;
        $update['pic'] = $data['pic'];
        //$update['pic_cover'] = $data['pic'];
        $update['poster_uid'] = $uid;
        if (isset($data['view_price']) && $data['view_price']) {
            $update['view_price'] = $data['view_price'];
        }
        if ($uid && $id) {
            # 此处要判断是用户自己的
            $info = Dever::db($this->table_info)->one($id);

            /*
            if ($uid == $info['poster_uid']) {
                Dever::alert('错误的用户参数');
            }
            */
            $update['where_id'] = $attr_update['where_id'] = $id;
            Dever::db($this->table_info)->update($update);
            Dever::db($this->table_attr)->update($attr_update);
            $pay = 0;
        } else {
            $id = Dever::db($this->table_info)->insert($update);
            $attr_update['category'] = $update['category'];
            $attr_update['info_id'] = $id;
            $attr_update['id'] = $id;
            Dever::db($this->table_attr)->insert($attr_update);

            # 验证是否需要支付，根据category判断
            $pay = false;
            //$pay = $this->getPayState($uid, $id, $category);

            $info = Dever::db($this->table_info)->one($id);
            $info = $this->getInfoLink($info);
        }
        return array('id' => $id, 'pay' => $pay, 'cate' => $category, 'top' => $top, 'info' => $info);
    }

    # 获取支付所需要的信息
    public function getPayInfo($id, $sku = 0, $type = 1, $value = '')
    {
        $info = is_array($id) ? $id : Dever::db($this->table_info)->find($id);

        if ($info) {
            if ($type == 2) {
                $info['price'] = $info['f_price'];
                unset($info['s_price']);
            } else {
                unset($info['f_price']);
            }
            $info['sku_name'] = '';
            $sku = $sku > 0 ? $sku : $info['sku_id'];
            if ($sku > 0) {
                $where['info_id'] = $info['id'];
                $where['id'] = $sku;
                $sku = Dever::db('goods/info_sku')->find($where);
                if ($sku) {

                    if ($sku['type'] == 3) {
                        $price = $sku['price'];
                        $s_price = $sku['s_price'];
                        $f_price = $sku['f_price'];
                        $c_price = $sku['c_price'];
                        $sku['price'] = 0;
                        $sku['s_price'] = 0;
                        $sku['f_price'] = 0;
                        $sku['c_price'] = 0;
                        # 计算价格
                        $key = explode('_', $sku['key']);
                        $attr = Dever::db('attr/info')->find($key[0]);
                        if ($attr) {
                            if ($value >= $attr['sell_value']) {
                                $sku['price'] = $price;
                                $sku['s_price'] = $s_price;
                                $sku['f_price'] = $f_price;
                                $sku['c_price'] = $c_price;
                            }
                        }
                    }

                    $info['sku_id'] = $sku['id'];
                    if ($type == 2) {
                        $info['price'] = $sku['f_price'];
                    } else {
                        $info['price'] = $sku['price'];
                        $info['s_price'] = $sku['s_price'];
                        $info['c_price'] = $sku['c_price'];
                    }

                    $info['min'] = $sku['min'];
                    //$info['attr_json'] = $sku['attr'];
                    $info['attr'] = Dever::json_decode($sku['attr']);

                    if ($info['attr']) {
                        $info['attr'] = Dever::load('attr/api')->getInfoByJson($info['attr']);
                        $info['sku_name'] = $info['attr']['string'];
                    }
                }
            }

            /*
            $info['freight_id'] = 0;
            $info['freight_price'] = 0;
            $freight = $this->freight($info, $info['price'], $user, $num);
            if ($freight) {
                $info['freight_id'] = $freight['id'];
                $info['freight_price'] = $freight['price'];
            }
            */

            # 佣金计算
            //$info['reward'] = $this->reward($info, $info['price']*$num);
        }

        return $info;
    }

    # 获取自提信息
    public function storeInfo($goods_id, $area_id = '')
    {
        $info = Dever::db($this->table_info)->find($goods_id);
        if (!$info) {
            return array();
        }
        $array = explode(',', $info['category']);
        $cate = $store = array();
        $total = count($array);
        $total -= 1;
        # 用户所在地理位置 
        if ($area_id) {
            $where['area'] = $area_id;
        }
        foreach ($array as $k => $v) {
            $cate[$k] = $v;
            if ($k < $total) {
                $cate[] = '-1';
            }
            $where['category'] = $cate;

            $data = Dever::db('goods/store')->state($where);
            if ($data) {
                $store += $data;
            }
        }

        return $store;
    }

    # 获取运费信息
    public function getFreight($id, $goods_price, $user, $num)
    {
        $info = Dever::db($this->table_info)->find($id);
        return $this->freight($info, $goods_price, $user, $num);
    }

    # 根据已经选择的sku获取商品信息
    public function getInfoBySku($id, $sku_id)
    {
        $info = Dever::db($this->table_info)->find($id);

        if ($info) {
            if (!isset($info['unit'])) {
                $info['unit'] = '';
            }
            if (!isset($info['weight'])) {
                $info['weight'] = '';
            }
            if (!isset($info['code'])) {
                $info['code'] = '';
            }
            $info['sku_name'] = '';
            if ($sku_id > 0) {
                $sku = Dever::db($this->table_sku)->find($sku_id);

                if ($sku && $sku['attr']) {
                    $sku['attr'] = Dever::json_decode($sku['attr']);
                    $info['sku'] = Dever::load('attr/api')->getInfoByJson($sku['attr']);
                    $info['code'] = $sku['code'];
                    $info['sku_name'] = $info['sku']['string'];
                    $info['unit'] = $sku['unit'];
                    $info['weight'] = $sku['weight'];
                }
            }
        }

        return $info;
    }

    # 获取基本信息
    public function getInfo($info, $attr = true, $other = false, $order = 'view_reorder', $user = array(), $reward = false)
    {
        if (!is_array($info)) {
            $info = Dever::db($this->table_info)->find($info);
        }

        if (!$info) {
            Dever::alert('商品不存在');
        }
        
        if ($info && $attr) {
            $info = $this->info($info, $order, $other, $user, $reward);
        } else {
            $this->getGroup($info);
        }

        if (!isset($info['goods_id'])) {
            $info['goods_id'] = $info['id'];
        }

        if ($info['pic']) {
            $info['pic'] = explode(',', $info['pic']);
        }

        if ($info['tag_id']) {
            $info['tag'] = Dever::db('goods/tag')->getAllByIds(array('ids' => $info['tag_id']));
        }

        return $info;
    }

    # 获取组合商品
    public function getGroup(&$info)
    {
        if ($info && $info['price_type'] > 2 && $info['goods'] && is_string($info['goods'])) {
            # 获取套餐或者组合的商品
            $goods = Dever::array_decode($info['goods']);
            $goods_info = array();
            foreach ($goods as $k => $v) {
                $ginfo = Dever::db('goods/info')->one($v['goods_id']);
                if ($ginfo) {
                    $goods_info[] = array
                    (
                        'id' => $ginfo['id'],
                        'name' => $ginfo['name'],
                        'price' => $ginfo['price'],
                        'cover' => $ginfo['cover'],
                        'num' => $v['num'],
                    );
                }
            }
            $info['goods'] = $goods_info;
        }
    }

    # 获取基本信息
    public function info($info, $key = 'view_reorder', $other = false, $user = array(), $reward = false)
    {
        $info['category_array'] = Dever::load('category/api')->string($info['category']);
        if ($info['price_type'] == 2) {
            
            $attr = $this->setAttr($info['category'], $key);
            $attr_data = $attr->one($info['id']);

            $info['attr'] = $info['group_attr'] = $info['single_attr']  = $info['input_attr'] = array();

            if ($attr->config['attr']) {
                $i = 0;
                foreach ($attr->config['attr'] as $k => $v) {
                    if (isset($v[$key]) && $v[$key] > 0 && $v['state'] == 1) {
                        if (isset($attr_data['attr_' . $v['id']])) {
                            $v['value'] = $attr_data['attr_' . $v['id']];
                        } else {
                            continue;
                            $v['value'] = '';
                        }

                        $v['value_string'] = Dever::load('attr/api')->getValue($v);
                        
                        if ($v['ename'] == 'price') {
                            $info['price'] = $v['value_string'];
                        } else {
                            if ($v['icon']) {
                                $v['bg'] = 'background-image: url('.$v['icon'].')';
                                $v['pic'] = '<img src="'.$v['icon'].'" width="18" />';
                            }
                            
                            $info['attr'][$i] = $this->attr($i, $v, $info);
                            $i++;
                        }
                    }
                }

                # 获取sku的价格
                $this->getPrice($info, $other);
            }

            if (!$info['attr']) {
                $info['price_type'] = 1;
            }
        }
       
        if (isset($info['cdate']) && $info['cdate']) {
            $info['cdate_string'] = Dever::mdate($info['cdate'], 2);
        }

        $info = $this->getInfoLink($info);

        $this->getGroup($info);

        if (Dever::config('base')->buy && Dever::config('base')->buy == 1) {
            $info['price'] = $info['f_price'];
        }


        //$info['freight'] = 0;
        //unset($info['goods']);
        unset($info['f_price']);
        unset($info['cdate']);
        unset($info['udate']);
        unset($info['category']);
        unset($info['top_category_id']);
        unset($info['second_category_id']);
        unset($info['category_id']);
        unset($info['area']);
        unset($info['mode']);
        unset($info['top']);
        unset($info['youhui']);
        unset($info['status']);
        unset($info['reorder']);
        unset($info['state']);

        return $info;
    }

    # 佣金计算
    private function reward($info, $price)
    {
        if ($info['reward_value'] && $info['reward_value'] > 0) {
            if ($info['reward_type'] == 2) {
                $info['reward_value'] = round(($info['reward_value']/100) * $price, 2);
            }
            return $info['reward_value'];
        }
        $array = explode(',', $info['category']);
        $cate = $reward = array();
        $total = count($array);
        $total -= 1;
        foreach ($array as $k => $v) {
            $cate[$k] = $v;
            if ($k < $total) {
                $cate[] = '-1';
            }
            $where['category'] = $cate;

            $data = Dever::db('goods/reward')->one($where);
            if ($data) {
                $reward = $data;
            }
        }

        if ($reward) {
            if ($reward['value'] && $reward['value'] > 0) {
                if ($reward['type'] == 2) {
                    $reward['value'] = round(($reward['value']/100) * $price, 2);
                }
                return $reward['value'];
            }
        }

        return 0;
    }

    # 运费计算，暂时用省份代表地区
    private function freight($info, $goods_price, $user = array(), $num = 1)
    {
        $array = explode(',', $info['category']);
        $cate = $freight = array();
        $total = count($array);
        $total -= 1;
        if ($info && $info['goods_area']) {
            $where['goods_area'] = $info['goods_area'];
        }
        # 用户所在地理位置 
        if ($user && isset($user['area_id']) && $user['area_id']) {
            $area = explode(',', $user['area_id']);
            $where['area'] = $area[0];
        }
        foreach ($array as $k => $v) {
            $cate[$k] = $v;
            if ($k < $total) {
                $cate[] = '-1';
            }
            $where['category'] = $cate;

            $data = Dever::db('goods/freight')->one($where);
            if ($data) {
                $freight = $data;
            }
        }

        if ($freight) {
            $price = $freight['first_price'];
            if ($num > $freight['first_num']) {
                $num = $num - $freight['first_num'];
                $price = $freight['first_price'] + ($freight['next_price']*$num);
            }

            if ($freight['type'] == 2) {
                $freight['price'] = round($goods_price*$num*($price/100), 2);
            } else {
                $freight['price'] = $price;
            }
        }

        return $freight;
    }

    private function attr($key, $data, &$info)
    {
        # 获取销售属性
        if ($data['option']) {
            $value = explode(',', $data['value']);
            $option = $data['option'];
            $data['option'] = array();
            foreach ($value as $k => $v) {
                if (isset($option[$v])) {
                    $option[$v]['parent_name'] = $data['name'];
                    $data['option'][] = $info['option'][$option[$v]['price_key']] = $option[$v];
                }
            }
        } else {
            unset($data['option']);
        }
        if ($data['is_sell'] == 2) {
            if ($data['sell_type'] == 1) {
                $info['group_attr'][] = $key;
            } elseif ($data['sell_type'] == 2) {
                $info['single_attr'][] = $key;
            } elseif ($data['sell_type'] == 3) {
                $info['input_attr'][] = $key;
            }
        }

        return $data;
    }

    private function getPrice(&$info, $other = false)
    {
        # 获取价格
        $where['info_id'] = $info['id'];
        $info['price_array'] = array();
        $list = Dever::db('goods/info_sku')->getData($where);

        $min = $max = array();
        if ($list) {
            foreach ($list as $k => $v) {
                if ($v['key']) {

                    if (Dever::config('base')->buy && Dever::config('base')->buy == 1) {
                        $v['price'] = $v['f_price'];
                    }

                    $v['name'] = array();
                    $temp = explode('_', $v['key']);
                    foreach ($temp as $k1 => $v1) {
                        if (isset($info['option'][$v1])) {
                            $v['name'][] = $info['option'][$v1]['name'];
                        }
                    }
                    $v['name'] = implode(',', $v['name']);

                    if ($other) {
                        foreach ($other[1] as $k1 => $v1) {
                            $v[$v1] = isset($other[0][$v['id']][$v1]) ? $other[0][$v['id']][$v1] : 0;
                        }
                    }
                    if ($v['type'] == 1) {
                        if (!$min) {
                            $min = $v;
                        }
                        if (!$max) {
                            $max = $v;
                        }

                        if ($min['price'] > $v['price']) {
                            $min = $v;
                        }

                        if ($max['price'] < $v['price']) {
                            $max = $v;
                        }
                    }

                    $info['price_array'][$v['key']] = $v;
                }
            }
        }
        $info['price_min'] = $min;
        $info['price_max'] = $max;

        if ($min) {
            $info['price'] = $min['price'];
            $info['s_price'] = $min['s_price'];
            $info['sku_id'] = $min['id'];
        }
        unset($info['option']);
    }

    public function getInfoLink($info)
    {
        if (isset($this->view_path)) {
            $info['view_path'] = $this->view_path . '?top=' . $info['top_category_id'] . '&id=' . $info['id'];
            $info['view_link'] = Dever::url($info['view_path']);
        }

        return $info;
    }

    public function setViewPath($path)
    {
        $this->view_path = $path;
    }

    # 根据分类获取商品
    public function getGoods_api()
    {
        $where['category_id'] = Dever::input('cate_id');
        $factory_id = Dever::input('id');

        $data = Dever::db('goods/info_category')->getData($where);

        return $data;
    }
}