<?php

namespace Shop\Lib;

use Dever;

class Info
{
    # 获取城市
    public function getCity()
    {
        $city = Dever::db('shop/info')->getCity();

        $result = array();
        if ($city) {
            foreach ($city as $k => $v) {
                $c = Dever::db('area/city')->find($v['city']);
                if ($c) {
                    $result[] = array
                    (
                        'id' => $v['city'],
                        'name' => $c['name'],
                    );
                }
            }
        }

        return $result;
    }

    # 获取店铺基本信息
    public function getOne($shop_id, $lng, $lat)
    {
        $shop = $this->fetch($shop_id, false, $lng, $lat, false);

        return $shop;
    }

    # 获取店铺基本信息
    public function get($city, $lng, $lat, $name = '', $method = 'fetch', $shop_id = false, $address = false)
    {
        if (!$city) {
            //Dever::alert('请传入城市');
        }

        if ((!$lng || !$lat) && $address) {
            list($lng, $lat) = Dever::load('shop/lib/info')->geo($city, $address);
        }

        if (!$lng || !$lat) {
            $city_info = Dever::db('area/city')->find($city);
            list($lng, $lat) = Dever::load('shop/lib/info')->geo($city, $city_info['name']);
            if (!$lng || !$lat) {
                Dever::alert('请传入用户坐标');
            }
        }

        $data = array();
        if ($city) {
            $data = $this->fetch(false, $city, $lng, $lat, 1, $name, $method);
        }
        
        $type = Dever::input('type', 1);
        if (!$data) {
            Dever::setInput('km', 2);
            if ($type == 1) {
                # 获取平台店
                $data = $this->fetch(false, $city, $lng, $lat, 10, $name, $method);
                if ($data && $method == 'fetch') {
                    # 提示是否进入平台
                    $data['alert'] = 2;
                }
                
            } elseif ($type == 2) {
                # 获取城市外的其他店
                $data = $this->fetch(false, false, $lng, $lat, 1, $name, $method);
                if ($data && $method == 'fetch') {
                    # 提示是否进入所有最近店铺
                    $data['alert'] = 4;
                }
            } elseif ($type == 3) {
                # 获取城市内的其他店
                $data = $this->fetch(false, $city, $lng, $lat, 1, $name, $method);

                if (!$data) {
                    # 获取平台店
                    $data = $this->fetch(false, $city, $lng, $lat, 10, $name, $method);
                    if ($data && $method == 'fetch') {
                        # 提示是否进入平台
                        $data['alert'] = 2;
                    }
                } elseif ($method == 'fetch') {
                    # 提示是否进入城市内最近店铺
                    $data['alert'] = 3;
                }
            }
        } elseif ($method == 'fetch') {
            # 是否提示 1不提示
            $data['alert'] = 1;
        }

        if ($data) {
            if ($method == 'fetch') {
                $data = $this->getInfo($data);
            } else {
                foreach ($data as $k => $v) {
                    $data[$k] = $this->getInfo($data[$k]);
                    if ($shop_id == $v['id']) {
                        $data[$k]['cur'] = 1;
                    } else {
                        $data[$k]['cur'] = 2;
                    }
                }
            }
        }

        return $data;
    }

    # 获取店铺的商品列表
    public function getGoods($shop, $column = false, $price_type = false, $sell_type = false, $status = false, $uid = -1)
    {
        $table = 'shop/goods';
        $where['shop_id'] = isset($shop['id']) ? $shop['id'] : $shop;
        if ($column) {
            $where['column'] = $column;
            $method = 'getData';
            $where['status'] = 1;
        } else {
            $method = 'getDataPage';
        }

        if ($status) {
            $where['status'] = 1;
        }
        
        $name = Dever::input('name');
        if ($name) {
            $where['name'] = $name;
        }

        if ($price_type) {
            $where['price_type'] = $price_type;
        }

        if ($sell_type) {
            $where['sell_type'] = $sell_type;
        }

        $where['state'] = 1;
        $where['state_1'] = 1;
        
        $data = Dever::db($table)->$method($where);

        $result_1 = array();
        $result_2 = array();
        if ($data) {
            foreach ($data as $k => $v) {
                $d = $this->getGoodsInfo($where['shop_id'], $v, false, true, true, $uid);
                if ($d) {
                    if ($d['total'] <= 0) {
                        $result_2[] = $d;
                    } else {
                        $result_1[] = $d;
                    }
                }
            }

            $data = array_merge($result_1, $result_2);
        }

        return $data;
    }

