<?php
namespace Smi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class ApiCityUserOrderController extends Controller{
	/**
	 * 城市用户订单
	 */

	//获取用户所有订单
	public function getUserOrderAll(){
		$openid = $_GET['openid'];//小程序openid
		if(!$openid || $openid == "undefined" || $openid == "null"){
			$result = array("status" => -1,"msg" => "小程序openid有误");
		}else{
			$users = M("users")->where(array("openid"=>$openid))->find();
	        if($users){
	            $order = M("order_city as o")
	            		->field("o.id,o.order_sn,o.total_fee,o.create_time,o.expect_time,o.status,o.store_id,a.store_photo")
	                    ->join('am_stores as a on a.id = o.store_id')
	                    ->where(array("o.openid" => $users["openid"]))
	                    ->order("o.id desc")
	                    ->select();
	            if($order){             
	                foreach ($order as $key => &$value) {
	                    $good_id = M("order_city_good")->where(array("order_id" => $value['id']))->select();
	                    foreach ($good_id as $k => $va) {
	                        $good_name = M("stores_goods")->where(array("id" => $va['good_id']))->field("goods_name")->find();
	                        $good_names= $good_name['goods_name'];
	                        $good_nums += $va['num']; //订单商品数目
	                    }
	                    $value['store_photo'] = 'http://'.$_SERVER['HTTP_HOST'].'/am_shop/Uploads/'.$value['store_photo'];
	                    $value['expect_time'] = date("Y-m-d H:i:s",$value['expect_time']);
	                    $value['create_time'] = date("Y-m-d H:i:s",$value['create_time']);               
	                    $value['goods_name']  = $good_names."等".$good_nums."件商品";
	                    $good_names = "";
	                    $good_nums  = "";
	                    $value['store_name'] = M("stores")->where("`id`={$value['store_id']}")->getField("name");
	                }
	                $result = $order; 
	            }else{
	                $result = array("status" => -1,"msg" => "此小程序openid没有订单");
	            }
	        }else{
	            $result = array("status" => -1,"msg" => "小程序openid有误users表无此openid");
	        }
		}
		apiReturn($result);
	}
	//获取用户订单详情
	public function getUserOrderDetail(){
		$id = $_GET['id'];
		if(!$id || $id == "undefined" || $id == "null"){
			$data = array("status" => -1,"msg" => "小程序openid有误");
		}else{
			$order = M("order_city")->where(array("id" => $id))->select();
	        if($order){
	            foreach ($order as $key => &$value) {
	                $value['expect_time'] = date("Y-m-d H:i:s",$value['expect_time']);
	                $value['create_time'] = date("Y-m-d H:i:s",$value['create_time']);
	                $value['finish_time'] = date("Y-m-d H:i:s",$value['finish_time']);
	            } 
	            $users    = M("users")->where(array("openid" => $order[0]['openid']))->find();
	            $store = M("stores")->where(array("id" => $order[0]['store_id']))->find();
	            // dump($storetel);die;
	            $name     = $users['name'];
	            $nickname = $users['nickname'];
	            $storetel = $store['mobile'];
	            // dump($_SERVER);die;
	            $store_photo = 'https://'.$_SERVER['HTTP_HOST'].'/am_shop/Uploads/'.$store['store_photo'];
	            $goods    = M("order_city_good")->where(array("order_id" => $order[0]['id']))->select();
	            foreach ($goods as $k => &$va) {
	                $good_name = M("stores_goods")->where(array("id" => $va['good_id']))->find();
	                $va['goods_name'] = $good_name['goods_name'];
	                $va['goods_price']= $good_name['goods_price'];
	                $va['goods_img']  = $good_name['thumb'];
	            }
	            $order = array("name" => $name,"nickname" => $nickname,"storetel" => $storetel,"order" => $order[0],"goods" => $goods,'store_photo'=>$store_photo);
	            $data = $order;          
	        }else{
	            $data = array("status" => -1,"msg" => "订单id有误");
	        }
		}
        apiReturn($data);
	}
	//用户处理订单status=3完成status=-1取消
	public function setUserOrderStatus(){
		$id             = $_GET['id'];//订单id
        $save['status'] = $_GET['status']; //订单状态
        $save['reason'] = $_GET['reason']; //取消理由
        if(!$id || $id == "undefined" || $id == "null"){
        	$data = array("status" => -1,"msg" => "订单id有误");
        }elseif (!$save['status'] || $save['status'] == "undefined" || $save['status'] == "null") {
        	$data = array("status" => -1,"msg" => "订单状态有误");
        }elseif ($save['status'] == -1) {
        	if(!$save['reason'] || $save['reason'] == "undefined" || $save['reason'] == "null"){
        		$data = array("status" => -1,"msg" => "请填写取消理由");
        	}else{
        		$status = M("order_city")->where(array("id"=>$id))->find();
        		if($status['status'] == 2){
        			$data = array("status" => -1,"msg" => "送货中，不可取消");
        		}else{
        			$result = M("order_city")->where(array("id"=>$id))->save($save);
	        		if($result){
	        			$data = array("status" => 1,"msg" => "订单已取消");

	        			$order_qx = M("order_city")->where(array("id"=>$id))->find();
		                $store_openid = M("stores")->where(array("id"=>$order_qx['store_id']))->find();
		                // 发送模板消息  这里需要修正 模板ID，在配置文件修改 APPID & APP_SERECT ！！！
		                vendor("WxPayPubHelperMp.WxPlugin");
		                $WxPlugin = new \WxPlugin();
		                $openid = $store_openid['openid'];
		                $template_id = "ceOx4A6iRPYWCor1Zkd_7pXN3ijgKOr-jb-reM5ZOU4";
		                $url = "http://" . $_SERVER['HTTP_HOST'] . U("Wechat/Store/storeOrder");
		                $datas = array(
		                    'first'    => array('value' => urlencode('订单已被用户取消'.'\r\n'), 'color' => "#000000"),
		                    'keyword1' => array('value' => urlencode($order_qx['order_sn']), 'color' => '#000000'),
		                    'keyword2' => array('value' => urlencode(date("Y-m-d H:i:s",time())), 'color' => '#f35900'),
		                    'keyword3' => array('value' => urlencode($order_qx['reason']), 'color' => '#000000'),
		                    'remark'   => array('value' => urlencode('\r\n'.'该订单已被用户取消，请知悉！'), 'color' => '#000000')
		                );
		                $res = $WxPlugin->doSend($openid, $template_id, $url, $datas);
		                if ($res['status'] == -1) {
		                    file_put_contents("./Logs/auditSuccess.log", JSON($res), FILE_APPEND);
		                }

	        		}else{
	        			$data = array("status" => -1,"msg" => "订单取消失败");
	        		}
        		}
        	}
        }elseif ($save['status'] ==  3) {
        	$save['finish_time'] = time();
        	$result = M("order_city")->where(array("id"=>$id))->save($save);
    		if($result){
    			$data = array("status" => 1,"msg" => "订单已完成");
    		}else{
    			$data = array("status" => -1,"msg" => "订单完成失败");
    		}
        }else{
        	$data = array("status" => -1,"msg" => "请发送正确订单状态");
        }
		apiReturn($data);
	}
}