<?php
namespace Api\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class GoodsController extends Controller
{

    /**
     * 自定义信息
     */
    public function get_info()
    {
        $business_id = I('get.business_id');

        $data = [
                    0 => [
                        'pageName' => '商店',
                        'deliveryName' => '运费',
                        'packageName' => '包装费',
                        'tipsName' => '小区内购买或快递配送',
                        'roomNum' => '房号',
                        'btnName' => ['小区内购买','快递配送'],
                        'showPersonNum' => false,
                        'locationName' => '门牌号'
                    ],

                    1 => [
                        'pageName' => '菜单',
                        'deliveryName' => '配送费',
                        'packageName' => '餐盒费',
                        'tipsName' => '店内就餐或外卖',
                        'roomNum' => '座位号',
                        'btnName' => ['店内就餐','外卖下单'],
                        'showPersonNum' => true,
                        'locationName' => '座位号'
                    ]
                ];

        if ($business_id == 38) {// bingo
            apiReturn($data[0]);
        } else {
            apiReturn($data[1]);
        }
    }

    /**
     * 商品列表接口
     */
    public function goods_list()
    {
        $data = I('post.');
        if (!isset($data['business_id']) || empty($data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);

        $this->business_status($data['business_id']);//查询商户状态

        $cat_list = $this->get_cat_list($data['business_id']);

        if (!$cat_list) apiReturn(['status' => -1, 'msg' => '该商户下没有商品分类']);

        $list = array();
        foreach ($cat_list as $key => $item) {
            $goods_list = $this->get_goods_list($data['business_id'], $item['id']);

            foreach ($goods_list as $k => $vo) {
                $goods_list[$k]['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$vo['img'];
                $goods_list[$k]['sales'] = $vo['sales']+$vo['false_sell'];
                $list[$key][$item['title']][] = $goods_list[$k];
            }

            if (empty($list[$key][$item['title']])) $list[$key][$item['title']] = [];
        } 

        $info['status'] = 1;
        $info['msg'] = '已获取数据';
        $info['data'] = $list;

        $this -> ajaxReturn($info);
        // return apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $list]);
    }

    /**
     * 获取商家信息接口
     */
    public function get_business_info()
    {
        $admin_id = I('post.business_id');
        if (empty($admin_id)) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);

        $this->business_status($admin_id);//查询商户状态

        $info = M('admin')->where('id = '.$admin_id.' AND is_business <> 2')->field('id as business_id, username, picture, picture_environment, business_name, business_des, business_phone, business_address, is_on_waimai, delivery, up_to_send, boxes, service_time')->limit(1)->select();

        if (empty($info)) {
            apiReturn(['status' => -1, 'msg' => '商户信息不存在']);
        }
        $info[0]['picture'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$info[0]['picture'];
        $info[0]['picture_environment'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$info[0]['picture_environment'];
        apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $info[0]]);
    }

    /**
     * 获取用户当天购买商品的数量
     */
    public function get_user_goods_num()
    {
        $data = I('post.');
        if (empty($data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);
        if (empty($data['users_id'])) apiReturn(['status' => -1, 'msg' => '用户id不能为空']);
        if (empty($data['goods_id'])) apiReturn(['status' => -1, 'msg' => '商品id不能为空']);

        $this->business_status($data['business_id']);//查询商户状态

        $where = '';
        $where .= 'admin_id = '.$data['business_id'].' AND ';
        $where .= 'users_id = '.$data['users_id'].' AND ';
        $where .= 'create_time > '.strtotime(date('Y-m-d')).' AND ';
        $where .= 'create_time < '.strtotime(date('Y-m-d', strtotime('+1days')));
        $result = M('car')->where($where)->select();

        if (empty($result)) {
            apiReturn(['status' => 1, 'msg' => '今天还没有购买商品，可以购买', 'buy_num' => 0]);
        } else {
            $goods_num = 0;
            foreach ($result as $value) {
                $car_content = unserialize($value['car_content']);
                foreach ($car_content as $vo) {
                    if ($vo['goods_id'] == $data['goods_id']) {
                        $goods_num += $vo['goods_num'];
                        break;
                    }
                }
            }
        }
        $max_buy = M('goods')->where(array('id' => $data['goods_id']))->getField('max_buy');// 最大购买数量
        if ($goods_num < $max_buy) {
            apiReturn(['status' => 1, 'msg' => '用户购买商品未超过限制，可以购买', 'buy_num' => $goods_num]);
        } else {
            apiReturn(['status' => -1, 'msg' => '已超过数量限制，禁止购买']);
        }
    }

     /**
     * 获取商品分类列表
     */
    private function get_cat_list($business_id = '')
    {
        $cat_list = M('goods_cat')->where(array('admin_id' => $business_id))->select();

        if (empty($cat_list)) {
            return false;
        } else {
            return $cat_list;
        }
    }

    /**
     * 获取商品分类下商品信息
     */
    private function get_goods_list($business_id = '', $cat_id1 = '')
    {
        $goods_list = M('goods')->where(array('admin_id' => $business_id, 'cat_id1' => $cat_id1, 'status' => 1))->getField('id, title, price, img, sales,max_buy,false_sell,content');

        if (empty($goods_list)) {
            return false;
        } else {
            return $goods_list;
        }
    }

    /**
     * 查询商户状态
     */
    private function business_status($business_id = '')
    {
//        $result = M('admin')->where(array('id' => $business_id, 'is_business' => 1))->field('status')->select();
        $result = M('admin')->where('id = '.$business_id.' AND is_business <> 2')->field('status')->select();
        // dump($result);die;
        // echo M()->getLastSql();die;
        if (empty($result)) {
            apiReturn(['status' => -1, 'msg' => '该商户不存在']);
        } elseif ($result[0]['status'] == -1) {
            apiReturn(['status' => -1, 'msg' => '该商户已被禁用']);
        }
    }

    //获得招商信息
    public function InvestmentInformation(){
    	$adminId = I('post.business_id');
    	$data = M('Admin') -> field('investment_information') -> find($adminId);
    	$data['investment_information'] = str_replace('/ueditor','https://'.$_SERVER['HTTP_HOST'].'/ueditor',$data['investment_information']);
        $data['investment_information'] = htmlspecialchars_decode($data['investment_information']);
    	apiReturn($data);
    }

    //获得商户地址信息
    public function BusinessAddress(){
    	$adminId = I('post.business_id');
    	$data = M('Admin') -> field('lnglat') -> find($adminId);
    	apiReturn($data);
    }
}