    # 获取店铺的商品SKU列表
    public function getGoodsSku($shop, $page = true)
    {
        $table = 'shop/goods_sku';
        $where['shop_id'] = isset($shop['id']) ? $shop['id'] : $shop;
        if ($page) {
            $method = 'getDataPage';
        } else {
            $method = 'getAllData';
        }
        
        $name = Dever::input('name');
        if ($name) {
            $where['name'] = $name;
        }
        $total = Dever::input('total');
        if ($total) {
            $where['total'] = $total;
        }
        //$where['status'] = 1;
        $where['state'] = 1;
        $where['state_1'] = 1;
        $data = Dever::db($table)->$method($where);

        $result = array();
        if ($data) {
            foreach ($data as $k => $v) {
                $data[$k] = Dever::load('goods/lib/info')->getPayInfo($v, $v['sku_id']);
                if (!isset($result[$v['id']])) {
                    $result[$v['id']] = $v;
                }
                if (isset($data[$k]['attr']) && $data[$k]['attr']) {
                    $result[$v['id']]['price_array'][] = array
                    (
                        'name' => $data[$k]['sku_name'],
                        'total' => $data[$k]['total'] <= 0 ? 0 : $data[$k]['total'],
                        'price' => $data[$k]['price'],
                        's_price' => $data[$k]['s_price'],
                    );
                }
                
            }
        }

        return $result;
    }

    # 获取详细信息
    private function getInfo($data)
    {
        if ($data) {
            if ($data['worktime']) {
                $time = date('Hi');
                $worktime = str_replace(':', '', $data['worktime']);
                $temp = explode('~', $worktime);
                if (isset($temp[0]) && isset($temp[1]) && ($time < $temp[0] || $time > $temp[1])) {
                    $data['open'] = 2;
                }
            }

            $data['gotime'] = $data['worktime'];
        }

        return $data;
    }

    # 获取距离
    public function fetch($id, $city, $lng, $lat, $type = 1, $name = '', $method = 'fetch')
    {
        $page = array();
        if ($method == 'fetchAll') {
            $page['template'] = 'list';
            $page['num'] = 10;
        } else {
            $page = false;
        }

        $where = 'status = 1 and state = 1';

        if ($type == 1) {
            $where .= ' and type in (1,2)';
        } elseif ($type) {
            $where .= ' and type = ' . $type;
        }

        if ($city) {
            $county = Dever::db('area/county')->find($city);
            if ($county) {
                $city = $county['city_id'];
            }
            if ($type < 10 && $city) {
                $where .= ' and city = ' . $city;
            }
        }
        
        if ($name) {
            $where .= ' and name like("%'.$name.'%")';
        }
        if ($id) {
            $where .= ' and id = ' . $id;
        }

        if ($type < 10) {
            $shop_method = Dever::input('method');
            if ($shop_method == 1) {
                $where .= ' and method in(1,3)';
            } elseif ($shop_method == 2) {
                $where .= ' and method in(2,3)';
            }
        }
        
        if ($lng && $lat) {
            $col = Dever::db('shop/info')->config['config_col'];
            $km = Dever::input('km');
            $distance = 'round((st_distance(point(lng, lat), point('.$lng.', '.$lat.'))*111195)/1000, 2)';
            if ($km && $km == 1 && $type < 10) {
                # 验证公里数
                $config = Dever::db('main/manage_config')->find();
                if ($config && $config['km'] > 0) {
                    $where .= ' and '.$distance.' <= ' . $config['km'];
                }
            }
            $sql = 'select '.$col.','.$distance.' as distance from {table} where '.$where.' order by distance asc';

            $data = Dever::db('shop/info')->$method($sql, array(), $page);
        } else {
            $data = Dever::db('shop/info')->getOne($id);
        }

        if ($data && isset($data['city']) && $data['city']) {
            $city = Dever::db('area/city')->one($data['city']);
            $data['city_name'] = $city['name'];
        }

        return $data;
    }

