<?php
namespace Smi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class DinnerController extends BaseController
{
    /**
     * 宴席定金比例
     */
    public function dinnerSet()
    {
        auth_check("dish_opt");
        if (IS_POST) {
            $result = D("SetDinner")->saveForm(I());
            if ($result) {
                alertMsg("修改成功", U("dinnerSet"));
            } else {
                $this->redirect("dinnerSet");die;
            }
        } else {
            $info = M("setDinner")->find();
            $this->assign("info", $info);
        }
        $this->display("dinnerSet");die;
    }

    /**
     * 套餐列表
     */
    public function dishList()
    {
        auth_check("dish_read");
        $where = "1";
        $order = "d.`id` DESC";
        $l = 10;//确定每页记录数
        if ($_GET['search']) {
            $search = I("search");
            $where .= " AND v.`name` LIKE '%{$search}%'";
            $this->assign("search", $search);
        }
        $count = M("dish")
            ->join("d LEFT JOIN `am_region_village` v ON d.`village_id`=v.`id`")
            ->join("`am_region_county` co ON v.`county_id`=co.`id`")
            ->join("`am_region_city` ci ON co.`city_id`=ci.`id`")
            ->join("`am_region_province` p ON ci.`province_id`=p.`id`")
            ->where($where)
            ->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("dish")
            ->join("d LEFT JOIN `am_region_village` v ON d.`village_id`=v.`id`")
            ->join("`am_region_county` co ON v.`county_id`=co.`id`")
            ->join("`am_region_city` ci ON co.`city_id`=ci.`id`")
            ->join("`am_region_province` p ON ci.`province_id`=p.`id`")
            ->field("d.*,v.`name` AS `village`,co.`name` AS `county`,ci.`name` AS `city`,p.`name` AS `province`")
            ->where($where)
            ->order($order)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        foreach ($list as $key => $value) {
            $list[$key]['thumb'] = str_replace("\"", "", $value['thumb']);
        }
        unset($key, $value);
        $this->assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this->assign("list", $list);
        $this->display("dishList");die;
    }

    /**
     * 套餐详情
     */
    public function dishDetail()
    {
        auth_check("dish_read");
        $id = $_GET['id'];
        $info = M("dish")
            ->join("d LEFT JOIN `am_region_village` v ON d.`village_id`=v.`id`")
            ->join("`am_region_county` co ON v.`county_id`=co.`id`")
            ->join("`am_region_city` ci ON co.`city_id`=ci.`id`")
            ->join("`am_region_province` p ON ci.`province_id`=p.`id`")
            ->field("d.*,v.`name` AS `village`,co.`name` AS `county`,ci.`name` AS `city`,p.`name` AS `province`")
            ->where("d.`id`={$id}")
            ->find();
        $info['thumb'] = str_replace("\"", "", $info['thumb']);
        $this->assign("info", $info);
        // 获取套餐材料
        $list = M("dishGood")
            ->join("dg LEFT JOIN `am_goods` g ON dg.`good_id`=g.`id`")
            ->where("dg.`dish_id`={$id}")
            ->field("dg.`good_id`,g.`goods_price` AS `price`,dg.`num`,g.`goods_name`,g.`thumb`")
            ->select();
        $this->assign("list", $list);
        // 总价
        $totalPrice = 0;
        foreach ($list as $key => $value) {
            $totalPrice += strval(strval($value['num']) * strval($value['price']));
        }
        unset($key, $value);
        $totalPrice = strval($totalPrice);
        $this->assign("totalPrice", $totalPrice);
        $this->display("dishDetail");die;
    }

    /**
     * 删除套餐
     */
    public function dishsDel()
    {
        auth_check("dish_opt");
        $id = $_GET['id'];
        $thumb = M("dish")->where("`id`={$id}")->getField("thumb");
        $result = M("dish")->where("`id`={$id}")->delete();
        if ($result) {
            @unlink("./Uploads/{$thumb}");
            M("dishGood")->where("`dish_id`={$id}")->delete();
        }
        $this->redirect("dishList");die;
    }

