<?php
include_once("htui_header.php");
include_once(RootPath."classes/images.php");  //生成缩略图
include_once(RootPath."common/watermark.php");//图片添加水印

if (!empty($_POST)){

    if (check_permission($_SESSION["a_uid"],'adlist.php',2)){

		try {
           
            $db->startTrans();

            $id         = intval($_POST["id"]);
			$adtitle    = flc_request(trim($_POST["adtitle"]));
			$adurl      = flc_request(trim($_POST["adurl"]));
			$adtype     = intval($_POST["adtype"]);
			$adflag     = intval($_POST["adflag"]);
			$ad_asc     = intval($_POST["ad_asc"]);
		    $category_id=intval($_POST["category_id"]);
			
			$begintime=flc_request(trim($_POST["begintime"]));
			$endtime=flc_request(trim($_POST["endtime"]));

			if (!empty($_FILES)){

				$width      = intval($_POST["width"]);         //图片宽度
	            $height     = intval($_POST["height"]);        //图片高度
			
				$file_name  = $_FILES['file']['name'];
				$tmp_name   = $_FILES['file']['tmp_name'];
				$file_size  = $_FILES['file']['size']/1024;

				$temp_arr   = explode(".", $file_name); 
				$file_ext   = array_pop($temp_arr); 
				$file_ext   = trim($file_ext);
				$file_ext   = strtolower($file_ext);
				
				if (in_array($file_ext, $ext_arr) === false) {
					$response_arr = array("status" => -1,"message"  => '限传'.$ext_str.'类型');
					echo json_encode($response_arr);
					exit;
				}
				
				$path = "../upload/user_ad/";
				$fn   = uniqid().".".$file_ext;
				$adfile = "../upload/user_ad/".$fn;
				$file_path = $path . iconv("UTF-8","gb2312",$file_name);

				/*删除原来已上传的图片*/
                $sql = "select * from {$tablepre}advert where id='".$id."'"; 
                $r   = $db->get_row($sql);

                include_once("../classes/fileclass.php");
			    $file = new fileoperate();
				$file->del_attach("",$r['ad_pic']);

				$sql = "update {$tablepre}advert set adtitle='".$adtitle."',adurl='".$adurl."',adtype='".$adtype."',
				        begintime='".$begintime."',endtime='".$endtime."',adflag='".$adflag."',ad_asc='".$ad_asc."',
						ad_h='".$height."',ad_w='".$width."',ad_pic='".$adfile."',category_id='".$category_id."' 
						where id=".$id;
				$db->exec($sql);

				if (move_uploaded_file($tmp_name, $adfile)){

					$thumbnail = new ImageResize();	
					$thumbnail->resizeimage($adfile,$width,$height,0,$adfile);

					$ip_addr = GetUserIP();
					$sql = "insert into {$tablepre}upload_log (uplod_type,scuser_id,ip_addr,action_file,upload_file,add_time) 
							values(1,'".$_SESSION["a_uid"]."','".$ip_addr."','edit_ad.php','".$adfile."','".$getnow."')";	
					$db->exec($sql,true);

				}else{
					throw new Exception('图片上传失败!');
				}

            }else{
                $sql = "update {$tablepre}advert set adtitle='".$adtitle."',adurl='".$adurl."',adtype='".$adtype."',begintime='".$begintime."',endtime='".$endtime."'
				   ,adflag='".$adflag."',ad_asc='".$ad_asc."',category_id='".$category_id."' where id=".$id;
				$db->exec($sql);
			}

			$db->commit();

			$response_arr = array("status" => 1,"message"  => '操作成功');
		    echo json_encode($response_arr);
            exit;

		} catch (Exception $e) {
			$db->rollback();
			$response_arr = array("status" => -1,"message"  => $e->getMessage());
		    echo json_encode($response_arr);
            exit;
        }		

	}else{
        $response_arr = array("status" => -1,"message"  => '对不起,您无权限操作!');
		echo json_encode($response_arr);
        exit;
	}
}

$sql = "select * from {$tablepre}category order by category_order asc, category_id Desc";
$ListArray = $db->get_all($sql);

if(!empty($ListArray) && is_array($ListArray)){
   foreach($ListArray as $k => $row){
	  $createtime = dateFormat($row['category_createtime'],'Y-m-d H:i:s');
	  $class_arr[] = array($row['category_id'],$row['category_name'],$row['category_parentid'],$row['category_order'],$row['category_status'],$row['category_url'],$createtime);
   }
}

