<?php
namespace Api\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class GroupManageController extends Controller
{
    /**
     * 配送订单 列表
     */
    public function orderList()
    {
        $openid = $_GET['openid'];    // 组管理员 (当前用户) openid
        if (!$openid || $openid == "undefined" || $openid == "null") {
            $data = array("status" => -1, "msg" => "组长openid有误");
        } else {
            // 获取数据刷新时间, 没有则定为 21:00
            $limitTime = D("Smi/SetElse")->getLimitTime();
            $order = "o.`id` DESC";
            $where = "o.`group_openid`='{$openid}' AND o.`status` > 1 AND o.`status` < 5 AND o.`create_time` < {$limitTime}";
            // $where = "o.`group_openid`='{$openid}' AND o.`status` > 1 AND o.`status` < 5";
            $list = M("order")
                ->join("o LEFT JOIN `am_users` u ON o.`group_openid`=u.`openid`")
                ->where($where)
                ->field("o.`id`,o.`order_sn` AS `sn`,o.`status`,o.`create_time`,u.`name` AS `group`")
                ->order($order)
                ->select();
            if (!$list) {
                $list = array();
            }
            foreach ($list as $ko => $vo) {
                if ($vo['create_time'] > 0) {
                    $list[$ko]['create_time'] = date("Y-m-d H:i", $vo['create_time']);
                }
                $order_id = $vo['id'];
                // 查询分订单
                $result = M("orderSmi")
                    ->join("os LEFT JOIN `am_users` u ON os.`dispatcher`=u.`openid`")
                    ->where("`order_id`={$order_id}")
                    ->field("os.`id`,os.`smi_sn` AS `sn`,u.`name` AS `dispatcher`")
                    ->select();
                if (!$result) {
                    $result = array();
                }
                $list[$ko]['branch'] = $result;
            }
            unset($ko, $vo);
            $data = array("status" => 1, "result" => $list);
        }
        apiReturn($data);
    }

    /**
     * 配送订单 确认送达
     */
    public function orderArrive()
    {
        $id = $_GET['id'];    // 分订单ID
        if (!$id || $id == "undefined" || $id == "null") {
            $data = array("status" => -1, "msg" => "分订单ID有误");
        } else {
            // 修改分订单状态
            $saveData = array(
                "status" => 4,
                "get_time" => $_SERVER['REQUEST_TIME']
            );
            $result = M("orderSmi")->where("`id`={$id}")->save($saveData);
            if (!$result) {
                $data = array("status" => -1, "msg" => "系统繁忙");
            } else {
                $row = M("orderSmi")->where("`id`={$id}")->find();
                $form_id_create = $row['form_id_create'];    // form_id
                $order_id = $row['order_id'];
                $order_sn = $row['order_sn'];
                $openid = $row['openid'];
                $group_openid = $row['group_openid'];
                $grouperInfo = M("users")->where("`openid`='{$group_openid}'")->find();
                $grouperName = $grouperInfo['name'];
                $grouperTel = $grouperInfo['tel'];
                $grouperAddress = $grouperInfo['address'];
                // 发送模板消息
                vendor("WxPayPubHelper.WxPlugin");
                $WxPlugin = new \WxPlugin();
                $params['form_id'] = $form_id_create;
                $params['touser'] = $openid;
                $params['template_id'] = "Sse96UtkKyu6q326k-g5zv5Ep1NUuaRJU7XYtljFNJ8";
                $params['data'] = array(
                    "keyword1" => array("value" => $order_sn, "color" => "#000000"),
                    "keyword2" => array("value" => $grouperTel, "color" => "#000000"),
                    "keyword3" => array("value" => $grouperAddress, "color" => "#000000"),
                    "keyword4" => array("value" => "您的订单已送至组管理员处，请尽快领取。", "color" => "#000000")
                );
                $result = $WxPlugin->XcxSend($params);
                if (!$result) {
                    file_put_contents("./Logs/templateMsg/orderArrive.log", JSON($result), FILE_APPEND);
                }
                // 发送结束
                $flag = true;    // 升起旗帜，若所属订单有未送达组长处的分订单 则降下
                $orderSmiList = M("orderSmi")->where("`order_id`={$order_id}")->select();
                foreach ($orderSmiList as $kos => $vos) {
                    $status = $vos['status'];
                    if ($status < 4) {
                        // 该分订单未送达，降旗并退出循环
                        $flag = false;
                        break;
                    }
                }
                unset($kos, $vos);
                if ($flag) {
                    // 旗帜挺立，所属订单下的所有分订单已完成送达，修改所属订单状态
                    M("order")->where("`id`={$order_id}")->setField("status", 4);
                }
                $data = array(
                    "status" => 1,
                    "msg" => "操作成功"
                );
            }
        }
        apiReturn($data);
    }

