<?php
include_once("htui_header.php");

/*
include_once("../common/config.php");
include_once("../common/publicfun.php");
include_once("../classes/dbclass.php");
include_once("../conn.php");
include_once("../common/checkpost.php");
include_once("check_master.php");
*/

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

if (!empty($_FILES) && !empty($_POST)){

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

    $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"]);
	//$msg_poster=getLoginName();
	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"]);

	$width      = intval($_POST["width"]);         //图片宽度
	$height     = intval($_POST["height"]);        //图片高度

	$strsql  ="select * from {$tablepre}message where msg_title='".$msg_title."'";
    $rs      =$db->get_row($strsql);
    if (!empty($rs)){
	   $response_arr = array("status" => -1,"message"  => '请不要重复提交！');
       echo json_encode($response_arr);
       exit;
    }


    $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) { //检查扩展名
		$response_arr = array("status" => -1,"message"  => '限传'.$ext_str.'类型');
        echo json_encode($response_arr);
        exit;
	}
	$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){	
			$response_arr = array("status" => -1,"message"  => '无法创建文件夹！');
            echo json_encode($response_arr);
            exit;
		}
	}

	if($categoryid!=''){

		try {
           
           $db->startTrans();

		   $sql = "insert into {$tablepre}message (msg_title,msg_titlecolor,msg_content,msg_keyword,msg_demourl,msg_integral,
	                msg_poster,msg_downurl,msg_starttime,msg_endtime,msg_status,msg_order,msg_isad) 
                    values('".$msg_title."','".$titlecolor."','".$msg_content."','".$msg_keyword."','".$msg_demourl."','".$msg_integral."',
		            '".$_SESSION["a_uid"]."','".$msg_downurl."','".$msg_starttime."','".$msg_endtime."','".$msg_status."',
			        '".$msg_order."','".$msg_isad."')";	   
	       $result = $db->exec($sql,true);
		   if (!$result){
              throw new Exception('数据写入失败!');
		   }

		   $cateid=explode(",",$categoryid);
		   foreach ($cateid as $cid){

			   if($cid==0){break;} 
			   
			   $strsql = "select * from {$tablepre}message where msg_title='".$msg_title."'";
			   $rows1  = $db->get_row($strsql);
			   $msgid  = $rows1['msg_id'];

			   $db->exec("insert into {$tablepre}categorymng (category_id,msg_id) values('".$cid."','".$msgid."')");

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

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

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

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

}
?>
<!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">
						<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: #333;"></i></span>
	                         <input class="form-control" type="hidden" id="titlecolor" name="titlecolor" value="">
	                       </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" placeholder="演示地址..">
                    </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" placeholder="下载地址..">
                    </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%"></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 echo $v2['category_name'];?></option>
					<?php
				      }		
				    ?>
					</optgroup>
                <?php
				}		
				?>
					</select>
					<input type="hidden" name="categoryid" id="categoryid" value="">
                  </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" placeholder="关键字..">
                    </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" checked><span>素材信息</span>
						</label>
						<label class="ftdms-radio radio-inline radio-primary">
						<input type="radio" name="msg_isad" value="1"><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="1">
                    </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" placeholder="从">
	                      <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" placeholder="至">
	                   </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="0">
                    </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" checked><span>显示</span>
						</label>
						<label class="ftdms-radio radio-inline radio-primary">
						<input type="radio" name="msg_status" value="0"><span>隐藏</span>
						</label>
					</div>
                  </div>
                  
                  <div class="form-group">
                    <div class="col-xs-12">
                      <!--<button class="btn btn-primary" type="submit" id="submit">提交</button>-->
					  <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();
	
});
/*
$("#submit").click(function(){

	var cateid = $("#sel").GetValues(",");
	//var catetxt = $("#sel").GetTexts(",");
	$('#categoryid').val(cateid);

    
    $.post("add_message.php", $("#form").serialize(), function(data) {
        alert(data);
    });
	

	//$("#submit").submit();

});

*/
</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 catetxt = $("#sel").GetTexts(",");
	    //var categoryid  = $('#categoryid').val(cateid);

		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();
		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 ($("#location").val()==''){
			tips.notify('上传图片不能为空', 'warning', 200);
			return false;
		}else if (categoryid==''){
			tips.notify('信息分类至少要选一个', 'warning', 200);
			return false;
		}

        formData.append("categoryid", categoryid);
		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);
		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 + "/add_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', 1000, 'ftsucai-name', 'top', 'center');
						}else{
						   tips.notify(msg, 'danger', 200);
						}
					},
					error: function(data) {
						tips.notify('服务器异常,请稍后再试~', 'danger', 200);
					}
				});
			}
		}
        
		/*
		$.ajax({
			url: basePath + "/add_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('提交成功', 'success', 1000, 'ftsucai-name', 'top', 'center');
				}else{
				   tips.notify('提交失败,请稍后再试~', 'danger', 200);
				}
			},
			error: function(data) {
				tips.notify('服务器异常,请稍后再试~', 'danger', 200);
			}
		});
		*/
	});
</script>
</body>
</html>