$id  = intval($_GET["id"]);
$sql = "select * from {$tablepre}advert where id='".$id."'"; 
$myrow = $db->get_row($sql);
?>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>后台管理中心_飞天素材网</title>
<meta name="author" content="ftsucai.com">
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link href="../css/fonts.css" rel="stylesheet">
<link href="../css/htstyle.css" rel="stylesheet">
<link href="../js/bootstrap-datepicker/bootstrap-datepicker3.min.css" rel="stylesheet">
<link href="../js/bootstrap-colorpicker/css/bootstrap-colorpicker.min.css" rel="stylesheet">
</head>
  
<body>

    <!--页面主要内容-->
    <main class="ftdms-layout-content">
      
      <div class="container-fluid" style="margin-bottom:90px;">
        
        <div class="row" style="margin-top:15px;">
          <div class="col-lg-12">
            <div class="card">
              <div class="card-header"><h4>修改广告</h4>
			     <ul class="card-actions">
                    <li> <span><a href="adlist.php">返回列表</a></span> </li>
                 </ul>
			  </div>
              <div class="card-body" style="padding:5px 20px;">
                
                <form class="form-horizontal" action="" method="post" enctype="multipart/form-data" id="form">

				  <div class="form-group">
                    <label class="col-xs-12" for="adtitle">广告标题</label>
                    <div class="col-xs-12">
                      <input class="form-control" type="text" id="adtitle" name="adtitle" value="<?php echo $myrow['adtitle'];?>">
                    </div>
                  </div>

				  <div class="form-group">
                    <label class="col-xs-12" for="adtype">广告类型</label>
					<div class="col-xs-12">
					    <label class="radio-inline" for="adtype">
                        <input type="radio" id="adflag" name="adtype" value="1" <?php if ($myrow['adtype']==1){?>checked<?php }?>>首页
                        </label>
						<label class="radio-inline" for="adtype">
                        <input type="radio" id="adflag" name="adtype" value="2" <?php if ($myrow['adtype']==2){?>checked<?php }?>>列表页
                        </label>
						<label class="radio-inline" for="adtype">
                        <input type="radio" id="adflag" name="adtype" value="3" <?php if ($myrow['adtype']==3){?>checked<?php }?>>详情页
                        </label>
					</div>
                  </div>

				  <div class="form-group">
                    <label class="col-xs-12" for="adurl">链接地址</label>
                    <div class="col-xs-12">
                      <input class="form-control" type="text" id="adurl" name="adurl" value="<?php echo $myrow['adurl'];?>">
                    </div>
                  </div>

                  <div class="form-group">
                    <label class="col-xs-12" for="category_id">广告位置</label>
					<div class="col-xs-12">
                      <select class="form-control" id="category_id" name="category_id" style="height:40px;">
					    <option value="0">网站首页</option>
                        <?php
            	           dafenglei_select(0,0,$myrow['category_id']);
			            ?>
                      </select>
                    </div>
                  </div>

				  <div class="form-group">
				       <label class="col-xs-12" for="pic">广告图片</label>
					   <div class="col-xs-12">
					       <div class="input-group">
					       <input id='location' class="form-control" onclick="$('#i-file').click();">
					           <label class="input-group-btn">
					               <input type="button" id="i-check" value="浏览文件" class="btn btn-default" onclick="$('#i-file').click();">
					           </label>
					       </div>
					   </div>
					   <input type="file" name="pic_file" id='i-file'  accept="<?php echo $ext_str;?>" onchange="$('#location').val($('#i-file').val());" style="display: none">
				  </div>

                  <div class="form-group">
                    <label class="col-xs-12" for="ad_asc">排序(值越小排越前)</label>
                    <div class="col-xs-12">
                      <input class="form-control" type="text" id="ad_asc" name="ad_asc" value="<?php echo $myrow['ad_asc'];?>">
                    </div>
                  </div>

                  <div class="form-group">
                    <label class="col-xs-12" for="adflag">显示状态</label>
					<div class="col-xs-12">
					    <label class="radio-inline" for="adflag">
                        <input type="radio" id="adflag" name="adflag" value="1" <?php if ($myrow['adflag']==1){?>checked<?php }?>>显示
                        </label>
						<label class="radio-inline" for="adflag">
                        <input type="radio" id="adflag" name="adflag" value="0" <?php if ($myrow['adflag']==0){?>checked<?php }?>>隐藏
                        </label>
					</div>
                  </div>
				  
				  <div class="form-group">
	                   <label class="col-xs-12" for="yxsj">有效时间</label>
	                   <div class="input-daterange input-group" style="padding:5px 16px;">
	                      <input class="form-control js-datepicker" data-date-format="yyyy-mm-dd" type="text" id="begintime" name="begintime" value="<?php echo $myrow['begintime'];?>">
	                      <span class="input-group-addon"><i class="mdi mdi-chevron-right"></i></span>
	                      <input class="form-control js-datepicker" data-date-format="yyyy-mm-dd" type="text" id="endtime" name="endtime" value="<?php echo $myrow['endtime'];?>">
	                   </div>
                  </div>
                  
                  <div class="form-group">
                    <div class="col-xs-12">
					  <input type="hidden" name="id" id="id" value="<?php echo $id;?>">
					  <button class="btn btn-primary" type="button" id="submit">确认修改</button>
					  <button type="button" class="btn btn-default" onclick="javascript:history.back(-1);return false;">返回</button>
                    </div>
                  </div>
                </form>
                
              </div>
            </div>
          </div>
          
        </div>
        
      </div>
      
    </main>
    <!--End 页面主要内容-->
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.js"></script>
<script src="../js/perfect-scrollbar.min.js"></script>
<script src="../js/main.min.js"></script>
<script src="../js/bootstrap-notify.min.js"></script>
<script src="../js/bootstrap-datepicker/bootstrap-datepicker.min.js"></script>
<script src="../js/bootstrap-datepicker/bootstrap-datepicker.zh-CN.min.js"></script>
<script src="../js/bootstrap-colorpicker/bootstrap-colorpicker.js"></script>
<script src="../js/tips.js"></script>
<script>

	$("#submit").click(function(){

		var formData  = new FormData();
        var id        = $("#id").val();
		var category_id = $("#category_id").val();
		var adtitle     = $("#adtitle").val();
		var adurl       = $("#adurl").val();
		var adtype      = $("input[name='adtype']:checked").val();
		var ad_pic      = $("#ad_pic").val();
		var adflag      = $("input[name='adflag']:checked").val();
		var begintime   = $("#begintime").val();
		var endtime     = $("#endtime").val();

		if (adtitle==''){
			tips.notify('广告标题不能为空', 'warning', 200);
			return false;
		}

        formData.append("id", id);
        formData.append("category_id", category_id);
		formData.append("adtitle", adtitle);
		formData.append("adurl", adurl);
		formData.append("adtype", adtype);
		formData.append("ad_pic", ad_pic);
		formData.append("adflag", adflag);
		formData.append("begintime", begintime);
		formData.append("endtime", endtime);

		if ($("#location").val()!=''){
			formData.append("file", $("#i-file")[0].files[0]);

			var file = $("#i-file")[0].files[0];
			var reader = new FileReader();
			reader.readAsDataURL(file);
			reader.onload = function (e) {

				var data = e.target.result;
				//加载图片获取图片真实宽度和高度
				var image = new Image();
				image.src = data;

				//图片先加载完，才可以得到图片宽度和高度
				image.onload = function(){
					var width  = image.width;
					var height = image.height;
					if (width>1158){
						pic_err="图片宽度要小于1158";
						tips.notify(pic_err, 'danger', 200);
						return false;
					}

					if ($("#location").val()==''){
						tips.notify('广告图片不能为空', 'warning', 200);
						return false;
					}

					formData.append("width", width);
					formData.append("height", height);

					$.ajax({
						url: "edit_ad.php",
						type: "post",
						data: formData,
						processData: false,
						contentType: false,
						dataType: 'text',
						//执行中
						beforeSend:function() {
							tips.loading('show');
						},
						success: function(data) {

							tips.loading('hide');
							var rs  = eval('('+data+')');
							var msg = rs.message;

							if(rs.status==1){
							   //tips.notify(msg, 'success', 1000, 'ftsucai-name', 'top', 'center');
							   window.location.href='adlist.php';
							}else{
							   tips.notify(msg, 'danger', 200);
							}
						},
						error: function(data) {
							tips.notify('服务器异常,请稍后再试~', 'danger', 200);
						}
					});
				}
			}
		}else{
            $.ajax({
				url: "edit_ad.php",
				type: "post",
				data: formData,
				processData: false,
				contentType: false,
				dataType: 'text',
				beforeSend:function() {
					tips.loading('show');
				},
				success: function(data) {

					tips.loading('hide');
					var rs  = eval('('+data+')');
					var msg = rs.message;

					if(rs.status==1){
					   //tips.notify(msg, 'success', 600, 'ftsucai-name', 'top', 'center');
					   window.location.href='adlist.php';
					}else{
					   tips.notify(msg, 'danger', 200);
					}
				},
				error: function(data) {
					tips.notify('服务器异常,请稍后再试~', 'danger', 200);
				}
			});
		}
	});
</script>
</body>
</html>