    /**
     * 配送订单 详情
     */
    public function orderInfo()
    {
        $id = $_GET['id'];    // am_order 表 的ID
        if (!$id || $id == "undefined" || $id == "null") {
            $data = array("status" => -1, "msg" => "订单ID有误");
        } else {
            $resource = M("order")
                ->join("o LEFT JOIN `am_order_smi` os ON o.`id`=os.`order_id`")
                ->join("LEFT JOIN `am_users` u ON os.`dispatcher`=u.`openid`")
                ->join("LEFT JOIN `am_order_good` og ON os.`id`=og.`smi_id`")
                ->join("LEFT JOIN `am_goods` g ON og.`good_id`=g.`id`")
                ->where("o.`id`={$id}")
                ->field("o.`order_sn` AS `sn`,o.`create_time`,os.`id`,os.`smi_sn`,os.`status`,u.`name` AS `dispatcher`,og.`smi_id`,og.`good_id`,og.`num`,g.`thumb`,g.`goods_name` AS `name`")
                ->select();
            if ($resource[0]['sn']) {
                // 订单编号
                $sn = $resource[0]['sn'];
            }
            if ($resource[0]['create_time']) {
                // 订单编号
                $create_time = $resource[0]['create_time'];
            }
            $goodList = array();
            $branchList = array();
            foreach ($resource as $kr => $vr) {
                $resource[$kr]['thumb'] = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/Uploads/" . $vr['thumb'];
                // 组装 商品数组
                array_push($goodList, array(
                    "good_id" => $resource[$kr]['good_id'],
                    "thumb" => $resource[$kr]['thumb'],
                    "name" => $resource[$kr]['name'],
                    "num" => $resource[$kr]['num'],
                    "smi_id" => $resource[$kr]['smi_id']
                ));
                // 组装 分订单数组
                $arr = array(
                    "id" => $resource[$kr]['id'],
                    "sn" => $resource[$kr]['smi_sn'],    // 分订单编号
                    "status" => $resource[$kr]['status'],
                    "dispatcher" => $resource[$kr]['dispatcher']
                );
                if (!in_array($arr, $branchList)) {
                    array_push($branchList, $arr);
                }
            }
            unset($kr, $vr);
            // 分订单数组 吸收 商品数组
            foreach ($branchList as $kb => $vb) {
                $branchList[$kb]['goods'] = array();
                $id = $vb['id'];
                foreach ($goodList as $kg => $vg) {
                    $smi_id = $vg['smi_id'];
                    if ($smi_id == $id) {
                        array_push($branchList[$kb]['goods'], array(
                            "good_id" => $vg['good_id'],
                            "thumb" => $vg['thumb'],
                            "name" => $vg['name'],
                            "num" => $vg['num']
                        ));
                    }
                }
                unset($kg, $vg);
            }
            unset($kb, $vb);
            // 订单信息
            $order = M("order")->where("`id`={$id}")->find();
            // 组管理员
            $group = M("users")->where("`openid`='{$order['group_openid']}'")->getField("name");
            $data = array(
                "status" => 1,
                "result" => array(
                    "sn" => $sn,
                    "name" => $order['name'],
                    "tel" => $order['tel'],
                    "address" => $order['address'],
                    "group" => $group,
                    "create_time" => date("Y年m月d日 H:i", $create_time),
                    "branch" => $branchList
                )
            );
        }
        apiReturn($data);
    }

