<?php
if (! defined ( 'APP_PATH' ) || ! defined ( 'I_PATH' )) {
	exit ( 'Access Denied' );
}

/**
 * 订单相关内容
 * Enter description here ...
 * @author Administrator
 *
 */
class member_order extends controllerBase {
	
	function __construct() {
		parent::__construct ();
		$this->sy_class_type = syClass ( 'syclasstype' );
		$this->SysIconfig = parent::geticonfig ();
	}
	
	/**
	 * 添加到购物车
	 * Enter description here ...
	 */
	public function add_shop_cart() {
		//if(empty($_SESSION['member'])){message("请先登录查看购物车","?c=member&a=login");}
		if ($this->sysParams ( "go" ) == 1) //添加产品
{
			if (! isset ( $_POST ['productid'] ) || ! isset ( $_POST ['num'] ) || ! preg_match ( '/^[1-9]\d*$/', $_POST ['productid'] ) || ! preg_match ( '/^[1-9]\d*$/', $_POST ['num'] )) {
				$Arr = array ('erro' => 1, 'error' => '参数不完整' );
				echo json_encode ( $Arr );
				exit ();
			}
			
			$conditions = array ('id' => $_POST ['productid'], 'isshow' => '1' );
			$rs = syDB ( 'product' )->find ( $conditions );
			if (is_array ( $rs )) {
				$Arr = array ('erro' => 1, 'error' => '该产品不存在，或已经下架' );
			}
			
			$product = $rs;			
		
			$order_detail = array ('price' => $product ['price'], 'pid' => $product ['id'], 'name' => $product ['title'], unit => $product ['unit'], attr => '', 'number' => $_POST ['num'], 'litpic' => $product ['litpic'] );
			$isexits = false;
			if ($_SESSION ['order_detail']) {
				$details = unserialize ( $_SESSION ['order_detail'] );
				foreach ( $details as $k => $t ) {
					if ($t ['pid'] == $product ['id']) {
						$t ['number'] += $order_detail ['number'];
						$details [$k] = $t;
						$_SESSION ['order_detail'] = serialize ( $details );
						$isexits = true;
						break;
					}
				}
			} else {
				$details = array ();
			}
			if (! $isexits) {
				$details [] = $order_detail;
				$_SESSION ['order_detail'] = serialize ( $details );
			}
			$Arr = array ('erro' => 0, 'error' => '商品已成功添加到购物车' );
			echo json_encode ( $Arr );
			exit ();
		
		} elseif ($this->sysParams ( "go" ) == 2) { //删除产品]]
			
			//TODOD 
			if (! $this->sysParams ( 'productid' )) {
				$Arr = array ('erro' => 1, 'error' => '参数不完整' );
				echo json_encode ( $Arr );
				exit ();
			}
			$pid = $_POST ['productid'];
			//逻辑修改4
			if (! empty ( $_SESSION ['order_detail'] )) {
				$details = unserialize ( $_SESSION ['order_detail'] );
				foreach ( $details as $k => $d ) {
					if ($d ['pid'] == $pid) {
						unset ( $details [$k] );
						$_SESSION ['order_detail'] = serialize ( $details );
						$dellArr = array ('erro' => 0, 'error' => '删除成功' );
						echo json_encode ( $dellArr );
						exit ();
					}
				}
			}
			$dellArr = array ('erro' => 1, 'error' => '删除失败' );
			echo json_encode ( $dellArr );
			exit ();
		} 
		
		//检出商品#逻辑修改5
		if (! empty ( $_SESSION ['member'] )) {
			$conditions = array ('mid' => $_SESSION ['member'] ['id'], 'status' => '0' );
			$this->order = syDB ( 'order' )->findall ( $conditions );
		} else {
			if (! empty ( $_SESSION ['shopingcar'] )) {
				$allorder = array ();
				$showArr = explode ( ',', substr ( $_SESSION ['shopingcar'], 1 ) );
				$where = "";
				foreach ( $showArr as $v ) {
					$checkshow = syDB ( 'order' )->find ( "id=" . $v . " and status=0" );
					if (! empty ( $checkshow )) {
						$allorder [] = $checkshow;
					}
				}
				$this->order = $allorder;
			}
		}
		//TODO 没有用胡业务逻辑	
		$logistics = syDB ( 'logistics' )->findall ();
		$this->logistics = $logistics;
		$arr = array ();
		//总价格
		$this->totalmoney = 0;
		
		foreach ( $this->order as $v ) {
			$arr [] = $v ['aid'];
			$this->totalmoney += $v ['price'] * $v ['pnum'];
		}
		$arrs = array_unique ( $arr );
		$Arrimg = array ();
		foreach ( $arrs as $vv ) {
			$proimg = array ('id' => $vv );
			$rm = syDB ( 'product' )->find ( $proimg );
			$Arrimg [$vv] = $rm ['litpic'];
		
		}
		//图片集
		$this->productImg = $Arrimg;
		$this->display ( "member/shopingcart.html" );
	
	}
	/**
	 * 展示购物车
	 * Enter description here ...
	 */
	
