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

if (!empty($_POST)){

	if (!check_permission($_SESSION["a_uid"],'messagelist.php',2)){
        $response_arr = array("status" => -1,"message"  => '对不起,您无权限操作!');
		echo json_encode($response_arr);
        exit;
	}

    $msg_id         = intval($_POST["msg_id"]);
    $msg_title      = flc_request($_POST["msg_title"]);
	$titlecolor     = flc_request($_POST["titlecolor"]);
	$msg_content    = flc_request($_POST["msg_content"]);
	$msg_keyword    = flc_request($_POST["msg_keyword"]);
	$msg_demourl    = flc_request($_POST["msg_demourl"]);
	$msg_downurl    = flc_request($_POST["msg_downurl"]);
	
	if ($_POST["msg_integral"]=='' || empty($_POST["msg_integral"])){
	   $msg_integral=0;
	}else{
	   $msg_integral=flc_request($_POST["msg_integral"]);
	}

	$msg_starttime=flc_request($_POST["msg_starttime"]);
	$msg_endtime=flc_request($_POST["msg_endtime"]);
	$msg_status=flc_request($_POST["msg_status"]);
	$msg_order=intval($_POST["msg_order"]);
	$msg_isad=intval($_POST["msg_isad"]);
	   
	if ($msg_starttime=="") $msg_starttime=$getnow;
	if ($msg_endtime=="") $msg_endtime="2099-11-11 00:00:00";
	$categoryid = flc_request($_POST["categoryid"]);
    
	if($categoryid!=''){

		try {
           
           $db->startTrans();

		   $sql="update {$tablepre}message set msg_title='".$msg_title."',msg_titlecolor='".$titlecolor."', msg_content='".$msg_content."',
	             msg_keyword='".$msg_keyword."',msg_demourl='".$msg_demourl."', msg_downurl='".$msg_downurl."', msg_integral='".$msg_integral."', msg_starttime='".$msg_starttime."', msg_endtime='".$msg_endtime."', msg_status='".$msg_status."', msg_order='".$msg_order."',
	             msg_isad='".$msg_isad."' where msg_id=".$msg_id."";
	       $result = $db->exec($sql,true);
		   if (!$result){
              throw new Exception('数据更新失败!');
		   }

           $cateid=explode(",",$categoryid);
		   if (empty($_FILES)){
			   //1.如果没有重新上传图片就取原有图片,然后重新插入图片
			   $strsql  ="select * from {$tablepre}attachmng where msg_id='".$msg_id."'";
			   $attach  =$db->get_row($strsql);
			   $attach_path = $attach['attach_path'];
			   $attach_size = $attach['attach_size'];
			   $attach_ext  = $attach['attach_ext'];
			   $thumbnail_path = $attach['thumbnail_path'];

               $db->exec("delete from {$tablepre}categorymng where msg_id='".$msg_id."'");
			   $db->exec("delete from {$tablepre}attachmng where msg_id='".$msg_id."'"); 

			   foreach ($cateid as $cid){

				   if($cid==0){break;} 
				   $db->exec("insert into {$tablepre}categorymng (category_id,msg_id) values('".$cid."','".$msg_id."')");
				   $db->exec("insert into {$tablepre}attachmng (category_id,msg_id,attach_path,attach_size,attach_ext,thumbnail_path,index_box,addtime) 
							 values('".$cid."','".$msg_id."','".$attach_path."','".$attach_size."','".$attach_ext."','".$thumbnail_path."',1,'".$getnow."')");
			   }

               $response_arr = array("status" => 1,"message"  => '操作成功!'.$result);

		   }else{

                //2.如果有上传新的图片就取新的图片信息,然后重新插入图片
			    $width      = intval($_POST["width"]);         //图片宽度
				$height     = intval($_POST["height"]);        //图片高度

				$Folder=date("Ym",time());                      //按月生成文件夹
				if(!file_exists ("../upload/".$Folder)){
					mkdir("../upload/".$Folder,0777);   
				}
				
				$savedb_url = '/upload/'.$Folder.'/';            //文件入库URL
				$save_path  = '../upload/'.$Folder.'/';          //文件保存目录路径
				//$ext_arr    = array('gif', 'jpg', 'png');        //定义允许上传的文件扩展名	
				$max_size   = $site_filesize;                    //最大文件大小

				$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);              //返回 array 数组的最后一个单元,并将数组 array 的长度减一
				$file_ext   = trim($file_ext);
				$file_ext   = strtolower($file_ext);
				
				if (in_array($file_ext, $ext_arr) === false) { //检查扩展名
					throw new Exception('限传'.$ext_str.'类型');
				}
				$file_path = $save_path . iconv("UTF-8","gb2312",$file_name);

				$pathArray = array("imgsmall");
				if(!file_exists($save_path."/imgsmall")){
					$createResult = createFilePath($save_path,$pathArray);
					if($createResult == false){
						throw new Exception('无法创建文件夹！');
					}
				}

                /*删除原来已上传的图片*/
				include_once("../classes/fileclass.php");
			    $file = new fileoperate();  
			    $sql1="select attach_path,thumbnail_path from {$tablepre}attachmng where msg_id=".$msg_id;
			    $rm = $db->get_all($sql1);
			    if(is_array($rm) && !empty($rm)){
				   foreach ($rm as $r){
					  $file->del_attach("..",$r['attach_path']);
					  $file->del_attach("..",$r['thumbnail_path']);
				   }
			    }
                /**********************/

			    $db->exec("delete from {$tablepre}categorymng where msg_id='".$msg_id."'");
			    $db->exec("delete from {$tablepre}attachmng where msg_id='".$msg_id."'"); 

			    foreach ($cateid as $cid){

				   if($cid==0){break;} 
				   $db->exec("insert into {$tablepre}categorymng (category_id,msg_id) values('".$cid."','".$msg_id."')");
				   $db->exec("insert into {$tablepre}attachmng (category_id,msg_id,attach_path,attach_size,attach_ext,thumbnail_path,index_box,addtime) 
							 values('".$cid."','".$msg_id."','".$savedb_url.$file_name."','".$file_size."','".$file_ext."','".$savedb_url."imgsmall/".$file_name."',1,'".$getnow."')");
			    }

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

					$thumbnail = new ImageResize();	
					$thumbnail->resizeimage($save_path.$file_name,265,350,0,$save_path."imgsmall/".$file_name);    //缩略图片
					$thumbnail->resizeimage($save_path.$file_name,$width,$height,0,$save_path.$file_name);         //原始图片按原尺寸重新生成,防止图片木马

					$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_message.php','".$savedb_url.$file_name."','".$getnow."')";	   
	                $db->exec($sql,true);

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

			    $response_arr = array("status" => 1,"message"  => '操作成功!');
		   }

           $db->commit();

		   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;
	}

}

$id = intval($_GET["id"]);
$sql = "select * from {$tablepre}message where msg_id='".$id."'";
$row = $db->get_row($sql);
if ($row['msg_titlecolor']==''){
   $titlecolor='#333;';
}else{
   $titlecolor=$row['msg_titlecolor'];
}

$sql = "select cm.category_id,c.category_parentid from {$tablepre}categorymng cm 
        inner join category c on cm.category_id=c.category_id 
		inner join {$tablepre}message m on m.msg_id=cm.msg_id where m.msg_id='".$id."'";
$mng = $db->get_all($sql);

foreach($mng as $v){
   $cate_arr[]=$v['category_id'];
}

$category_str = implode(',',$cate_arr);
?>
<!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="messagelist.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="msg_title">信息标题</label>
                    <div class="input-group" style="padding:5px 18px;">
					   <input name="msg_title" type="text" class="form-control" id="msg_title" value="<?php echo $row['msg_title'];?>">
						<div class="input-group-btn">
                           <div class="js-colorpicker input-group colorpicker-element" style="padding:0px;">
	                         <span class="input-group-addon" style="height:38px;border: 1px solid #ebebeb;" title="标题颜色">
							 <i style="background-color: <?php echo $titlecolor;?>"></i></span>
	                         <input class="form-control" type="hidden" id="titlecolor" name="titlecolor" value="<?php echo $row['msg_titlecolor'];?>">
	                       </div>
                        </div>
                    </div>
                  </div>

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

				  <div class="form-group">
                    <label class="col-xs-12" for="msg_downurl">下载地址</label>
                    <div class="col-xs-12">
                      <input class="form-control" type="text" id="msg_downurl" name="msg_downurl" value="<?php echo $row['msg_downurl'];?>">
                    </div>
                  </div>
				  
				  <div class="form-group">
                    <label class="col-xs-12" for="msg_content">内容描述</label>
                    <div class="col-xs-12">
					  <textarea id="content" name="msg_content" class="xheditor-simple" rows="10" cols="80" style="width: 100%">
					  <?php echo $row['msg_content'];?>
					  </textarea>
                    </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="cateid">所属分类</label>
				    <select class="form-control" id="sel" multiple="multiple" size="1">
				<?php
				$sql   = "select * from {$tablepre}category where category_parentid=0 and category_status=1 order by category_order asc"; 
                $cate1 = $db->get_all($sql);
			    foreach ($cate1 as $k1 => $v1){
				?>
					<optgroup label="<?php echo $v1['category_name'];?>">
					<?php
	                  $sql="select * from {$tablepre}category where category_parentid='".$v1['category_id']."' and category_status=1 order by category_order asc"; 
	                  $cate2 = $db->get_all($sql);
					  foreach ($cate2 as $k2 => $v2){
                    ?>
						<option value="<?php echo $v2['category_id'];?>" <?php if (in_array($v2['category_id'],$cate_arr)){?>selected<?php }?>>
						  <?php echo $v2['category_name'];?>
						</option>
					<?php
				      }		
				    ?>
					</optgroup>
                <?php
				}		
				?>
					</select>
					<input type="hidden" name="categoryid" id="categoryid" value="<?php echo $category_str;?>">
                  </div>
                  <div class="form-group">
                    <label class="col-xs-12" for="msg_keyword">关 键 字</label>
                    <div class="col-xs-12">
                      <input class="form-control" type="text" id="msg_keyword" name="msg_keyword" value="<?php echo $row['msg_keyword'];?>">
                    </div>
                  </div>
                  
                  <div class="form-group">
                    <label class="col-xs-12" for="msg_isad">信息分类</label>
					<div class="col-xs-12">
						<label class="ftdms-radio radio-inline radio-primary">
						<input type="radio" name="msg_isad" value="0" <?php if ($row['msg_isad']==0){?>checked<?php }?>><span>素材信息</span>
						</label>
						<label class="ftdms-radio radio-inline radio-primary">
						<input type="radio" name="msg_isad" value="1" <?php if ($row['msg_isad']==1){?>checked<?php }?>><span>广告信息</span>
						</label>
					</div>
                  </div>
                  <div class="form-group">
                    <label class="col-xs-12" for="msg_order">排序(值越大排越前)</label>
                    <div class="col-xs-12">
                      <input class="form-control" type="text" id="msg_order" name="msg_order" value="<?php echo $row['msg_order'];?>">
                    </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="msg_starttime" name="msg_starttime" value="<?php echo $row['msg_starttime'];?>">
	                      <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="msg_endtime" name="msg_endtime" value="<?php echo $row['msg_endtime'];?>">
	                   </div>
                  </div>
                   
                  <div class="form-group">
                    <label class="col-xs-12" for="msg_integral">下载积分</label>
                    <div class="col-xs-12">
                      <input class="form-control" type="text" id="msg_integral" name="msg_integral" value="<?php echo $row['msg_integral'];?>">
                    </div>
                  </div>

                  <div class="form-group">
                    <label class="col-xs-12" for="msg_status">显示状态</label>
					<div class="col-xs-12">
						<label class="ftdms-radio radio-inline radio-primary">
						<input type="radio" name="msg_status" value="1" <?php if ($row['msg_status']==1){?>checked<?php }?>><span>显示</span>
						</label>
						<label class="ftdms-radio radio-inline radio-primary">
						<input type="radio" name="msg_status" value="0" <?php if ($row['msg_status']==0){?>checked<?php }?>><span>隐藏</span>
						</label>
					</div>
                  </div>
                  
                  <div class="form-group">
                    <div class="col-xs-12">
                      <input type="hidden" name="msg_id" id="msg_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/fSelect.js"></script>
<script src="../xheditor/xheditor-1.2.2.min.js"></script>
<script src="../xheditor/zh-cn.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/bootstrap-notify.min.js"></script>
<script src="../js/tips.js"></script>
<script>
$(function(){
    $('.dropdown-menu a').click(function() {
        var field = $(this).data('field') || '';
        $('#titlecolor').val(field);
        $('#select-btn').html($(this).text() + ' <span class="caret"></span>');
    });

    $('#color').colorpicker({
        color: "#333333"//初始化颜色
    });

	//载入多选分类值
	$('#sel').fSelect();
	
});
</script>
<script type="text/javascript">
    //获取项目路径
	var basePath = getContextPath();
	function getContextPath() {
		var pathName = window.document.location.pathname;
		var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
		return projectName;
	}

	//var url = location.pathname;

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

		var formData      = new FormData();
		var categoryid    = $("#sel").GetValues(",");

        var msg_id        = $("#msg_id").val();
		var msg_title     = $("#msg_title").val();
		var titlecolor    = $("#titlecolor").val();
		var msg_demourl   = $("#msg_demourl").val();
		var msg_downurl   = $("#msg_downurl").val();
		var msg_content   = $("#content").val();
		msg_content       = msg_content.replace(/\s*/g,"");
		var msg_keyword   = $("#msg_keyword").val();
		var msg_isad      = $("input[name='msg_isad']:checked").val();
		var msg_order     = $("#msg_order").val();
		var msg_starttime = $("#msg_starttime").val();
		var msg_endtime   = $("#msg_endtime").val();
		var msg_integral  = $("#msg_integral").val();
		var msg_status    = $("input[name='msg_status']:checked").val();

		if (msg_title==''){
			tips.notify('信息标题不能为空', 'warning', 200);
			return false;
		}else if (categoryid==''){
			tips.notify('信息分类至少要选一个', 'warning', 200);
			return false;
		}

        formData.append("categoryid", categoryid);
		formData.append("msg_id", msg_id);
		formData.append("msg_title", msg_title);
		formData.append("titlecolor", titlecolor);
		formData.append("msg_demourl", msg_demourl);
		formData.append("msg_downurl", msg_downurl);
		formData.append("msg_content", msg_content);
		formData.append("msg_keyword", msg_keyword);
		formData.append("msg_isad", msg_isad);
		formData.append("msg_order", msg_order);
		formData.append("msg_starttime", msg_starttime);
		formData.append("msg_endtime", msg_endtime);
		formData.append("msg_integral", msg_integral);
		formData.append("msg_status", msg_status);

        //如果修改时有重新上传图片,则加入图片信息
        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>680 || width<265){
						pic_err="上传的图片宽度范围只能在265~680之间";
						tips.notify(pic_err, 'danger', 200);
						return false;
					}

					formData.append("width", width);
					formData.append("height", height);
					//console.log("宽度：" + width + " 高度：" + height);

					$.ajax({
						url: basePath + "/edit_message.php",
						type: "post",
						data: formData,
						processData: false, // 告诉jQuery不要去处理发送的数据
						contentType: false, // 告诉jQuery不要去设置Content-Type请求头
						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='messagelist.php';
							}else{
							   tips.notify(msg, 'danger', 200);
							}
						},
						error: function(data) {
							tips.notify('服务器异常,请稍后再试~', 'danger', 200);
						}
					});
				}
			}
        }else{
            $.ajax({
				url: basePath + "/edit_message.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='messagelist.php';
					}else{
					   tips.notify(msg, 'danger', 200);
					}
				},
				error: function(data) {
					tips.notify('服务器异常,请稍后再试~', 'danger', 200);
				}
			});
		}

	});
</script>
</body>
</html>