    # 获取库存
    public function getGoodsInfo($shop_id, $info, $sku_id = false, $attr = true, $check = true, $uid = -1)
    {
        $where['shop_id'] = $shop_id;
        $where['goods_id'] = isset($info['goods_id']) ? $info['goods_id'] : $info;
        if ($sku_id) {
            $where['sku_id'] = $sku_id;
        }
        
        $total = 1;
        $other = Dever::db('shop/goods_sku')->getData($where);
        if (!$other && $check) {
            if ($check == -1) {
                $total = 2;
            } else {
                return false;
            }
        }
        $other_array = array('total', 'min', 'price_id');
        if (Dever::config('base')->buy && Dever::config('base')->buy == 1) {
            # 购买不需要读取goods_sku的min
            $other_array = array('total', 'price_id');
        }
        
        $data = Dever::load('goods/lib/info')->getInfo($info, $attr, array($other, $other_array));

        if($data) {
            
            if (Dever::config('base')->buy && Dever::config('base')->buy == 1) {

            } else {
                $goods_sku = Dever::db('shop/goods_sku')->find($where);
                if ($goods_sku && isset($goods_sku['min'])) {
                    $data['min'] = $goods_sku['min'];
                }
            }
            
            $sku_id = $sku_id ? $sku_id : $data['sku_id'];
            $data['total'] = 0;
            if ($data['price_type'] == 4) {
                if (isset($data['goods']) && is_array($data['goods'])) {
                    foreach ($data['goods'] as $k => $v) {
                        $where = array();
                        $where['shop_id'] = $shop_id;
                        $where['goods_id'] = $v['id'];
                        $gother = Dever::db('shop/goods_sku')->getData($where);
                        $data['goods'][$k]['total'] = $this->getTotal($gother, -1);

                        if ($data['total'] == 0) {
                            $data['total'] = $data['goods'][$k]['total'];
                        }
                        if ($data['total'] > $data['goods'][$k]['total']) {
                            $data['total'] = $data['goods'][$k]['total'];
                        }
                    }
                }
            } else {
                $data['total'] = $this->getTotal($other, $sku_id);
            }

            if ($total == 2) {
                $data['total'] = 0;
            }

            if ($data['min'] && floor($data['min']) == $data['min']) {
                $data['min'] = intval($data['min']);
            }

            # 根据角色计算折扣
            $data['discount'] = (object) array();
            if ($uid && $uid > 0) {
                $role = $this->getRole($uid);
                if ($role) {
                    $role_state = false;
                    $discount_goods = Dever::db('act/discount_goods')->getData(array('discount_id' => $role['id']));
                    if ($discount_goods) {
                        $discount_goods = array_keys($discount_goods);
                        if (in_array($data['id'], $discount_goods)) {
                            $role_state = true;
                        }
                    } elseif ($role['category'] && in_array($data['top_category_id'], $role['category'])) {
                        $role_state = true;
                    }
                    if ($role_state) {
                        $data['discount'] = $role;
                    }
                }
            }
        }

        return $data;
    }

    # 获取角色
    public function getRole($uid)
    {
        $bind = Dever::db('agent/user_bind')->find(array('uid' => $uid, 'status' => 2));
        if ($bind) {
            $discount = Dever::db('act/discount')->find(array('role' => 1));
            return $discount;
        }
        return false;
    }

    # 验证库存
    public function checkTotal(&$num, $goods_id, $shop_id, $sku_id, $state = 1)
    {
        $info = $this->getGoodsInfo($shop_id, $goods_id, $sku_id, false);
        if (!$info) {
            if ($state == 2) {
                Dever::alert('商品不存在');
            } else {
                return false;
            }
        }
        $total = $info['total'];
        $min = $info['min'];

        # 增加最小起购量
        if ($state < 3 && $min > 0 && $num < $min) {
            $num = $min;
        }
        if ($num > $total) {
            if ($state == 2) {
                Dever::alert('库存不足');
            }
            $num = $total;
        }

        return $total;
    }

    # 获取库存
    public function getTotal($other, $sku_id)
    {
        if (isset($other[$sku_id])) {
            return $other[$sku_id]['total'];
        } else {
            return 0;
        }
    }

    # 获取经纬度
    public function geo($code, $name)
    {
        # 获取经纬度
        $url = 'https://restapi.amap.com/v3/geocode/geo';
        $param['key'] = 'f18cb42560b8aa54e3b53a6265bfd764';
        //$param['city'] = $code;
        $param['address'] = $name;
        $result = json_decode(Dever::curl($url, $param), true);
        $lng = 0;
        $lat = 0;
        $map = '';
        if (isset($result['geocodes'][0]['location']) && $result['geocodes'][0]['location']) {
            $map = $code . ',' . $result['geocodes'][0]['location'] . ',11';
            $temp = explode(',', $result['geocodes'][0]['location']);
            $lng = $temp[0];
            $lat = $temp[1];
        }

        return array($lng, $lat, $map);
    }

    # 根据经纬度获取地址
    public function address($lng, $lat)
    {
        $url = 'http://restapi.amap.com/v3/geocode/regeo';
        $param['key'] = 'f18cb42560b8aa54e3b53a6265bfd764';
        $param['location'] = $lng . ',' . $lat;
        $param['radius'] = 2800;
        $result = json_decode(Dever::curl($url, $param), true);

        $address = '';
        if (isset($result['regeocode']['formatted_address'])) {
            $address = $result['regeocode']['formatted_address'];
        }

        return $address;
    }
}