	public function show_shop_cart() {
		$logistics = syDB ( 'logistics' )->findall ();
		$this->logistics = $logistics;
		$payments = syDB ( 'payment' )->findall ( "enabled=1" );
		$this->payments = $payments;
		//总价格
		$this->totalmoney = 0;
		if ($_SESSION ['order_detail']) {
			$details = unserialize ( $_SESSION ['order_detail'] );
			foreach ( $details as $d ) {
				$this->totalmoney += $d ['price'] * $d ['number'];
			}
			$this->details = $details;
		}
		$this->display ( "member/shopingcart.html" );
	}
	
	/**
	 * 提交购物车
	 * Enter description here ...
	 */
	public function submit_shop_cart() {
		if (! empty ( $_SESSION ['order_detail'] )) {
			$details = unserialize ( $_SESSION ['order_detail'] );
			//计算总价
			$total = 0;
			foreach ( $details as $d ) {
				$total += $d ['number'] + $d ['price'];
			}
			//计算保价
			$logistics = syDB ( 'logistics' )->findall ();
			$this->logistics = $logistics;
			$payments = syDB ( 'payment' )->findall ( "enabled=1" );
			$this->payments = $payments;
			$goods_total=$total;
			$insure_fee=0;
			$l_f=0;
			foreach ($logistics as $l)
			{
				if($l['log_id']==$_REQUEST['logistics'])
				{
					$l_f=$l['price'];
					$total+=$l['price'];
					if($l['insure']!=0)
					{
						$insure_fee=$goods_total*$l['insureproportion']/100;
						$total+=$insure_fee;
					}
					break;
				}
			}
			$pay_fee=0;
			//计算支付费用
			foreach ($payments as $p)
			{
				if($p['pay_id']==$_REQUEST['peyment'])
				{
					if($p['pay_fee']>0)
					{
						$pay_fee=$total*$p['pay_fee']/100;
						$total+=$pay_fee;
					}
				}
			}
			$row=array();
			$row['order_code']=date('Ymdhis',time());
			$row['status']=0;
			$row['mid']=checklogined()===false?0:checklogined();
			
			$row['adddate']=time();
			$row['ip']=ip();
			$row['status']=1;
			$row['mobile']=$_REQUEST['phone'];
			$row['address']=$_REQUEST['address'];
			$row['postcode']=$_REQUEST['yzcode'];
			$row['more']=$_REQUEST['more'];
			$row['goods_total']=$goods_total;
			$row['payment']=$_REQUEST['payment'];
			$row['logistic']=$_REQUEST['logistics'];
			$row['payment_fee']=$pay_fee;
			$row['logistics_fee']=$l_f;
			$row['insure_fee']=$insure_fee;
			$row['totalmoney']=$total;
			$row['email']=$_REQUEST['email'];
			$row['source']=1;
			$row['reciver_user']=$_REQUEST['reciver_user'];
			$id=syDB("order")->create($row);
			//-->将订单的order_id序列化存在到session里开
			$order_ids = array ();
			//如果session里存在order_id则先将order_id反序列化，得到一个数组，把新的值用array_push()压到数组里，然后再把数组序列化存到session里
			if(!empty($_SESSION['order_ids'])){
				$arr = unserialize($_SESSION['order_ids']);
				array_push($arr,$id);
				$_SESSION['order_ids'] = serialize($arr);
			}else 
			{
			$order_ids[] = $id;
			$_SESSION['order_ids'] = serialize($order_ids); 
			}
			//<--将订单的order_id序列化存在到session里开
			if($id===false)
			{
				$d=array('error'=>1,'msg'=>'添加购物车异常');
				echo json_encode($d);
				exit;
			}
			else 
			{
				foreach ($details as $d)
				{
					$d['order_id']=$id;
					syDB('order_detail')->create($d);
				}
				unset($_SESSION['order_detail']);
				$d=array('error'=>0,'msg'=>$id);
				
				echo json_encode($d);
				exit;
			}
			
		}
		exit;
	}
	
	/**
	 * 判断用户是否已经登录  登录 返回1  否则返回 0
	 * Enter description here ...
	 */
	public function logined() {
		if (checklogined () === false) {
			echo 0;
			exit ();
		} else {
			echo 1;
			exit ();
		}
	}
	