    /**
     * 宴席订单 列表
     */
    public function orderList()
    {
        auth_check("dish_read");
        $where = "1";
        $order = "d.`id` DESC";
        $l = 10;//确定每页记录数
        // if ($_GET['search']) {
        //     $search = I("search");
        //     $where .= " AND v.`name` LIKE '%{$search}%'";
        //     $this->assign("search", $search);
        // }
        $count = M("dinner")
            ->join("d LEFT JOIN `am_region_village` v ON d.`village_id`=v.`id`")
            ->where($where)
            ->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("dinner")
            ->join("d LEFT JOIN `am_region_village` v ON d.`village_id`=v.`id`")
            ->join("`am_region_county` co ON v.`county_id`=co.`id`")
            ->join("`am_region_city` ci ON co.`city_id`=ci.`id`")
            ->join("`am_region_province` p ON ci.`province_id`=p.`id`")
            ->field("d.*,v.`name` AS `village`,co.`name` AS `county`,ci.`name` AS `city`,p.`name` AS `province`")
            ->where($where)
            ->order($order)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this->assign("list", $list);
        $this->display("orderList");die;
    }

    /**
     * 确认收回退货
     */
    public function orderGoodBack()
    {
        auth_check("dish_opt");
        $id = $_GET['id'];    // 宴席订单ID
        $data = array(
            "status" => 5
        );
        $result = M("dinner")->where("`id`={$id}")->save($data);
        if ($result) {
            alertMsg("操作成功！", U("orderList"));
        } else {
            $this->redirect("orderList");die;
        }
    }

    /**
     * 确认完成
     */
    public function orderFinish()
    {
        auth_check("dish_opt");
        $id = $_GET['id'];    // 宴席订单ID
        $data = array(
            "status" => 6,
            "finish_time" => $_SERVER['REQUEST_TIME']
        );
        $result = M("dinner")->where("`id`={$id}")->save($data);
        if ($result) {
            // 计算佣金
            $row = M("dinner")->where("`id`={$id}")->find();
            $total_fee = $row['total_fee'];    // 订单总价
            $group_openid = $row['group_openid'];    // 组管理员openid
            $cook_openid = $row['cook_openid'];    // 厨师openid
            $village_id = $row['village_id'];    // 村ID
            // 村管理员openid
            $villager = M("users")->where("`village_id`={$village_id} AND `identity`=2")->find();
            $village_openid = $villager['openid'];
            $villageSet = M("regionVillage")->where("`id`={$village_id}")->find();
            $is_self = $villageSet['is_self'];
            if ($is_self == 2) {
                // 用村设置的比例计算佣金
                $village_percent = $villageSet['village_percent'];
                $group_percent = $villageSet['group_percent'];
                $cook_percent = $villageSet['cook_percent'];
            } elseif ($is_self == 1) {
                // 用后台设置的比例计算佣金
                $set = M("setFund")->find();
                $village_percent = $set['village_percent'];
                $group_percent = $set['group_percent'];
                $cook_percent = $set['cook_percent'];
            }
            // 村管理员佣金
            $data = array(
                "type" => 2,
                "target" => 1,
                "openid" => $village_openid,
                "benefit" => $total_fee * $village_percent / 100,
                "order_id" => 0,
                "dinner_id" => $id,
                "good_id" => 0,
                "create_time" => $_SERVER['REQUEST_TIME']
            );
            M("fundLog")->add($data);
            // 组管理员佣金
            $data = array(
                "type" => 2,
                "target" => 2,
                "openid" => $group_openid,
                "benefit" => $total_fee * $group_percent / 100,
                "order_id" => 0,
                "dinner_id" => $id,
                "good_id" => 0,
                "create_time" => $_SERVER['REQUEST_TIME']
            );
            M("fundLog")->add($data);
            // 厨师佣金
            $data = array(
                "type" => 2,
                "target" => 3,
                "openid" => $cook_openid,
                "benefit" => $total_fee * $cook_percent / 100,
                "order_id" => 0,
                "dinner_id" => $id,
                "good_id" => 0,
                "create_time" => $_SERVER['REQUEST_TIME']
            );
            M("fundLog")->add($data);
            // 退货 & 加货 在加退货操作时修改库存 不在这里修改
            alertMsg("操作成功！", U("orderList"));
        } else {
            $this->redirect("orderList");die;
        }
    }

