<?php ob_start();
include_once 'init-lite.php';?>
<script>
//$(document).on("pagecreate","#pageone",function(){
//填坑。首页tap无效。

$("a").on("tap",function(e){
	var taptype = $(this).attr("dstype");
	var tapid = $(this).attr("id");
	var id ='';
	try {
		id = tapid.replace(taptype,"");
	}catch(err){
	}
	var tapval = $(this).text();
	//alert("taptype : " + taptype + "\n id :" +  id + "\n val : " + tapval);
	switch (taptype){
		case "btnAddmenu":
		  AddToOrders(id,tapval);
		  break;
		case "btnMinusmenu":
		  AddToOrders(id,tapval);
		  break;
		case "btnPopupOrderRemark":
		  var SQL_UserCode =encodeURIComponent($("#UserCode"+id).val());
		  var SQL_ProductName =$("#ProductName"+id).val();
		  var SQL_action =$("#action"+id).val();
		  var SQL_Remark =$("#Remark"+id).html();
		  //alert('*'+SQL_Remark+'*');
  		  $("#ActionRemark").val(SQL_action).selectmenu('refresh', true); //先修改值 然后再刷新
  		  $("#ProductNameRemark").html(SQL_ProductName);
		  $("#UserCodeRemark").val(SQL_UserCode);
		  $("#OrderRemark").val(SQL_Remark);
		  $("#line").val(id);
		  $("#dviPopRemark").popup("open"); 
		  break;
	}	
		
 	switch(tapid){
		case "dviPopRemarkx":
			var oid = <?php echo is_numeric($LastOrderID)?$LastOrderID:0;?>;
			var SQL_UserCode = encodeURIComponent($("#UserCodeRemark").val());
			var SQL_Remark = encodeURIComponent($("#OrderRemark").val());
			//alert(SQL_Remark);
			var SQL_Action = encodeURIComponent($("#ActionRemark").val());
			//alert($("#line").val());
			$("#Remark"+$("#line").val()).html($("#OrderRemark").val());	
			$.ajax({
				type: "POST", //提交的类型
				url: "addMenu-saveremark.php", //提交地址
				data: "_dc=" + new Date().getTime() + "&oid=" + oid + "&UserCode=" + SQL_UserCode + "&Remark=" + SQL_Remark+ "&Action=" + SQL_Action, //参数
				success: function(data) { //回调方法
				//$("#myDivTotal").html(data);
				//if (data=='false') 
				//	alert('更新备注失败');						 
				}
			});
			break;		
	}
}); 
//});
                      
</script>

<div data-role="popup" class="data-shadow" data-dismissible="false"  id="dviPopRemark" data-dialog="true" style="min-width:250px;"  data-overlay-theme="b">
      <a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn ui-icon-delete ui-btn-icon-notext ui-btn-right">关闭</a>
        <div data-role="main" class="ui-content ">
   <h3>附加信息</h3>
    <p id="ProductNameRemark"></p>
<input type="hidden" id="line" />
<input type="hidden" id="UserCodeRemark" />
<textarea name="addinfo" id="OrderRemark"></textarea>
<fieldset data-role="fieldcontain">
   <label for="ActionRemark">操作</label>
   <select name="ActionRemark" id="ActionRemark">
      <option value="" selected="selected">无</option>
         <option value="dish">催菜</option>
         <option value="cook">厨单</option>
         <option value="bar">酒水单</option>
         <option value="help">服务员帮助</option>
         <!--<option value="god">上天</option>-->
   </select>
</fieldset>
	  
	      <a href="#" id="dviPopRemarkx" class="ui-btn ui-btn-inline ui-shadow ui-corner-all ui-icon-check ui-btn-icon-left ui-btn-inline ui-mini" data-rel="back">提交</a>

  
  </div>