	/**
	 * 删除单个产品
	 * Enter description here ...
	 */
	public function shop_cart_delete() {
		if (! $this->sysParams ( 'productid' )) {
			$Arr = array ('erro' => 1, 'error' => '参数不完整' );
			echo json_encode ( $Arr );
			exit ();
		}
		$pid = $_POST ['productid'];
		//逻辑修改4
		if (! empty ( $_SESSION ['order_detail'] )) {
			$details = unserialize ( $_SESSION ['order_detail'] );
			foreach ( $details as $k => $d ) {
				if ($d ['pid'] == $pid) {
					unset ( $details [$k] );
					$_SESSION ['order_detail'] = serialize ( $details );
					$dellArr = array ('erro' => 0, 'error' => '删除成功' );
					echo json_encode ( $dellArr );
					exit ();
				}
			}
		}
		$dellArr = array ('erro' => 1, 'error' => '删除失败' );
		echo json_encode ( $dellArr );
		exit ();
	}
	
	/**
	 * 更新购物车详情
	 * Enter description here ...
	 */
	public function update_detail() {
		if (! $this->sysParams ( 'productid' )) {
			$Arr = array ('erro' => 1, 'error' => '参数不完整' );
			echo json_encode ( $Arr );
			exit ();
		}
		$pid = $_POST ['productid'];
		//逻辑修改4
		if (! empty ( $_SESSION ['order_detail'] )) {
			$details = unserialize ( $_SESSION ['order_detail'] );
			$totalpirce = "0";
			$isexits = false;
			foreach ( $details as $k => $d ) {
				if ($d ['pid'] == $pid) {
					$d ['number'] = $_POST ['number'];
					$details [$k] = $d;
					$_SESSION ['order_detail'] = serialize ( $details );
					$totalpirce += $d ['number'] * $d ['price'];
					$isexits = true;
				} else {
					$totalpirce += $d ['number'] * $d ['price'];
				}
			}
		}
		if ($isexits) {
			$dellArr = array ('erro' => 0, 'error' => '更新成功', 'totalmoney' => $totalpirce );
			echo json_encode ( $dellArr );
			exit ();
		} else {
			$dellArr = array ('erro' => 1, 'error' => '没有找到对应的产品' );
			echo json_encode ( $dellArr );
			exit ();
		}
	}
	
	/**
	 * 直接订购  添加单个商品到订单
	 * Enter description here ...
	 */
	public function create_order() {
		//phone:phone,address:address,yzcode:yzcode,more:more,idliststr:str,reciver_user:reciver_user
		echo $_POST ['phone'];
		if (! isset ( $_POST ['productid'] ) || ! isset ( $_POST ['num'] ) || ! preg_match ( '/^[1-9]\d*$/', $_POST ['productid'] ) || ! preg_match ( '/^[1-9]\d*$/', $_POST ['num'] )) {
			$Arr = array ('erro' => 1, 'error' => '参数不完整' );
			echo json_encode ( $Arr );
			exit ();
		}
		$conditions = array ('id' => $_POST ['productid'], 'isshow' => '1' );
		$rs = syDB ( 'product' )->find ( $conditions );
		if (! $rs) {
			$Arr = array ('erro' => 1, 'error' => '该产品不存在，或已经下架' );
		}
		$serialNum = date ( 'md' ); //流水号
		$num1 = 4 - strlen ( $rs ['id'] );
		if (intval ( $num1 ) > 0) {
			for($i = 1; $i <= $num1; $i ++) {
				$serialNum .= '0';
			}
		}
		
		$serialNum .= $rs ['id'];
		
		//逻辑修改1
		if (! empty ( $_SESSION ['member'] )) {
			$num2 = 4 - strlen ( $_SESSION ['member'] ['id'] );
			if (intval ( $num2 ) > 0) {
				for($s = 1; $s <= intval ( $num2 ); $s ++) {
					$serialNum .= '0';
				}
			}
			
			$serialNum .= $_SESSION ['member'] ['id'];
		} else {
			$serialNum .= '0000';
		}		
		$addArr = array ('code' => $serialNum, 'aid' => $rs ['id'], 'status' => '0', 'ip' => ip (), 'telphone' => $_POST ['phone'], 'pnum' => $_POST ['num'], 'pname' => $rs ['title'], 'price' => $rs ['price'], 'subtotal' => $total );
		
		$add = syClass ( 'ldi_order' );
		$a = $add->create($addArr);
		
	
	}
	
	/**
	 * 结算 直接生成订单   
	 * Enter description here ...
	 */
	public function add_order() {
	
	}
	
	/**
	 *同步会员信息到订单
	 * Enter description here ...
	 */
	public function sycn_member() {
	
	}
	