    /**
     * 宴席订单详情
     */
    public function orderDetail()
    {
        auth_check("dish_read");
        // {$_GET['id']} 为订单ID
        $info = M("dinner")
            ->join("d LEFT JOIN `am_region_village` v ON d.`village_id`=v.`id`")
            ->join("LEFT JOIN `am_region_county` co ON v.`county_id`=co.`id`")
            ->join("LEFT JOIN `am_region_city` ci ON co.`city_id`=ci.`id`")
            ->join("LEFT JOIN `am_region_province` p ON ci.`province_id`=p.`id`")
            ->join("LEFT JOIN `am_users` grouper ON d.`group_openid`=grouper.`openid`")
            ->join("LEFT JOIN `am_users` cook ON d.`cook_openid`=cook.`openid`")
            ->field("d.*,v.`name` AS `village`,co.`name` AS `county`,ci.`name` AS `city`,p.`name` AS `province`,grouper.`name` AS `group_name`,grouper.`mobile` AS `group_mobile`,cook.`name` AS `cook_name`,cook.`mobile` AS `cook_mobile`")
            ->where("d.`id`={$_GET['id']}")
            ->find();
        // 定义变量并显示模板
        $this->assign("info", $info);
        // 读取套餐
        $dishes = M("dinnerDish")
            ->join("dd LEFT JOIN `am_dish` d ON dd.`dish_id`=d.`id`")
            ->where("dd.`dinner_id`={$_GET['id']}")
            ->field("d.`thumb`,d.`name`,dd.`id`")
            ->select();
        foreach ($dishes as $key => $value) {
            $dishes[$key]['thumb'] = str_replace("\"", "", $value['thumb']);
            // 读取商品
            $goods = M("dinnerDishGood")
                ->join("ddg LEFT JOIN `am_goods` g ON ddg.`good_id`=g.`id`")
                ->where("ddg.`dinner_dish_id`={$value['id']}")
                ->field("ddg.`num`,ddg.`goods_price`,g.`thumb`,g.`id`,g.`goods_name`")
                ->select();
            $dishes[$key]['goods'] = $goods;
        }
        $this->assign("dishes", $dishes);
        // 读取增购商品
        $else = M("dinnerDishGood")
            ->join("ddg LEFT JOIN `am_goods` g ON ddg.`good_id`=g.`id`")
            ->where("ddg.`dinner_id`={$_GET['id']} AND `dinner_dish_id`=0")
            ->field("ddg.`num`,ddg.`goods_price`,g.`thumb`,g.`id`,g.`goods_name`")
            ->select();
        // 循环原食材数组
        $elseGoods = array();
        foreach ($else as $ke => $ve) {
            // 循环输出的数组，有商品ID相同的元素则加数组数量，没有则插入到输出的数组中
            $flag = false;
            foreach ($elseGoods as $kpg => $veg) {
                if ($veg['id'] == $ve['id']) {
                    // 输出数组中存在同一商品
                    $elseGoods[$kpg]['num'] += $ve['num'];
                    $flag = true;
                }
            }
            unset($kpg, $kpg);
            if (!$flag) {
                array_push($elseGoods, $ve);
            }
        }
        unset($ke, $ve);
        $this->assign("elseGoods", $elseGoods);
        // 读取退余货商品
        $return = M("dinnerGoodReturn")
            ->join("dgr LEFT JOIN `am_goods` g ON dgr.`good_id`=g.`id`")
            ->where("dgr.`dinner_id`={$_GET['id']}")
            ->field("dgr.`num`,dgr.`goods_price`,g.`thumb`,g.`goods_name`")
            ->select();
        // 循环原食材数组
        $returnGoods = array();
        foreach ($return as $kr => $vr) {
            // 循环输出的数组，有商品ID相同的元素则加数组数量，没有则插入到输出的数组中
            $flag = false;
            foreach ($returnGoods as $krg => $vrg) {
                if ($vrg['id'] == $vr['id']) {
                    // 输出数组中存在同一商品
                    $returnGoods[$krg]['num'] += $vr['num'];
                    $flag = true;
                }
            }
            unset($krg, $kpg);
            if (!$flag) {
                array_push($returnGoods, $vr);
            }
        }
        unset($kr, $vr);
        $this->assign("returnGoods", $returnGoods);
        $this->display("orderDetail");die;
    }

    /**
     * 删除宴席订单
     */
    public function orderDel()
    {
        auth_check("dish_opt");
        $id = $_GET['id'];
        $result = M("dinner")->where("`id`={$id}")->delete();
        if ($result) {
            M("dinnerDish")->where("`dinner_id`={$id}")->delete();
            M("dinnerDishGood")->where("`dinner_id`={$id}")->delete();
            M("dinnerGoodReturn")->where("`dinner_id`={$id}")->delete();
        }
        $this->redirect("orderList");die;
    }
}