</div>  
 
  
<table width="100%"   class="ui-responsive ui-shadow"  id="myTable" data-role="table"  data-filter="true" data-input="#myFilter" data-autodividers="true"  data-mode="columntoggle:none">
	<thead>
		<tr>
			<th colspan="3">
				<form class="ui-filterable">
					<input id="myFilter" placeholder="搜索" size="6" data-type="search" data-clear-btn="true">
				</form>
			</th> 
		</tr>
	</thead>
	<tbody>
		<?php
		function DownloadPhotoFromDB($ProductID,$UserCode){
			global $dbconnection;
			global $dbuser;
			global $dbpassword;
			global $CFG_PrintEnable; 
			$orders = new PDO($dbconnection,$dbuser,$dbpassword);
			//$SQlStrImage = "SELECT top 1 [Image] FROM Products where Image is not null";
			$sql = "SELECT Usercode,[Image] FROM Products where ProductID=".$ProductID;
			$stmt = $orders->prepare($sql); 
			$stmt->execute(); 
			$stmt->bindColumn(1, $Usercode); 
			$stmt->bindColumn(2, $data, PDO::PARAM_LOB); 
			$stmt->fetch(); 
			$data=preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $data);	
			$imgbin=hex2bin($data);
			file_put_contents("Photo/" . $Usercode . ".jpg", $imgbin, true);
			console_log('下载'.$Usercode . '.jpg');
		}
		
		$Line1=0;
		$wherestr1 = "";
		$joinstr = " LEFT OUTER JOIN "; 
	
		if (!empty($_POST['CategoryID']) && strlen($_POST['CategoryID'])>0) 
			$wherestr1 = " where Products.CategoryID=".$_POST['CategoryID'];    
		elseif (!empty($_POST['textSerch'])) 
			$wherestr1 = " where Products.ProductName like '%".$_POST['textSerch']."%'";
			
 		$sql = "SELECT Products.ProductID,Products.UserCode,Products.ProductName,Products.ProductName2,Products.UnitPrice,Products.CategoryID,Products.Step,Products.limitQty,null as Quantity,null as Remark,null as [action],CAST(Products.Picture AS varchar(MAX)) AS Picture  FROM Products  LEFT OUTER JOIN
                Categories ON Products.CategoryID = Categories.CategoryID  " . $wherestr1 ;  
		
		if (is_numeric($LastOrderID)) {
			$wherestr1 = "";
			$joinstr = " LEFT OUTER JOIN "; 
			if (!empty($_POST['CategoryID']) && strlen($_POST['CategoryID'])>0 && $_POST['CategoryID']=='thisorder') 
				$joinstr = " INNER JOIN ";    
			elseif (!empty($_POST['CategoryID']) && strlen($_POST['CategoryID'])>0 && $_POST['CategoryID']!='thisorder') 
				$wherestr1 = " where Products.CategoryID=".$_POST['CategoryID'];    
			elseif (!empty($_POST['textSerch'])) 
				$wherestr1 = " where Products.ProductName like '%".$_POST['textSerch']."%'";
				
			$sql = "SELECT   Products.ProductID,Products.UserCode, Products.ProductName, Products.ProductName2, Products.UnitPrice, Products.CategoryID, 
                Products.Step, Products.limitQty, derivedtbl_1.Quantity AS Quantity,derivedtbl_1.Remark,derivedtbl_1.[action] , 
                    CAST(Products.Picture AS varchar(MAX)) AS Picture 
FROM      Products  LEFT OUTER JOIN
                Categories ON Products.CategoryID = Categories.CategoryID ".$joinstr."
                    (SELECT   SUM(Quantity) AS Quantity, UserCode, Remark,[action] 
FROM      [Order Details]
WHERE   (OrderID = ".$LastOrderID.")  
GROUP BY UserCode,Remark,[action]) AS derivedtbl_1 ON derivedtbl_1.UserCode = Products.UserCode
" . $wherestr1 ." 
            GROUP BY Categories.PrintGroup, Products.UserCode,  Products.ProductName,   Products.ProductName2,
                     Products.UnitPrice,    Products.ProductID, Products.CategoryID,    Products.Step,
                     Products.limitQty,     derivedtbl_1.Quantity,  derivedtbl_1.Remark,    derivedtbl_1.[action],
                     CAST(Products.Picture AS varchar(MAX))";
				 
	}
	       $sql .= " order by Categories.PrintGroup,Products.CategoryID,LEN(Products.UserCode),Products.UserCode";
 
  //die($sql);
 $values = $orders->query($sql);