    /**
     * 查看本组宴席订单
     */
    public function dinnerList()
    {
        $village_id = $_GET['village_id'];    // 村ID
        $openid = $_GET['openid'];    // 当前用户openid
        if (!$village_id || $village_id == "undefined" || $village_id == "null" || !is_numeric($village_id)) {
            $data = array("status" => -1, "msg" => "村ID有误");
        } elseif (!$openid || $openid == "undefined" || $openid == "null") {
            $data = array("status" => -1, "msg" => "用户openid有误");
        } else {
            // 村长宴席佣金比例
            $villageSet = M("regionVillage")->where("`id`={$village_id}")->find();
            $is_self = $villageSet['is_self'];
            if ($is_self == 2) {
                // 用村设置的比例计算佣金
                $group_percent = $villageSet['group_percent'];
            } elseif ($is_self == 1) {
                // 用后台设置的比例计算佣金
                $set = M("setFund")->find();
                $group_percent = $set['group_percent'];
            }
            $list = M("dinner")
                ->where("`group_openid`='{$openid}'")
                ->field("`id`,`dinner_sn`,`total_fee`,`status`,`create_time`,`dinner_time`")
                ->order("`id` DESC")
                ->select();
            if (!$list) {
                $list = array();
            }
            foreach ($list as $key => $value) {
                $list[$key]['yongjin'] = number_format($value['total_fee'] * $group_percent / 100, 2, ".", "");
                if ($value['create_time']) {
                    $list[$key]['create_time'] = date("Y-m-d", $value['create_time']);
                }
                if ($value['dinner_time']) {
                    $list[$key]['dinner_time'] = date("Y-m-d", $value['dinner_time']);
                }
                $dinner_id = $value['id'];
                // 已选套餐
                if ($dinner_id) {
                    $row = M("dinnerDish")
                        ->join("dd LEFT JOIN `am_dish` d ON dd.`dish_id`=d.`id`")
                        ->where("`dinner_id`={$dinner_id}")
                        ->field("d.`name`")
                        ->find();
                    $dish_name = $row['name'];
                    if (!$dish_name) {
                        $dish_name = "";
                    }
                    $list[$key]['dish_name'] = $dish_name;
                }
            }
            unset($key, $value);
            $data = array(
                "status" => 1,
                "all" => $list
            );
        }
        apiReturn($data);
    }

    /**
     * 查看厨师的宴席订单
     */
    public function cookeDinnerList()
    {
        $village_id = $_GET['village_id'];    // 村ID
        $openid = $_GET['openid'];    // 当前用户openid
        if (!$village_id || $village_id == "undefined" || $village_id == "null" || !is_numeric($village_id)) {
            $data = array("status" => -1, "msg" => "村ID有误");
        } elseif (!$openid || $openid == "undefined" || $openid == "null") {
            $data = array("status" => -1, "msg" => "用户openid有误");
        } else {
            // 村长宴席佣金比例
            $villageSet = M("regionVillage")->where("`id`={$village_id}")->find();
            $is_self = $villageSet['is_self'];
            if ($is_self == 2) {
                // 用村设置的比例计算佣金
                $cook_percent = $villageSet['cook_percent'];
            } elseif ($is_self == 1) {
                // 用后台设置的比例计算佣金
                $set = M("setFund")->find();
                $cook_percent = $set['cook_percent'];
            }
            $list = M("dinner")
                ->where("`cook_openid`='{$openid}'")
                ->field("`id`,`dinner_sn`,`total_fee`,`status`,`create_time`,`dinner_time`")
                ->order("`id` DESC")
                ->select();
            if (!$list) {
                $list = array();
            }
            foreach ($list as $key => $value) {
                $list[$key]['yongjin'] = number_format($value['total_fee'] * $cook_percent / 100, 2, ".", "");
                if ($value['create_time']) {
                    $list[$key]['create_time'] = date("Y-m-d", $value['create_time']);
                }
                if ($value['dinner_time']) {
                    $list[$key]['dinner_time'] = date("Y-m-d", $value['dinner_time']);
                }
                $dinner_id = $value['id'];
                // 已选套餐
                if ($dinner_id) {
                    $row = M("dinnerDish")
                        ->join("dd LEFT JOIN `am_dish` d ON dd.`dish_id`=d.`id`")
                        ->where("`dinner_id`={$dinner_id}")
                        ->field("d.`name`")
                        ->find();
                    $dish_name = $row['name'];
                    if (!$dish_name) {
                        $dish_name = "";
                    }
                    $list[$key]['dish_name'] = $dish_name;
                }
            }
            unset($key, $value);
            $data = array(
                "status" => 1,
                "all" => $list
            );
        }
        apiReturn($data);
    }
}