<?php
namespace Api\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class DinnerController extends Controller
{
    /**
     * 我的宴席
     */
    public function myDinner()
    {
        $openid = $_GET['openid'];
        if (!$openid || $openid == "undefined" || $openid == "null") {
            $data = array("status" => -1, "msg" => "openid有误");
        } else {
            // 订单
            $list = M("dinner")
                ->where("`openid`='{$openid}'")
                ->field("`id`,`village_id`,`total_fee`,`pre_fee`,`end_fee`,`table_num`,`name`,`tel`,`address`,`dinner_time`,`status`,`dinner_sn`,`create_time`")
                ->order("`id` DESC")
                ->select();
            if (!$list) {
                $list = array();
            }
            // 待确认  待付款  进行中  已结束
            $notSured = $notPaid = $going = $finished = array();
            foreach ($list as $kl => $vl) {
                if ($vl['dinner_time'] > 0) {
                    $list[$kl]['dinner_time'] = date("n月j日", $vl['dinner_time']);
                }
                if ($vl['create_time'] > 0) {
                    $list[$kl]['create_time'] = date("Y-m-d H:i", $vl['create_time']);
                }
                // 村管理员电话
                $village_id = $vl['village_id'];
                $villager = M("users")->where("`village_id` AND `identity`=2")->find();
                $village_tel = $villager['mobile'];
                $list[$kl]['village_tel'] = $village_tel;
                // 已选套餐
                $dinner_id = $vl['id'];
                $row = M("dinnerDish")
                    ->join("dd LEFT JOIN `am_dish` d ON dd.`dish_id`=d.`id`")
                    ->where("dd.`dinner_id`={$dinner_id}")
                    ->field("d.`name`,dd.`id`")
                    ->find();
                $dish_name = $row['name'];    // 套餐名称
                $dinner_dish_id = $row['id'];    // 订单套餐副表ID
                if (!$dish_name) {
                    $dish_name = "";
                }
                $list[$kl]['dish_name'] = $dish_name;
                // 套餐食材
                $goods = M("dinnerDishGood")
                    ->join("ddg LEFT JOIN `am_goods` g ON ddg.`good_id`=g.`id`")
                    ->where("ddg.`dinner_dish_id`={$dinner_dish_id}")
                    ->field("g.`goods_name`,ddg.`goods_price`,ddg.`num`")
                    ->select();
                if (!$goods) {
                    $goods = array();
                }
                $goods_total = 0;    // 套餐食材总价
                foreach ($goods as $kg => $vg) {
                    $goods_price = $vg['goods_price'];
                    $num = $vg['num'];
                    $goods_total = strval($goods_total) + strval(strval($goods_price) * $num);
                }
                unset($kg, $vg);
                $list[$kl]['goods_count'] = count($goods);    // 套餐食材类数
                $list[$kl]['goods_total'] = $goods_total;    // 套餐食材总价
                $list[$kl]['goods'] = $goods;    // 套餐食材
                if ($vl['status'] == 1) {
                    // 待确认
                    array_push($notSured, $list[$kl]);
                } elseif ($vl['status'] == 2) {
                    // 待付款
                    array_push($notPaid, $list[$kl]);
                } elseif ($vl['status'] > 2 && $vl['status'] < 6) {
                    // 进行中
                    array_push($going, $list[$kl]);
                } elseif ($vl['status'] == 6) {
                    // 已结束
                    array_push($finished, $list[$kl]);
                }
            }
            unset($kl, $vl);
            $data = array(
                "status" => 1,
                "all" => $list,
                "notSured" => $notSured,
                "notPaid" => $notPaid,
                "going" => $going,
                "finished" => $finished
            );
        }
        apiReturn($data);
    }