if (is_iterable($values)){
  foreach ($values as $pProductsAddMenu){ 
 $Line1++; 
$pProductsAddMenu['UserCode']=loadFromMssql($pProductsAddMenu['UserCode']);
$pProductsAddMenu['ProductName']=loadFromMssql($pProductsAddMenu['ProductName']);
$pProductsAddMenu['ProductName2']=loadFromMssql($pProductsAddMenu['ProductName2']);
$pProductsAddMenu['Remark']=loadFromMssql($pProductsAddMenu['Remark']);
$pProductsAddMenu['action']=loadFromMssql($pProductsAddMenu['action']);
$pQuantity=$pProductsAddMenu['Quantity']?$pProductsAddMenu['Quantity']:0;
$pProductsAddMenu['limitQty']=-1;
if (intval($pQuantity) == $pQuantity) $pQuantity = number_format($pQuantity, 0);
 ?>
		<tr>
			<td width="90">	 
<?php 	 
				$PictureMd5 = $pProductsAddMenu['Picture'];

				if (file_exists('Photo/'.$pProductsAddMenu['UserCode'].'.jpg')) {
					//读取本地文件md5跟数据库对比
					//TODO:影响执行速度,需要优化
					$md5file = md5_file('Photo/'.$pProductsAddMenu['UserCode'].'.jpg');

					//存在本地图片
					if ($PictureMd5 != $md5file){
                    	//如果本地md5和数据库md5不一致，则下载数据库的图片到本地
						console_log('下载数据库的图片 ： '.$PictureMd5 );
						console_log('本地MD5 ： '.$md5file );
						DownloadPhotoFromDB($pProductsAddMenu['ProductID'],$pProductsAddMenu['UserCode']);
					}
				}else if(!empty($PictureMd5)){
					DownloadPhotoFromDB($pProductsAddMenu['ProductID'],$pProductsAddMenu['UserCode']);
				}

				if (file_exists('Photo/'.$pProductsAddMenu['UserCode'].'.jpg'))  
				{
					//读取显示到控件
					echo '<img src="Photo/'.$pProductsAddMenu['UserCode'].'.jpg" width="80" height="80" 
					class="ui-corner-all ui-shadow "/>';
			    }else{ 
					echo '<img src="_ini/iconblank.png" width="80" height="80" 
					class="ui-corner-all ui-shadow "/>';
				}
				?>
			</td>
		<td> 
				<?php  echo $pProductsAddMenu['ProductName']; ?>
				
				
				
				<?php 	 if (!empty($LastOrderID)) 	echo '  <input type="hidden" name="OrderID" id="OrderID" value="'.$LastOrderID.'"/>';  ?>
				
				
				<input type="hidden" name="UserCode<?php echo $Line1; ?>" id="UserCode<?php echo $Line1; ?>" value="<?php echo $pProductsAddMenu['UserCode']; ?>"/>
				<input type="hidden" name="action<?php echo $Line1; ?>" id="action<?php echo $Line1; ?>" value="<?php echo $pProductsAddMenu['action']; ?>"/>				
				<input type="hidden" name="ProductName<?php echo $Line1; ?>" id="ProductName<?php echo $Line1; ?>" value="<?php echo $pProductsAddMenu['ProductName']; ?>"/>
				<input type="hidden" name="UnitPrice<?php echo $Line1; ?>" id="UnitPrice<?php echo $Line1; ?>" value="<?php echo $pProductsAddMenu['UnitPrice']; ?>"/>
				<br />
				<?php  
								  if ($pQuantity>0) echo '<b>'.number_format($pProductsAddMenu['UnitPrice'],2).'</b>';  else echo number_format($pProductsAddMenu['UnitPrice'],2);  ;?>
				<input type="hidden" name="Step<?php echo $Line1; ?>" id="Step<?php echo $Line1; ?>" value="<?php echo $pProductsAddMenu['Step']; ?>" size="2"/>
				<input name="limitQty<?php echo $Line1; ?>" type="hidden" id="limitQty<?php echo $Line1; ?>" value="<?php echo $pProductsAddMenu['limitQty']; ?>" size="2"/>&nbsp;&nbsp;<i id="Remark<?php echo $Line1; ?>"><?php echo $pProductsAddMenu['Remark'];?></i>
	</td>
			<td width="125">
				<div data-role="navbar">
					<?php 
					if ($pProductsAddMenu['limitQty']!=0 &&  strlen($CompanyName)<>0 ) {  //limitQty  库存（-1表示不限量供  ?>
					<ul> 
						<li><a href="#" dstype="btnPopupOrderRemark" id="btnPopupOrderRemark<?php echo $Line1; ?>" <?php if ($pQuantity==0) echo 'style=\'display: none;\''; ?>  class="ui-btn ui-alt-icon ui-nodisc-icon ui-icon-edit ui-btn-icon-notext "  ></a></li>
						<li><a href="#" dstype="btnMinusmenu" id="btnMinusmenu<?php echo $Line1; ?>" <?php if ($pQuantity==0 || (isset($_POST['forcein']) && $_POST['forcein']==1)) echo 'style=\'display: none;\''; ?>  class="ui-btn ui-shadow ui-corner-all ui-icon-minus ui-btn-icon-notext "  >-</a></li>
						<li><span id="Quantity<?php echo $Line1; ?>" <?php if ($pQuantity==0) echo 'style=\'display: none;\''; ?> class="table-td-count" style="color:blue; text-align:center"><?php echo $pQuantity;?></span></li>
						<li><a href="#" dstype="btnAddmenu" id="<?php echo $Line1; ?>" class="ui-btn ui-shadow ui-corner-all ui-icon-plus ui-btn-icon-notext" >+</a></li>
					</ul>
					<span style="padding: 2px 0px 0px 0px;display:block; text-align:center ; font-size:11px;color:gray" id="myDiv<?php echo $Line1; ?>">
					<?php 
 if ($pProductsAddMenu['limitQty']!=-1) echo "余:".$pProductsAddMenu['limitQty'];
?>
					</span>
					<?php }else if ($pProductsAddMenu['limitQty']==0)  
	echo "<b><span style='color:red;display:block; text-align:center ;'>已售罄！</span></b>";
  ?>
				</div>
			</td>
		</tr>
		<?php   }}
                          ?>
	</tbody>
</table>
<?php ob_end_flush();?>


 