<?php
namespace Smi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class ApiCityOnOrderController extends Controller{
	/**
	 * 城市用户购买
	 */
	//获取商品价格
	public function getGoodsPrice(){
		$id = $_GET['id'];//商品ID
		if($this->dataCheck($id)){
			$result = array("status" => -1,"msg" => "商品id有误");
		}else{
			$price  = M("stores_goods")->where(array("id"=>$id))->find();
			if($price){
				$result = array("status" =>  1,"id" => $price['id'],"goods_price" => $price['goods_price']);
			}else{
				$result = array("status" => -1,"msg" => "没有这个id的商品");
			}
		}
		apiReturn($result);
	}
	public function tete(){
		dump(htmlspecialchars_decode('[{&quot;good_id&quot;:1,&quot;num&quot;:4},{&quot;good_id&quot;:38,&quot;num&quot;:2},{&quot;good_id&quot;:13,&quot;num&quot;:1}]'));
		dump((unserialize('a:9:{s:6:"openid";s:28:"oLrUa0WsHYv9KCEF3XREwdcnl8PU";s:8:"store_id";s:1:"1";s:9:"total_fee";s:8:"42883.00";s:4:"name";s:3:"asd";s:6:"mobile";s:2:"sd";s:7:"address";s:2:"sd";s:11:"expect_time";s:5:"12:00";s:5:"goods";s:129:"[{&quot;good_id&quot;:1,&quot;num&quot;:4},{&quot;good_id&quot;:38,&quot;num&quot;:2},{&quot;good_id&quot;:13,&quot;num&quot;:1}]";s:7:"form_id";s:24:"the formId is a mock one";}')));die;
	}
	//城市用户确认下单
	public function confirmOrder(){
		//file_put_contents('loggggg.log',serialize(I()));die;
		$data['openid']      = $_GET['openid'];
		$data['store_id']    = $_GET['store_id'];
		$data['total_fee']   = $_GET['total_fee'];
		$data['dispatch_fee']   = $_GET['dispatch_fee'];
		$data['name']        = $_GET['name'];
		$data['mobile']      = $_GET['mobile'];
		$data['address']     = $_GET['address'];
		$data['form_id']     = $_GET['form_id'];
		$data['expect_time'] = $_GET['expect_time'];
		$data['goods']       = json_decode($_GET['goods'], true);
		// print_r($data['goods']);die;
		if($this->dataCheck($data['openid'])){
			$result = array("status" => -1,"msg" => "openid有误");
		}elseif ($this->dataCheck($data['store_id']) || $this->ifStores($data['store_id'])) {
			$result = array("status" => -1,"msg" => "store_id商家id有误或不存在");
		}elseif ($this->dataCheck($data['total_fee'])) {
			$result = array("status" => -1,"msg" => "total_fee总价有误");
		}elseif ($data['dispatch_fee'] == "null" || $data['dispatch_fee'] == "undefined" || !is_numeric($data['dispatch_fee'])) {
			$result = array("status" => -1,"msg" => "dispatch_fee配送费有误");
		}elseif ($this->dataCheck($data['name'])) {
			$result = array("status" => -1,"msg" => "name收货人有误");
		}elseif ($this->dataCheck($data['mobile'])) {
			$result = array("status" => -1,"msg" => "mobile收货人有误");
		}elseif ($this->dataCheck($data['address'])) {
			$result = array("status" => -1,"msg" => "address收货地址有误");
		}elseif ($this->dataCheck($data['form_id'])) {
			$result = array("status" => -1,"msg" => "form_id小程序表单id有误");
		}elseif ($this->dataCheck($data['expect_time'])) {
			$result = array("status" => -1,"msg" => "expect_time预计送达时间有误");
		}elseif ($this->goodsCheck($data['goods'])) {
			$result = array("status" => -1,"msg" => "goods商品有误");
		}else{
			$send_price = M("stores")->where(array("id"=>$data['store_id']))->find();
			if($data['total_fee'] >= $send_price['send_price']){
				$data['order_sn'] 	 = "SN".$data['store_id'].date("YmdHis");//订单编号 "SN商家ID年月日时分秒"
				$data['status']      = 1;//状态 1.待确认 2.待送货 3.已完成 -1.订单取消 -2.拒绝接单
				$data['expect_time'] = strtotime($data['expect_time']);//预计送达时间戳
				$data['create_time'] = time();//下单时间戳
				$orderCity = M("order_city")->add($data);
				if($orderCity){
					foreach ($data['goods'] as $key => $value) {//循坏商品数组
						$goods['order_id'] = $orderCity;//订单id
						$goods['good_id']  = $value['good_id'];
						$goods['num']      = $value['num'];
						$orderCityGood = M("order_city_good")->add($goods);
					}
					//$result = array("status" =>  1,"msg" => "下单成功");
					$order_new = M("order_city")->where(array("id"=>$orderCity))->find();

					// 发送模板消息（公众号）  这里需要修正 模板ID，在配置文件修改 APPID & APP_SERECT ！！！
	                vendor("WxPayPubHelperMp.WxPlugin");
	                $WxPlugin = new \WxPlugin();
	                $openid = $send_price['openid'];
	                $template_id = "k3jA1JLJawN_SfIi8Ymm171OzhRLebmAe0BLRYz5E6I";
	                $url = "http://" . $_SERVER['HTTP_HOST'] . U("Wechat/Store/storeOrder");
	                $data = array(
	                    'first'    => array('value' => urlencode("下单时间：".date("Y-m-d H:i:s",$order_new['create_time'])), 'color' => "#000000"),
	                    'keyword1' => array('value' => urlencode($order_new['order_sn']), 'color' => '#000000'),
	                    'keyword2' => array('value' => urlencode($order_new['total_fee']), 'color' => '#f35900'),
	                    'keyword3' => array('value' => urlencode(date("Y-m-d H:i:s",$order_new['expect_time'])."(预计)"), 'color' => '#f35900'),
	                    'keyword4' => array('value' => urlencode($order_new['mobile']), 'color' => '#000000'),
	                    'keyword5' => array('value' => urlencode($order_new['address']), 'color' => '#000000'),
	                    'remark'   => array('value' => urlencode('\r\n'.'您有新的点单,请及时处理!'), 'color' => '#000000')
	                );
	                $res = $WxPlugin->doSend($openid, $template_id, $url, $data);
	                if ($res['status'] == -1) {
	                    file_put_contents("./Logs/CityOrderFial.log", JSON($res)."\r\n", FILE_APPEND);
	                }
					$result = array("status" => 1,"msg" => "下单成功");
				}else{
					$result = array("status" => -1,"msg" => "下单失败");
				} 
			}else{
				$result = array("status" => -1,"msg" => "总价".$data['total_fee']."小于起送价".$send_price['send_price']."，拒绝下单");
			}
			
		}
		apiReturn($result);
	}
	
	//下单数据检查
    public function dataCheck($data){
        if (!$data || $data == "undefined" || $data == "null"){
            return true;
        }else{
            return false;
        }
    }
    //商家检查 $store_id商家id
	public function ifStores($store_id){
		$store = M("stores")->where(array("id" => $store_id))->find();
		if($store){
			return false;
		}else{
			return true;
		}
	}
    //下单数据商品数组检查
    public function goodsCheck($data){
    	//file_put_contents('loggggg.log',serialize($data));die;
    	if ($this->dataCheck($data)){
			return true;//goods商品有误
		}else{
			if(is_array($data)){ //判断是否为数组
				foreach ($data as $kg => $vg) {
					if($this->dataCheck($vg['good_id']) || $this->dataCheck($vg['num'])){ //检查商品数组中good_id、num
						return true;//$good_id&num商品id或数量有误
					}else{
						return false;
					}
				}	
			}else{
				return true;
			}		
		}
    }
}