    /**
     * 我的宴席》套餐列表
     */
    public function myDishes()
    {
        $dinner_id = $_GET['dinner_id'];    // 宴席订单ID
        if (!$dinner_id || $dinner_id == "undefined" || $dinner_id == "null" || !is_numeric($dinner_id)) {
            $data = array("status" => -1, "msg" => "宴席订单ID有误");
        } else {
            $list = M("dinnerDish")
                ->join("dd LEFT JOIN `am_dish` d ON dd.`dish_id`=d.`id`")
                ->where("dd.`dinner_id`={$dinner_id}")
                ->field("dd.`id`,dd.`price`,d.`name`,d.`thumb`,d.`describe`")
                ->select();
            foreach ($list as $key => $value) {
                $list[$key]['thumb'] = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/Uploads/" . str_replace("\"", "", $value['thumb']);
            }
            $data = array(
                "status" => 1,
                "result" => $list
            );
            // 查询是否有追加商品
            $count = M("dinnerDishGood")->where("`dinner_id`={$dinner_id} AND `dinner_dish_id`=0")->count();
            if ($count > 0) {
                $data['goodElse'] = true;
            } else {
                $data['goodElse'] = false;
            }
            // 查询是否有退货商品
            $count = M("dinnerGoodReturn")->where("`dinner_id`={$dinner_id}")->count();
            if ($count > 0) {
                $data['goodReturn'] = true;
            } else {
                $data['goodReturn'] = false;
            }
        }
        apiReturn($data);
    }

    /**
     * 预订下单
     */
    public function newDinner()
    {
        $openid = $_GET['openid'];
        $village_id = $_GET['village_id'];    // 村ID
        $total_fee = strval($_GET['total_fee']);    // 总价 & 套餐价
        $name = I('name');
        $tel = I('tel');
        $address = I('address');
        $form_id = $_GET['form_id'];
        $arrive_time = $_GET['arrive_time'];
        $dinner_time = I('dinner_time');
        $table_num = intval(I('table_num'));
        $dish_id = $_GET['dish_id'];
        $goods = json_decode($_GET['goods']);
        // 检查食材数组
        $flagGoods = true;
        $countGoods = 0;
        foreach ($goods as $kg => $vg) {
            if (!$vg->id || !$vg->price) {
                $flagGoods = false;
                break;
            }
            if ($vg->num) {
                $countGoods++;
            }
        }
        unset($kg, $vg);
        // 手机号码正则
        $pattern = "/^1[3|4|5|7|8][0-9]{9}$/";
        $matchMobile = preg_match($pattern, $tel);  //匹配正确返回 1,错误返回 0
        // 验证信息
        if (!$openid || $openid == "undefined" || $openid == "null") {
            $data = array("status" => -1, "msg" => "openid有误");
        } elseif (!$village_id || $village_id == "undefined" || $village_id == "null") {
            $data = array("status" => -1, "msg" => "村ID有误");
        } elseif (!$total_fee || $total_fee == "undefined" || $total_fee == "null" || !is_numeric($total_fee) || $total_fee <= 0) {
            $data = array("status" => -1, "msg" => "总价有误");
        } elseif (!$address || $address == "undefined" || $address == "null") {
            $data = array("status" => -1, "msg" => "宴会地点有误");
        } elseif (!$name || $name == "undefined" || $name == "null") {
            $data = array("status" => -1, "msg" => "联系人有误");
        } elseif (!$tel || $tel == "undefined" || $tel == "null" || !is_numeric($tel)) {
            $data = array("status" => -1, "msg" => "手机号码有误");
        } elseif ($matchMobile == 0) {
            $data = array("status" => -1, "msg" => "请填写正确手机号码");
        } elseif (!$form_id || $form_id == "undefined" || $form_id == "null") {
            $data = array("status" => -1, "msg" => "form_id有误");
        } elseif (!$arrive_time || $arrive_time == "undefined" || $arrive_time == "null") {
            $data = array("status" => -1, "msg" => "预计到达时间有误");
        } elseif (!$dinner_time || $dinner_time == "undefined" || $dinner_time == "null") {
            $data = array("status" => -1, "msg" => "预计尾款结算时间有误");
        } elseif (!$table_num || $table_num == "undefined" || $table_num == "null" || !is_numeric($table_num) || $table_num < 1) {
            $data = array("status" => -1, "msg" => "桌数有误");
        } elseif (!$dish_id || $dish_id == "undefined" || $dish_id == "null" || !is_numeric($dish_id)) {
            $data = array("status" => -1, "msg" => "套餐ID有误");
        } elseif (!$goods || $goods == "undefined" || $goods == "null" || !is_array($goods) || !$flagGoods) {
            $data = array("status" => -1, "msg" => "食材有误");
        } elseif (!$countGoods) {
            $data = array("status" => -1, "msg" => "食材数量为0");
        } else {
            // 用户uid
            $uid = M("users")->where("`openid`='{$openid}'")->getField("uid");
            // 订金比例、封顶金额
            $set = M("setDinner")->find();
            $percent = $set['earnest_percent'];
            $limit = strval($set['earnest_limit']);
            if (!$percent) {
                $percent = 10;
            }
            if (!$limit) {
                $limit = 10000;
            }
            $pre_fee = strval(strval($total_fee) * $percent / 100);
            if ($pre_fee > $limit) {
                $pre_fee = $limit;
            }
            // 创建宴席订单
            $addData = array(
                "openid" => $openid,
                "village_id" => $village_id,
                "dinner_sn" => "DN{$uid}" . date("YmdHis"),
                "total_fee" => $total_fee,
                "pre_fee" => $pre_fee,
                "end_fee" => $total_fee - $pre_fee,
                "name" => $name,
                "tel" => $tel,
                "address" => $address,
                "table_num" => $table_num,
                "form_id" => $form_id,
                "create_time" => $_SERVER['REQUEST_TIME'],
                "arrive_time" => $arrive_time,
                "dinner_time" => strtotime($dinner_time)
            );
            $dinner_id = M("dinner")->add($addData);
            // 创建套餐副表记录
            $addData = array(
                "dinner_id" => $dinner_id,
                "dish_id" => $dish_id,
                "price" => $total_fee
            );
            $dinner_dish_id = M("dinnerDish")->add($addData);
            foreach ($goods as $kg => $vg) {
                $good_id = $vg->id;    // 商品ID
                $num = $vg->num;    // 商品数量
                $price = $vg->price;    // 商品单价
                // 创建 材料商品副表
                $addData = array(
                    "dinner_id" => $dinner_id,    // 宴席订单ID
                    "dinner_dish_id" => $dinner_dish_id,    // 宴席套餐副表ID
                    "good_id" => $good_id,    // 商品ID
                    "num" => $num,
                    "goods_price" => $price
                );
                M("dinnerDishGood")->add($addData);
                // 支付定金后进行库存操作
            }
            unset($kg, $vg);
            $data = array("status" => 1, "msg" => "预订成功");
        }
        apiReturn($data);
    }

    /**
     * 我的宴席》套餐列表》套餐材料
     */
    public function myMaterial()
    {
        $dinner_dish_id = $_GET['dinner_dish_id'];    // 宴席订单套餐ID
        if (!$dinner_dish_id || $dinner_dish_id == "undefined" || $dinner_dish_id == "null") {
            $data = array("status" => -1, "msg" => "宴席订单套餐ID有误");
        } else {
            $list = M("dinnerDishGood")
                ->join("ddg LEFT JOIN `am_dish_good` dg ON ddg.`dish_good_id`=dg.`id`")
                ->join("LEFT JOIN `am_goods` g ON dg.`good_id`=g.`id`")
                ->where("`dinner_dish_id`={$dinner_dish_id}")
                ->field("ddg.`id`,ddg.`num`,ddg.`dish_good_id`,g.`goods_name` AS `name`,g.`thumb`,dg.`price`")
                ->select();
            // dump($list);die;
            foreach ($list as $key => $value) {
                $list[$key]['thumb'] = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/Uploads/" . $value['thumb'];
            }
            unset($key, $value);
            $data = array("status" => 1, "result" => $list);
        }
        apiReturn($data);
    }

    /**
     * 我的宴席》附加商品》商品列表
     */
    public function getElseGoods()
    {
        $dinner_id = $_GET['dinner_id'];    // 宴席订单套餐ID
        if (!$dinner_id || $dinner_id == "undefined" || $dinner_id == "null" || !is_numeric($dinner_id)) {
            $data = array("status" => -1, "msg" => "订单ID有误");
        } else {
            $list = M("dinnerDishGood")
                ->join("ddg LEFT JOIN `am_dish_good` dg ON ddg.`dish_good_id`=dg.`id`")
                ->join("LEFT JOIN `am_goods` g ON dg.`good_id`=g.`id`")
                ->where("`dinner_id`={$dinner_id} AND `dinner_dish_id`=0")
                ->field("ddg.`id`,ddg.`num`,ddg.`dish_good_id`,g.`goods_name` AS `name`,g.`thumb`,dg.`price`")
                ->select();
            foreach ($list as $key => $value) {
                $list[$key]['thumb'] = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/Uploads/" . $value['thumb'];
            }
            unset($key, $value);
            $data = array("status" => 1, "result" => $list);
        }
        apiReturn($data);
    }

    /**
     * 我的宴席》回收商品》商品列表
     */
    public function getReturnGoods()
    {
        $dinner_id = $_GET['dinner_id'];    // 宴席订单套餐ID
        if (!$dinner_id || $dinner_id == "undefined" || $dinner_id == "null" || !is_numeric($dinner_id)) {
            $data = array("status" => -1, "msg" => "订单ID有误");
        } else {
            $list = M("dinnerGoodReturn")
                ->join("ddg LEFT JOIN `am_dish_good` dg ON ddg.`dish_good_id`=dg.`id`")
                ->join("LEFT JOIN `am_goods` g ON dg.`good_id`=g.`id`")
                ->where("`dinner_id`={$dinner_id}")
                ->field("ddg.`id`,ddg.`num`,ddg.`dish_good_id`,g.`goods_name` AS `name`,g.`thumb`,dg.`price`")
                ->select();
            foreach ($list as $key => $value) {
                $list[$key]['thumb'] = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/Uploads/" . $value['thumb'];
            }
            unset($key, $value);
            $data = array("status" => 1, "result" => $list);
        }
        apiReturn($data);
    }

    /**
     * 用户增购商品
     */
    public function addGoods()
    {
        $dinner_id = $_GET['dinner_id'];    // 宴席订单ID
        $goods = json_decode($_GET['goods']);
        if (!$dinner_id || $dinner_id == "undefined" || $dinner_id == "null") {
            $data = array("status" => -1, "msg" => "宴席订单ID有误");
        } elseif (!$goods || !is_array($goods) || !$goods[0]) {
            $data = array("status" => -1, "msg" => "商品数组有误");
        } else {
            $pricePlus = 0;    // 加价数值初始化
            foreach ($goods as $key => $value) {
                $good_id = $value->id;    // 商品ID
                $num = $value->plus_num;    // 订单中商品的增加数量
                // 查询商品价格
                $goods_price = M("goods")->where("`id`={$good_id}")->getField("goods_price");
                if (!$goods_price) {
                    $goods_price = 0;
                }
                if ($num > 0) {
                    // 生成 追加订单
                    $addData = array(
                        "dinner_id" => $dinner_id,
                        "dinner_dish_id" => 0,
                        "goods_price" => $goods_price,
                        "good_id" => $good_id,
                        "num" => $num
                    );
                    $insert_id = M("dinnerDishGood")->add($addData);
                    if ($insert_id) {
                        // 库存操作
                        // 总仓库库存减少
                        M("goodsStorage")->where("`good_id`={$good_id} AND `village_id`=0")->lock()->setDec("storage", $num);
                        // 生成总仓库出库记录
                        $data = array(
                            "choice" => 1,
                            "type" => 3,
                            "order_id" => 0,
                            "dinner_id" => $dinner_id,
                            "good_id" => $good_id,
                            "change_num" => $num,
                            "create_time" => $_SERVER['REQUEST_TIME']
                        );
                        M("storageTotal")->add($data);
                        // 计算价格
                        if (!$goods_price) {
                            $goods_price = 0;
                        } else {
                            $goods_price = strval($goods_price);
                        }
                        // 加价数值累加
                        $pricePlus = strval($pricePlus) + strval(strval($num) * strval($goods_price));
                    }
                }
            }
            unset($key, $value);
            // 订单加价
            M("dinner")->where("`id`={$dinner_id}")->lock()->setInc("total_fee", $pricePlus);
            M("dinner")->where("`id`={$dinner_id}")->lock()->setInc("end_fee", $pricePlus);
            // 返回信息
            $data = array("status" => 1, "msg" => "操作成功");
        }
        apiReturn($data);
    }

    /**
     * 获取村管理员联系方式
     */
    public function villagerTel()
    {
        $village_id = $_GET['village_id'];
        if (!$village_id || $village_id == "undefined" || $village_id == "null" || !is_numeric($village_id)) {
            $data = array("status" => -1, "msg" => "村ID有误");
        } else {
            $row = M("users")->where("`village_id`={$village_id} AND `identity`=2")->find();
            $mobile = $row['mobile'];
            $data = array("status" => 1, "result" => $mobile);
        }
        apiReturn($data);
    }

    /**
     * 查看宴席预计到达时间
     */
    public function viewArriveTime()
    {
        $row = M("setDinner")->find();
        // 几天后到达
        $arrive_day = $row['arrive_day'];
        // 几点到达
        $arrive_clock = $row['arrive_clock'];
        $timeStampF = strtotime("+{$arrive_day} days");
        $result = mktime($arrive_clock, 0, 0, date("m", $timeStampF), date("d", $timeStampF), date("Y", $timeStampF)) * 1000;
        $current = time()*1000;
        $now = mktime(0, 0, 0, date("m"), date("d"), date("Y")) * 1000;
        apiReturn(array(
            "time" => $result,
            "current" => $current,
            "now" => $now,
            "minusOneDay" => $result - (24 * 60 * 60) * 1000
        ));
    }
}