	/**
	 * 设置订单付款完成
	 * Enter description here ...
	 */
	public function set_payment() {
	
	}
	
	/**
	 * 展示订单列表
	 * Enter description here ...
	 */
	public function index() {
		if (! empty ( $_SESSION ['member'] )) {
			$page = max($_GET[page],1);
			$pagesize = 15;
			$start = ($page-1)*$pagesize;
			
			//$this->listorder = syDB ( 'order' )->findall ( 'mid = ' . $_SESSION ['member'] ['id'] . ' AND status > 0', ' id desc ' );
			$sql = "select orders.*,product.title,product.litpic from ld_order orders left join ld_order_detail detail on orders.id=detail.order_id 
			left join ld_product product on product.id=detail.pid 
			where orders.mid='{$_SESSION[member][id]}' and status > 0 and product.id>0 order by orders.id desc  limit $start,$pagesize";
			$data            = getlistData("order", " mid='{$_SESSION[member][id]}' ",$sql);
			$this->listorder = $data['list'];
			$pagearray       = page_c($data[nums],$page,$pagesize);
			$this->pages     = pagetxt($pagearray);
		} else {
			//如果没有登陆则从session里读取order_id			
			$order_ids = unserialize($_SESSION['order_ids']);//将反序列化session，得到一个order_id数组
			//print_r($order_ids);die;
			if (! empty ( $order_ids)) {
								
				$myarr = array ();
				$page = max($_GET[page],1);
				$pagesize = 15;
				$start = ($page-1)*$pagesize;
				foreach ( $order_ids as $v ) {
					
					$sql = "select orders.*,product.title,product.litpic from ld_order orders left join ld_order_detail detail on orders.id=detail.order_id 
			                left join ld_product product on product.id=detail.pid 
			                where orders.id={$v} and status > 0 and product.id>0 order by orders.id desc  limit $start,$pagesize";

					$aa = getlistData("order", " id ={$v} ",$sql);
					
					//$aa = syDB ( 'order' )->find ( 'id = ' . $v . ' AND status > 0' );
					if (! empty ( $aa )) {
						$myarr  = $aa['list'];	
					}
				}
				$this->listorder = $myarr;	
				$pagearray       = page_c($aa[nums],$page,$pagesize);
				$this->pages     = pagetxt($pagearray);	
			} else {
				$this->listorder = array ();
			}		
		}		
		$this->display ("member/listorder.html" );
	}
	
	/**
	 * 查看一张订单的明细
	 */
	public function show_order_detail() {
		if (! $this->sysParams ( 'orderid', 1 ))
			message ( "请按正确的流程操作", "?c=member_order&a=index" );
		
		if (! empty ( $_SESSION ['member'] ['id'] )){
			
			$conditions = array ('mid' => $_SESSION ['member'] ['id'], 'id' => $this->sysParams ( 'orderid', 1 ));
			$this->ordershow = syDB ('order')->find($conditions);
			
			$this->order_detail = syDB ( 'order_detail' )->findall ('order_id='.$this->ordershow['id']);
		} else {
			
			$conditions = array ('mid' => '0', 'id' => $this->sysParams ( 'orderid', 1 ) );
			$this->ordershow = syDB ('order')->find ( $conditions );
			$this->order_detail = syDB ( 'order_detail' )->findall ('order_id='.$this->ordershow['id']);
		
		}
		
		$proimg = array ('id' => $this->ordershow ['aid'] );
		$rm = syDB ( 'product' )->find ( $proimg );
		$this->productImg = $rm ['litpic'];
		$this->orderStatus = array ('1' => '已下单', '2' => '已付款', '4' => '系统已确认', '8' => '已发货' );
		
		//支付信息
		if ($this->ordershow ['status'] < 2) {
			$recodeArr = syDB ( 'consumer_records' )->find ( array ('orderid' => $this->ordershow ['id'] ) );
			
			$this->aplipayOrderId = $this->ordershow ['id']; //订单ID
			$this->aplipayPorductName = $this->ordershow ['pname']; //商品名
			$this->aplipayTotalFee = $this->ordershow ['pnum'] * $this->ordershow ['price']; //商品总价
			$this->aplipayUid = $_SESSION ['member'] ['id']; //用户ID
			$this->aplipayInfo = $this->ordershow ['more'];
			$this->aplipayMid = $_SESSION ['member'] ['id'] . "|" . $this->ordershow ['id'] . "|" . $recodeArr ['id'];
			if ($this->ordershow ['more'] == '') {
				$this->Info = '购买' . $this->ordershow ['pname'] . '共计' . $this->aplipayTotalFee . '元';
			}
		
		}
		
		$this->display ( "member/ordershow.html" );
	}
}
	
	
