<?php
namespace Api\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class OrderController extends Controller
{
    /**
     * 查询商品价格
     */
    public function get_goods_price()
    {
        $ids = I('post.ids');

        $ids = html_entity_decode($ids);
        $ids = stripslashes($ids);
        $ids = json_decode($ids, true);
        if (empty($ids)) apiReturn(['status' => -1, 'msg' => 'id不能为空']);
        $where = 'id = ';
        foreach($ids as $id) {
            $where .= $id.' OR id = ';
        }
        $where = rtrim($where, ' OR id = ');
        $info = M('goods')->where($where)->field('id as goods_id, title, price, img')->select();
        foreach ($info as &$value) {
            $value['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$value['img'];
        }

        if (empty($info)) {
            apiReturn(['status' => -1, 'msg' => '没有数据']);
        } else {
            apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $info]);
        }
    }

    /**
     * 生成订单
     */
    public function create_order()
    {
        $data = I('post.');
        // dump($data);die;
        $this->check_param($data);
        if (empty($data['order_type'])) apiReturn(['status' => -1, 'msg' => 'order_type不能为空']);

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

        $data['car_content'] = html_entity_decode($data['car_content']);
        $data['car_content'] = stripslashes($data['car_content']);
        $data['car_content'] = json_decode($data['car_content'], true);

        $sum_price = 0;// 订单总价
        foreach ($data['car_content'] as $value) {
            $sum_price += $value['sum_price'];
        }

         $int = 0;// 积分初始值
        // 获取会员设置
        $member_config = M('member_config')->where(array('admin_id' => $data['business_id']))->find();
        if (empty($member_config)) {
            M('member_config')->add(array('admin_id' => $data['business_id'], 'create_time' => time()));
            $member_config = M('member_config')->where(array('admin_id' => $data['business_id']))->find();
        }
        $int_rate = $member_config['int_rate'];// 积分比例
        $int_rate = split(':', $int_rate);

        $data['order_sn'] = str_replace(' ', '', str_replace(':', '', str_replace('-', '', date('Y-m-d H:i:s').rand(100000, 999999))));// 生成订单编号
        $business_info = M('admin')->where(array('id' => $data['business_id']))->field('delivery, boxes, business_name, is_on_waimai, up_to_send')->limit(1)->select()[0];// 商户信息
        
        if ($data['order_type'] == 1) {// 外卖
            if ($business_info['is_on_waimai'] == 2) apiReturn(['status' => -1, 'msg' => '商家不支持外卖']);
            if (($sum_price + $business_info['boxes']) < $business_info['up_to_send']) apiReturn(['status' => -1, 'msg' => '金额没有满起送费，不能下单']);
            if ($car_id = $this->add_car($data)) {
                $add_data = [
                    'delivery'       =>  $business_info['delivery'],
                    'fachu_time'     =>  $data['fachu_time'],
                    'address_name'   =>  $data['address_name'],
                    'address_phone'  =>  $data['address_phone'],
                    'address_area'   =>  $data['address_area'],
                    'address_info'   =>  $data['address_info'],
                    'mark'           =>  $data['mark'],
                    'order_type'     =>  $data['order_type'],
                    'create_time'    =>  time(),
                    'status'         =>  1,
                    'order_sn'       =>  $data['order_sn'],
                    'uid'            =>  $data['users_id'],
                    'admin_id'       =>  $data['business_id'],
                    'car_id'         =>  $car_id,
                    'price'          =>  $sum_price + $business_info['delivery'] + $business_info['boxes'],
                    'total_price'    =>  $sum_price + $business_info['delivery'] + $business_info['boxes'],
                    'admin_title'    =>  $business_info['business_name'],
                    'boxes'          =>  $business_info['boxes'],
                    'meals_num'      =>  isset($data['meals_num']) ? $data['meals_num'] : 1, // 默认1人
                ];
                $add_data['int'] = intval($add_data['price'] * ($int_rate[1] / $int_rate[0]));// 积分

                if ($order_id = M('order')->add($add_data)) {
                    $add_data['order_id'] = $order_id;
                    $add_data['business_id'] = $add_data['admin_id'];
                    unset($add_data['admin_id']);
                    unset($add_data['car_id']);
                    $add_data['order_name'] = $add_data['admin_title'];
                    unset($add_data['admin_title']);
                    $add_data['car_content'] = $data['car_content'];
                    // $this->api = new ApiController();
                    // $this->api->payMoney($data['order_sn']);

                    foreach ($add_data['car_content'] as &$vo) {
                        $vo['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$this->get_goods_info($vo['goods_id'])['img'];
                    }

                    apiReturn(['status' => 1, 'msg' => '生成订单成功', 'data' => $add_data]);
                } else {
                    M('car')->delete($car_id);
                    apiReturn(['status' => -1, 'msg' => '生成订单失败']);
                }
            } else {
                apiReturn(['status' => 1, 'msg' => '生成订单失败']);
            }
            
        } elseif ($data['order_type'] == 2) {// 店内
            if (empty($data['seat'])) apiReturn(['status' => -1, 'msg' => '请输入桌位号']);
            if ($car_id = $this->add_car($data)) {
                $add_data = [
                    'delivery'       =>  $business_info['delivery'],
                    'mark'           =>  $data['mark'],
                    'order_type'     =>  $data['order_type'],
                    'create_time'    =>  time(),
                    'status'         =>  1,
                    'order_sn'       =>  $data['order_sn'],
                    'uid'            =>  $data['users_id'],
                    'admin_id'       =>  $data['business_id'],
                    'car_id'         =>  $car_id,
                    'price'          =>  $sum_price,
                    'total_price'    =>  $sum_price,
                    'admin_title'    =>  $business_info['business_name'],
                    'boxes'          =>  $business_info['boxes'],
                    'meals_num'      =>  isset($data['meals_num']) ? $data['meals_num'] : 1, // 默认1人
                    'seat'           =>  $data['seat'],
                ];
                $add_data['int'] = intval($add_data['price'] * ($int_rate[1] / $int_rate[0]));// 积分

                if ($order_id = M('order')->add($add_data)) {
                    $add_data['order_id'] = $order_id;
                    $add_data['business_id'] = $add_data['admin_id'];
                    unset($add_data['admin_id']);
                    unset($add_data['car_id']);
                    $add_data['order_name'] = $add_data['admin_title'];
                    unset($add_data['admin_title']);
                    $add_data['car_content'] = $data['car_content'];
                    // $this->api = new ApiController();
                    // $this->api->payMoney($data['order_sn']);

                    foreach ($add_data['car_content'] as &$vo) {
                        $vo['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$this->get_goods_info($vo['goods_id'])['img'];
                    }

                   apiReturn(['status' => 1, 'msg' => '生成订单成功', 'data' => $add_data]);
                } else {
                    M('car')->delete($car_id);
                    apiReturn(['status' => -1, 'msg' => '生成订单失败']);
                }
            } else {
                apiReturn(['status' => 1, 'msg' => '生成订单失败']);
            }
        } else {
            apiReturn(['status' => -1, 'msg' => 'order_type参数错误']);
        }
    }

    /**
     * 获取订单列表
     */
    public function get_order_list()
    {
        $data = I('post.');
        $this->check_param($data);
        if (empty($data['page'])) apiReturn(['status' => -1, 'msg' => 'page参数必须']);

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

        $order_list = M('order')
        ->join('am_car ON am_car.id = am_order.car_id')
        ->where(array('am_order.admin_id' => $data['business_id'], 'am_order.uid' => $data['users_id']))
        ->field('am_order.order_sn, delivery, boxes, price, seat, status, order_type, mark, am_order.create_time, pay_time, fachu_time, address_name, address_phone, address_area, address_info, am_car.car_content, meals_num')
        ->order('am_order.create_time DESC')
        ->page($data['page'].', 5')
        ->select();
        if (empty($order_list)) {
            apiReturn(['status' => -1, 'msg' => '没有数据']);
        } else {
            foreach ($order_list as $key => &$value) {
                $value['car_content'] = unserialize($value['car_content']);
                foreach ($value['car_content'] as $k => &$v) {
                    $v['title'] = M('goods')->where(array('id' => $v['goods_id']))->getField('title');
                    $v['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$this->get_goods_info($v['goods_id'])['img'];
                }
            }
        }
        apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $order_list]);
    }

    /**
     * 查询桌位号
     */
    public function get_seats()
    {    
        $business_id = I('post.business_id');
        if (empty($business_id)) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);

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

        $list = M('table')->where(array('admin_id' => $business_id))->field('id, name, pid')->select();

        // $layer = M('table')->where(array('admin_id' => $business_id, 'pid' => 0))->field('id, name, pid')->select();
        // $table = M('table')->where(array('admin_id' => $business_id, 'pid' => array('gt', 0)))->field('id, name, pid')->select();

        // $arr = array();
        // foreach ($layer as $key => $value) {
        //     foreach ($table as $k => $v) {
        //         if ($v['pid'] != 0 && $v['pid'] == $value['id']) {
        //             // $arr[$value['name']][] = $v['name'];
        //             $arr[$value['name']][] = ['id' => $v['id'], 'name' => $v['name']];
        //         }
        //     }
        // }
        if (empty($list)) {
            apiReturn(['status' => -1, 'msg' => '没有数据']);
        } else {
            apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' =>  $this->class2($list)]);
            // apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' =>  $arr]);
        }
    }

    /**
     * 查询订单信息
     */
    public function get_order_info()
    {   
        $order_sn = I('post.order_sn');
        if (empty($order_sn)) apiReturn(['status' => -1, 'msg' => '订单编号不能为空']);

        $info = M('order')
            ->join('am_car ON am_order.car_id = am_car.id')
            ->field('am_order.order_sn, delivery, boxes, price, seat, status, order_type, mark, am_order.create_time, pay_time, fachu_time, address_name, address_phone, address_area, address_info, meals_num, am_car.car_content')
            ->where(array('am_order.order_sn' => $order_sn))
            ->find();

        if (empty($info)) apiReturn(['status' => -1, 'msg' => '订单不存在']);

        $info['car_content'] = unserialize($info['car_content']);
        foreach ($info['car_content'] as $k => &$v) {
            $v['title'] = M('goods')->where(array('id' => $v['goods_id']))->getField('title');
            $v['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$this->get_goods_info($v['goods_id'])['img'];
        }

        apiReturn(['status' => 1, 'msg' => '已获取订单数据', 'data' => $info]);
    }

    /**
     * 提交预约订单
     */
    public function create_app_order()
    {
        $data = I('post.');

        if (empty($data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);
        if (empty($data['time'])) apiReturn(['status' => -1, 'msg' => '日期不能为空']);
        if (empty($data['time_interval'])) apiReturn(['status' => -1, 'msg' => '用餐时段不能为空']);
        if (empty($data['nums'])) apiReturn(['status' => -1, 'msg' => '用餐人数不能为空']);
        if (empty($data['name'])) apiReturn(['status' => -1, 'msg' => '联系人不能为空']);
        if (empty($data['mobile'])) apiReturn(['status' => -1, 'msg' => '联系方式不能为空']);
        if (empty($data['table_id'])) apiReturn(['status' => -1, 'msg' => '桌位号id不能为空']);
        if (empty($data['user_id'])) apiReturn(['status' => -1, 'msg' => '用户id参数不能为空']);
        // if (empty($data['app_status'])) apiReturn(['status' => -1, 'msg' => '是否需要定金参数不能为空']);

        $add = array(
                'admin_id' => $data['business_id'],
                'time' => $data['time'],
                'time_interval' => $data['time_interval'],
                'nums' => $data['nums'],
                'table_id' => $data['table_id'],
                'name' => $data['name'],
                'mobile' => $data['mobile'],
                'status' => 1,
                // 'app_status' => $data['app_status'],
                'create_time' => time(),
                'user_id' => $data['user_id']
            );

        // if ($data['app_status'] == 1) {
        //     if (empty($data['money'])) apiReturn(['status' => -1, 'msg' => '定金不能为空']);

        //     $add['money'] = $data['money'];
        // }

        $result = M('appointment')->add($add);

        if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => '提交成功']);
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => '提交失败']);
        }
    }

    /**
     * 获取预约订单列表
     */
    public function get_app_list()
    {
        $data = I('post.');

        if (empty($data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);
        if (empty($data['user_id'])) apiReturn(['status' => -1, 'msg' => '用户id不能为空']);
        // if (empty($data['page'])) apiReturn(['status' => -1, 'msg' => '分页参数不能为空']);

        $list = M('appointment')->field('time, time_interval, nums, name, mobile, status, table_id, create_time')->where(array('admin_id' => $data['business_id'], 'user_id' => $data['user_id']))->select();
        if (empty($list)) apiReturn(['status' => -1, 'msg' => '没有数据']);

        foreach ($list as $key => &$value) {
                $value['table'] = '';
                $table_info = M('table t')
                            ->join('LEFT JOIN am_table tp ON tp.id = t.pid')
                            ->where(array('t.id' => $value['table_id']))
                            ->field('t.name, tp.name pname')
                            ->find();
                            
                $value['table'] = $table_info['pname'].' '.$table_info['name'];
                unset($list[$k]['table_id']);
                $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            }

        apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $list]);
    }

    /**
     * 确认预约订单
     */
    public function sure_o()
    {
        $data = I('post.');

        if (empty($data['id'])) {
            $this->ajaxReturn(['status' => -1, 'msg' => 'id不能为空']);die;
        }

        $result = M('appointment')->where(array('id' => $data['id']))->setField('status', 2);

        if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => '确认成功']);
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => '确认失败']);
        }
    }

    // public function get_app_config()
    // {
    //     $data = I('post.');

    //     if (empty($data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);

    //     $info = M('appointment_config')->where(array('admin_id' => $data['business_id']))->find();

    //     if (empty($info)) {
    //         M('appointment_config')->add(array('admin_id' => $data['business_id'], 'create_time' => time()));
    //          $info = M('appointment_config')->where(array('admin_id' => $data['business_id']))->find();
    //     }

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

    private function class2($array = array())
    {
        if (!is_array($array)) return false;
        $arr = array();
        foreach ($array as $key => $value) {
            if ($value['pid'] == 0) {
                foreach ($array as $k => $v) {
                    if ($v['pid'] != 0 && $v['pid'] == $value['id']) {
                        $arr[$value['name']][] = $v['name'];
                        // $arr[$value['name']][] = ['id' => $v['id'], 'name' => $v['name']];
                    }
                }
            }
        }
        return $arr;
    }

    /**
     * 获取商品信息
     */
    private function get_goods_info($id = '')
    {
        $info = M('goods')->where(array('id' => $id))->field('img')->find();
        return $info;
    }

    /**
     * 添加购物车信息
     */
    private function add_car($data = '')
    {
        // $data = I('post.');
        // $this->check_param($data);
        if (empty($data['car_content'])) apiReturn(['status' => -1, 'msg' => '购物车信息不能为空']);

        $temp = array();
        foreach ($data['car_content'] as $key => $vo) {
            $vo['price'] = $vo['sum_price'] / $vo['goods_num'];
            $temp[] = $vo;
        }
        $data['car_content'] = $temp;
        $data['car_content'] = serialize($data['car_content']);
        $data['admin_id'] = $data['business_id'];
        unset($data['business_id']);
        $data['create_time'] = time();

        if ($insert_id = M('car')->add($data)) {
           return $insert_id;
        } else {
            return false;
        }
    }

    /**
     * 检查参数
     */
    private function check_param($data = '')
    {
        if (empty($data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);
        if (empty($data['users_id'])) apiReturn(['status' => -1, 'msg' => '用户id不能为空']); 
    }

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