增刪改查mybatis用法

//PolicyManageController.java


package com.chinasoft.biz.policyManage.controller;


import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;


import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


import com.chinasoft.biz.common.entity.PolicyManageInfo;
import com.chinasoft.biz.policyManage.service.PolicyManageService;
import com.chinasoft.util.GsonUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;


/**
 * @author lishuying
 *
 */
@Controller
@RequestMapping("/policyManage")
public class PolicyManageController {
@Resource
PolicyManageService policyManageService;
Gson gson = new GsonBuilder().create();
Gson gsonFor = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
// 加載列表
@RequestMapping(value = "/getPolicyManageInfo")
public void getPolicyManageInfo(PolicyManageInfo policyManageInfo, HttpServletResponse response) {
JsonObject jo = policyManageService.getAllPolicyManageInfo(policyManageInfo);
try {
response.getWriter().write(GsonUtil.toJson(jo));
} catch (IOException e) {
e.printStackTrace();
}
}


// 單列刪除
@RequestMapping(value = "/deletePolicyManageById")
@ResponseBody
public int deletePolicyManageById(int id) {
return policyManageService.deletePolicyManageById(id);
}


// 批量刪除
@RequestMapping("/deleteInBatch")
@ResponseBody
public int deleteInBatch(String ids) {
if (ids == null || ids.isEmpty()) {
return 0;
}
return policyManageService.deleteInBatch(ids);
}


// 顯示編輯內容
@RequestMapping("/showEditInfoById")
@ResponseBody
public void showEditInfoById(int id, HttpServletResponse response) {
try {
PolicyManageInfo result = policyManageService.getEditInfoById(id);
response.getWriter().println(gsonFor.toJson(result));
} catch (IOException e) {
e.printStackTrace();
}
}


// 編輯中保存按鈕
@RequestMapping("/savePolicyManageById")
@ResponseBody
public int savePolicyManageById(PolicyManageInfo policyManageInfo, HttpServletRequest request,
HttpServletResponse response) {
boolean flagFile;
int flagUpdate = 0;
String title = policyManageInfo.getTitle();
String contentUrlName = policyManageInfo.getContentUrl();
if(null == contentUrlName || contentUrlName.isEmpty()){
return policyManageService.updatePolicyManageById(policyManageInfo);
}else{
String contentUrl = contentUrlName.substring(contentUrlName.lastIndexOf("."), contentUrlName.length());
String newName = title + contentUrl;
contentUrl = "upload/policyManageInfo/" + title + contentUrl;
policyManageInfo.setContentUrl(contentUrl);

String tempPath = request.getServletContext().getRealPath("/");
String savePath = tempPath.substring(0, tempPath.lastIndexOf("webapps")) + "upload/policyManageInfo";

File saveFile = new File(savePath, contentUrlName);
flagFile = saveFile.renameTo(new File(savePath, newName));
if(flagFile){
flagUpdate =  policyManageService.updatePolicyManageById(policyManageInfo);
}
return  flagUpdate;
}
}


// 將上傳文件放在臨時目錄裏
@RequestMapping("/uploadFile")
public void uploadFile(@RequestParam("uploadName") CommonsMultipartFile file, HttpServletRequest request,
HttpServletResponse response) {
// 得到上傳文件的保存目錄,將上傳的文件存放於WEB-INF目錄下,不允許外界直接訪問,保證上傳文件的安全
String tempPath = request.getServletContext().getRealPath("/");
String savePath = tempPath.substring(0, tempPath.lastIndexOf("webapps")) + "upload/policyManageInfo";
File saveFile = new File(savePath, file.getOriginalFilename());
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), saveFile);
response.getWriter().write(1);
} catch (IOException e) {
e.printStackTrace();
}

}


// 新增政策
@RequestMapping("/addPolicyManageInfo")
@ResponseBody
public int addPolicyManageInfo(PolicyManageInfo policyManageInfo, HttpServletRequest request,
HttpServletResponse response) throws IOException {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");//設置日期格式
boolean flagFile;
int flagInsert = 0;
String title = policyManageInfo.getTitle();
String contentUrlName = policyManageInfo.getContentUrl();
if(null == contentUrlName || contentUrlName.isEmpty()){
return policyManageService.insertPolicyManage(policyManageInfo);
}else{
String contentUrl = contentUrlName.substring(contentUrlName.lastIndexOf("."), contentUrlName.length());
// String newName = title + df.format(new Date()) + contentUrl;
// contentUrl = "upload/policyManageInfo/" + title + df.format(new Date()) + contentUrl;
String newName = title + contentUrl;
contentUrl = "upload/policyManageInfo/" + title + contentUrl;
policyManageInfo.setContentUrl(contentUrl);

String tempPath = request.getServletContext().getRealPath("/");
String savePath = tempPath.substring(0, tempPath.lastIndexOf("webapps")) + "upload/policyManageInfo";

File saveFile = new File(savePath, contentUrlName);
flagFile = saveFile.renameTo(new File(savePath, newName));
if(flagFile){
flagInsert =  policyManageService.insertPolicyManage(policyManageInfo);
}
return  flagInsert;
}

}


// 下載
@RequestMapping("/downloadPolicyManage")
public void downloadPolicyManage(HttpServletRequest request, HttpServletResponse response, int id) {
try {
PolicyManageInfo policyManageInfo = policyManageService.getEditInfoById(id);
String tempPath = request.getServletContext().getRealPath("/");
String savePath = tempPath.substring(0, tempPath.lastIndexOf("webapps"));


String fileName = policyManageInfo.getContentUrl();
String fileNameNew = fileName.substring(("upload/policyManageInfo/").length(),fileName.length());
byte[] fileByte = getByteBlob(savePath, fileName);
ByteArrayInputStream in = new ByteArrayInputStream(fileByte);
fileNameNew = URLEncoder.encode(fileNameNew, "UTF-8");
response.reset();
response.setContentType("multipart/form-data;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileNameNew);
ServletOutputStream outputStream = response.getOutputStream();
int b;
while ((b = in.read()) != -1) {
outputStream.write(b);
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}


public byte[] getByteBlob(String savePath, String fileName) {
File saveFile = new File(savePath, fileName);
InputStream in = null;
byte[] fileByte = null;
try {
in = new FileInputStream(saveFile);
fileByte = new byte[in.available()];
in.read(fileByte);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}


return fileByte;
}


}








//PolicyManageServiceImpl.java 


package com.chinasoft.biz.policyManage.service;


import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;


import javax.annotation.Resource;


import org.springframework.stereotype.Service;


import com.chinasoft.biz.common.entity.DataDictionary;
import com.chinasoft.biz.common.entity.Dept;
import com.chinasoft.biz.common.entity.PolicyManageInfo;
import com.chinasoft.biz.dataManage.dao.DeptDaoMapper;
import com.chinasoft.biz.policyManage.dao.PolicyManageMapper;
import com.chinasoft.framework.common.BaseService;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;


/**
 * @author lishuying
 *
 */
@Service("policyManageServiceImpl")
public class PolicyManageServiceImpl extends BaseService implements PolicyManageService {
@Resource
PolicyManageMapper policyManageMapper;
@Resource
DeptDaoMapper deptDaoMapper;
@Override
public JsonObject getAllDataBank(DataDictionary dataDictionary) {
int page = dataDictionary.getPage();
int rows = dataDictionary.getRows();
PageHelper.startPage(page, rows);
List<DataDictionary> list = policyManageMapper.getAllCityData(dataDictionary);
JsonObject jo = convertTableData(list, "yyyy-MM-dd HH:mm:ss");
return jo;
}


@Override
public int addCityData(String site, int type) {
DataDictionary data = new DataDictionary();
data.setText(site);
data.setType(type);
data.setCreateTime(new Timestamp(System.currentTimeMillis()));
boolean flag = policyManageMapper.insertCityData(data) > 0;
if (flag) {
return 1;
} else {
return 0;
}
}


@Override
public int deleteCityDataById(int id) {
boolean flag = policyManageMapper.deleteCityDataById(id) > 0;
if (flag) {
return 1;
} else {
return 0;
}
}


@Override
public JsonObject getAllPolicyManageInfo(PolicyManageInfo policyManageInfo) {
int page = policyManageInfo.getPage();
int rows = policyManageInfo.getRows();
PageHelper.startPage(page, rows);
List<PolicyManageInfo> list = policyManageMapper.getAllPolicyManageInfo(policyManageInfo);
JsonObject jo = convertTableData(list, "yyyy-MM-dd HH:mm:ss");
return jo;
}


@Override
public int deletePolicyManageById(int id) {
boolean flag = policyManageMapper.deletePolicyManageById(id) > 0;
if (flag) {
return 1;
} else {
return 0;
}
}


@Override
public int deleteInBatch(String ids) {
if (ids == null) {
return 0;
}
String[] list = ids.split(",");
List<Integer> idList = new ArrayList<Integer>();
for (int i = 0; i < list.length; i++) {
idList.add(Integer.valueOf(list[i]));
}
boolean flag = policyManageMapper.deleteInBatch(idList) > 0;
if (flag) {
return 1;
} else {
return 0;
}
}


@Override
public PolicyManageInfo getEditInfoById(int id) {
PolicyManageInfo policyManageInfo = policyManageMapper.getEditInfoById(id);
return policyManageInfo;
}


@Override
public int updatePolicyManageById(PolicyManageInfo policyManageInfo) {
int deptId = policyManageInfo.getDeptbuId();
Dept dept = deptDaoMapper.getDeptDuById(deptId);
policyManageInfo.setDeptbuName(dept.getName());
boolean flag = policyManageMapper.updatePolicyManageById(policyManageInfo) > 0;
if (flag) {
return 1;
} else {
return 0;
}
}


@Override
public int insertPolicyManage(PolicyManageInfo policyManageInfo) {
int deptId = policyManageInfo.getDeptbuId();
Dept dept = deptDaoMapper.getDeptDuById(deptId);
policyManageInfo.setDeptbuName(dept.getName());
boolean flag = policyManageMapper.insertPolicyManage(policyManageInfo) > 0;
if (flag) {
return 1;
} else {
return 0;
}
}

@Override
public JsonArray getDataBankByType(int type) {
JsonArray ja = new JsonArray();
List<DataDictionary> list = policyManageMapper.getDataBankByType(type);
for (int i = 0; i < list.size(); i++) {
JsonObject jo  = new JsonObject();
jo.addProperty("id", list.get(i).getId());
jo.addProperty("name", list.get(i).getText());
ja.add(jo);
}
return ja;
}


}




//PolicyManageMapper


package com.chinasoft.biz.policyManage.dao;


import java.util.List;


import javax.annotation.Resource;


import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;


import com.chinasoft.biz.common.entity.DataDictionary;
import com.chinasoft.biz.common.entity.PolicyManageInfo;


/**
 * @author lishuying
 *
 */
@Repository("policyManageMapper")
public interface PolicyManageMapper {

public List<DataDictionary> getPostOrArea();


// 數據字典中查找所有城市
public List<DataDictionary> getAllCityData(@Param("data") DataDictionary dataDictionary);


// 數據字典中新增城市
public int insertCityData(DataDictionary data);


// 數據字典中刪除城市
public int deleteCityDataById(int id);


// 招聘政策•查詢
public List<PolicyManageInfo> getAllPolicyManageInfo(@Param("data") PolicyManageInfo policyManageInfo);


// 招聘政策•單行刪除
public int deletePolicyManageById(int id);


// 招聘政策•批量刪除
public int deleteInBatch(List<Integer> idList);

// 招聘政策•顯示編輯內容
public PolicyManageInfo getEditInfoById(int id);

// 招聘政策•保存編輯內容
public int updatePolicyManageById(PolicyManageInfo policyManageInfo);

// 招聘政策•新增
public int insertPolicyManage(PolicyManageInfo policyManageInfo);

public List<DataDictionary> getDataBankByType(int type);


}




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.chinasoft.biz.policyManage.dao.PolicyManageMapper">
<resultMap id="DataDictionaryBean" type="com.chinasoft.biz.common.entity.DataDictionary">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="text" property="text" jdbcType="VARCHAR"/>
<result column="value" property="value" jdbcType="VARCHAR"/>
<result column="type" property="type"  jdbcType="INTEGER"/>
<result column="create_time" property="createTime"  jdbcType="TIMESTAMP"/>
</resultMap>

<resultMap id="PolicyManageInfoBean" type="com.chinasoft.biz.common.entity.PolicyManageInfo">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="title" property="title" jdbcType="VARCHAR"/>
<result column="publish_type" property="publishType" jdbcType="INTEGER"/>
<result column="content" property="content" jdbcType="VARCHAR"/>
<result column="content_url" property="contentUrl" jdbcType="VARCHAR"/>
<result column="deptbu_id" property="deptbuId" jdbcType="INTEGER"/>
<result column="deptbu_name" property="deptbuName" jdbcType="VARCHAR"/>
<result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
<result column="creator_id" property="creatorId" jdbcType="VARCHAR"/>
<result column="creator" property="creator" jdbcType="VARCHAR"/>
<result column="updator" property="updator" jdbcType="VARCHAR"/>
<result column="updator_id" property="updatorId"  jdbcType="VARCHAR"/>
<result column="update_time" property="updateTime"  jdbcType="TIMESTAMP"/>
<result column="remark" property="remark" jdbcType="VARCHAR"/>
</resultMap>

<insert id="insertPolicyManage"  parameterType="PolicyManageInfo">
insert into policy_manage_info
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="title != null">
title,
</if>
<if test="publishType != null">
publish_type,
</if>
<if test="content != null">
content,
</if>
<if test="contentUrl != null">
content_url,
</if>
<if test="deptbuId != null">
deptbu_id,
</if>
<if test="deptbuName != null">
deptbu_name,
</if>
<if test="creatorId != null">
creator_id,
</if>
<if test="creator != null">
creator,
</if>
<if test="updator != null">
updator,
</if><if test="updatorId != null">
updator_id,
</if>
<if test="remark != null">
remark,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id},
</if>
<if test="title != null">
#{title},
</if>
<if test="publishType != null">
#{publishType},
</if>
<if test="content != null">
#{content},
</if>
<if test="contentUrl != null">
#{contentUrl},
</if>
<if test="deptbuId != null">
#{deptbuId},
</if>
<if test="deptbuName != null">
#{deptbuName},
</if>
<if test="creatorId != null">
#{creatorId},
</if>
<if test="creator != null">
#{creator},
</if>
<if test="updator != null">
#{updator},
</if><if test="updatorId != null">
#{updatorId},
</if>
<if test="remark != null">
#{remark},
</if>
</trim>
</insert>

<update id="updatePolicyManageById"  parameterType="PolicyManageInfo">
update policy_manage_info
<trim prefix="set" suffixOverrides=",">
<if test="title != null">
title=#{title},
</if>
<if test="publishType != null">
publish_type=#{publishType},
</if>
<if test="content != null">
content=#{content},
</if>
<if test="contentUrl != null">
content_url=#{contentUrl},
</if>
<if test="deptbuId != null">
deptbu_id=#{deptbuId},
</if>
<if test="deptbuName != null">
deptbu_name=#{deptbuName},
</if>
<if test="updator != null">
updator=#{updator},
</if>
<if test="updatorId != null">
updator_id=#{updatorId},
</if>
<if test="remark != null">
remark=#{remark},
</if>
</trim>
where 
id=#{id}
</update>

<select id="getEditInfoById" resultMap="PolicyManageInfoBean" parameterType="int">
SELECT 
*
FROM 
policy_manage_info
WHERE 
id = #{id}
</select>

<delete id="deleteInBatch" parameterType="java.util.List" >
delete from policy_manage_info where id in 
 <foreach collection="list" item="idList" open="(" close=")" separator=",">  
            #{idList}  
        </foreach> 
</delete>

<delete id="deletePolicyManageById" parameterType="int" >
delete from policy_manage_info where id=#{id}
</delete>

<select id="getAllPolicyManageInfo" resultMap="PolicyManageInfoBean" parameterType="PolicyManageInfo">
SELECT * FROM policy_manage_info
WHERE 1=1
<if test=" data.title !='' and data.title !=null">
    and title like concat(concat('%',#{data.title}),'%')
  </if>
  <if test="data.publishType !='' and data.publishType !=null ">
    and publish_type=#{data.publishType}
  </if>
  <if test="data.content !='' and data.content !=null ">
    and content like concat(concat('%',#{data.content}),'%')
  </if>
  <if test="data.deptbuName !='' and data.deptbuName !=null ">
    and deptbu_name like concat(concat('%',#{data.deptbuName}),'%')
  </if>
  <if test="data.creatorId !='' and data.creatorId !=null ">
    and creator_id like concat(concat('%',#{data.creatorId}),'%')
  </if>
  <if test="data.creator !='' and data.creator !=null ">
    and creator like concat(concat('%',#{data.creator}),'%')
  </if>
  <choose>
     <when test="data.sidx == 'title'.toString()">
      order bytitle ${data.sord}
     </when>
     <when test="data.sidx == 'publishType'.toString()">
      order bypublish_type ${data.sord}
     </when>
     <when test="data.sidx == 'content'.toString()">
      order bycontent ${data.sord}
     </when>
     <when test="data.sidx == 'deptbuName'.toString()">
      order bydeptbu_name ${data.sord}
     </when>
     <when test="data.sidx == 'creatorId'.toString()">
      order bycreator_id ${data.sord}
     </when>
     <when test="data.sidx == 'creator'.toString()">
      order bycreator ${data.sord}
     </when>
     <when test="data.sidx == 'updateTime'.toString()">
      order byupdate_time ${data.sord}
     </when>
      <when test="data.sidx == 'remark'.toString()">
      order byremark ${data.sord}
     </when>
     <otherwise>
    order by ${data.sidx}  ${data.sord}
     </otherwise>
    </choose>
</select>

<select id="getAllCityDataInfo" resultMap="DataDictionaryBean" parameterType="DataDictionary">
       select * from data_bank where type = 1
</select>

<select id="getAllCityData" resultMap="DataDictionaryBean" parameterType="DataDictionary">
       select * from data_dictionary  where  1 = 1
  <if test=" data.text !='' and data.text !=null ">
    and text like concat(concat('%',#{data.text}),'%')
  </if>
  <if test="data.type != 0 and data.type !=null ">
    and type=#{data.type}
  </if>
    order by ${data.sidx} ${data.sord}
</select>

<insert id="insertCityData"  parameterType="DataDictionary" useGeneratedKeys="true" keyProperty="id">
insert into data_dictionary
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
    </if>
    <if test="text != null">
text,
    </if>
<if test="type != null">
type,
</if>
<if test="createTime != null">
create_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id},
    </if>
    <if test="text != null">
#{text},
    </if>
<if test="type != null">
#{type},
</if>
<if test="createTime != null">
#{createTime},
</if>
</trim>
</insert>

<delete id="deleteCityDataById" parameterType="Integer">
delete from data_dictionary where id=#{id}
</delete>

<select id="getDataBankByType" resultMap="DataDictionaryBean" parameterType="Integer">
       select * from data_bank  where  type=#{type}
</select>


<select id="getPostOrArea" resultMap="DataDictionaryBean">
select * from data_bank
</select>

</mapper>  





<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>


<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>政策</title>
<%@ include file="../../../../framework/icss_framework/base/jsp/include/include.jsp" %>
<script type="text/javascript" src="<%=basePath%>jsp/views/policyManage/js/policyManage.js"></script>
</head>


<body>
<div  id="loadDiv">
<div class="ConditionP">
<div class="publicConditionDiv">
<span>主題:</span>
<input type="text" class="" id="title" name ="title"  maxlength='64'>
   </div>
   <div class="publicConditionDiv">
<span>制度內容:</span>
<input type="text" class="" id="content" name ="content"  maxlength='2000'>
   </div>
   <div class="publicConditionDiv">
<span>部門名稱:</span>
<input type="text" class="" id="deptbu_name" name ="deptbu_name"  maxlength='64'>
   </div>
   <div class="publicConditionDiv">
<span>工號:</span>
<input type="text" class="" id="creator_id" name ="creator_id"  maxlength='16'>
   </div>
   <div class="publicConditionDiv">
<span>創建者:</span>
<input type="text" class="" id="creator" name ="creator"  maxlength='16'>
   </div>
<div class="publicConditionDiv">
<button class="btn btn-add"  οnclick="searchButton();" ><i class="fa fa-search"></i>查詢</button>
<button class="btn btn-nose"  οnclick="resetButton();" ><i class="fa fa-refresh"></i>重置</button>
</div>
</div>
<div id="showListDiv">
<div align="right" style="margin-bottom: 10px;">
<button class="btn btn-nose"  οnclick="addButton();" ><i class="fa fa-plus"></i>新增</button>
<button class="btn btn-nose"  οnclick="deleteInBatchesButton();" ><i class="fa fa-times"></i>批量刪除</button>
<!-- <button class="publicButtonB"  οnclick="uploadButton();" >導入</button>
<button class="publicButtonB"  οnclick="exportButton();" >導出</button> -->
</div>
</div>
<div>
<table id="policyManageId" class=""></table>
   <div id='policyManagePager'></div>
</div>
</div>


<script id="editDiv" type="text/html">
<table class="editDepOrCityT1"  cellspacing="0" cellpadding="0" id="dataTable" style="width:550; height:100">
<tr><td><span class="redStar">*</span>主題:</td><td><input type="text" class="" id="titleEdit" name ="titleEdit" placeholder="請輸入主題" maxlength='16' οnblur="checkTitle(this.id);" οnfοcus="checktips(this.id);"><span id="titleEditError" style="color: red"></span></td></tr>
<tr><td><span class="redStar">*</span>發佈類型:</td>
<td>
<select class="timeS" id="publishTypeEdit">
<option value="-1">請選擇</option>
<option value="1">制度</option>
<option value="2">政策</option>
</select>
</td>
</tr>
           <tr id="fileIdEdit"><td>上傳內容:</td>
<td>
<input type="file" id="fileId" name="uploadName" size="20" style="margin:8px 0"  οnchange="fileChange(this);" >
<input type="hidden" id="fileName_id">
<input type="text" style="display:none">
<input type="button"  οnclick="downloadPolicyManage()" style="display:none">
</td>
</tr>
<tr class="fileIdEditTr" style="display:none" id="displayNoneEdit"><td><span class="redStar">*</span>上傳內容:</td>
<td >
<input type="text" class="" id="contentUrlEdit" name="contentUrlEdit">
<button  οnclick="downloadPolicyManage();">下載 </button>
<input type="hidden" id="rowId">
</td>
</tr>
<tr id="fileIdEditWorld"><td></td>
<td><label id="upload_type" style="position: relative;left:2px;margin-top:-6px;color: #999;font-weight:100;height: 20px;width: 100%">
僅支持.docx或者.pdf(2007以上版本Microsoft Office Word),且最大不能超過3M
</label>
</td>
</tr>

<tr style="display:none" id="upload_suggess">
<td></td>
<td><label  style="color: red">注意:重新導入文件會覆蓋您之前的文件</label></td>
</tr>
<tr><td><span class="redStar">*</span>所屬業務線名稱:</td>
<td>
<select class="timeS" id="deptbuNameEdit" name ="deptbuNameEdit"><option  value="-1">請選擇</option></select>
</td>
</tr>


<tr class="contentEditTr"><td>發佈內容:</td>
<td><textarea id="contentEdit" style="border-radius: 4px;border: 1px solid #d2d2d2;width:100%" name="contentEdit" cols ="50" rows = "10" placeholder="請輸入內容" οnblur="checkContent(this.id);" οnfοcus="checktips(this.id);" maxlength='5000'></textarea>
<span id="contentEditError" style="color: red"></span></td></tr>

<tr id="creatorIdEditTr"><td><span class="redStar">*</span>創建者工號</td><td><input type="text" class="" id="creatorIdEdit" name ="creatorIdEdit" placeholder="請輸入創建者工號" maxlength='64' disabled><span id="creatorIdEditError" style="color: red"></span></td></tr>
<tr id="creatorEditTr"><td><span class="redStar">*</span>創建者名稱</td><td><input type="text" class="" id="creatorEdit" name ="creatorEdit" placeholder="請輸入創建者名稱" maxlength='64' disabled><span id="creatorEditError" style="color: red"></span></td></tr>
<tr id="updateTimeEditTr"><td><span class="redStar">*</span>修改時間:</td><td><input type="text" class="" id="updateTimeEdit" name ="updateTimeEdit" placeholder="請輸入修改時間" maxlength='64' disabled><span id="updateTimeEditError" style="color: red"></span></td></tr>
<tr><td>備註:</td><td>
                  <textarea  id="remarkEdit" name ="remarkEdit"  style="border-radius: 4px;border: 1px solid #d2d2d2;width:100%"  cols ="50" rows = "5" placeholder="請輸入備註"maxlength='64' ></textarea> 
</table>
</script>










</body>
</html>






$(function(){
//加載表格
loadtable(colName, colModel);
});
//下載
function downloadPolicyManage(){
var id = $("#rowId").val();
window.location.href = basePath + "policyManage/downloadPolicyManage?id="+ id;
}
function downloadPolicyManageTable(object){
var id = object.id;
window.location.href = basePath + "policyManage/downloadPolicyManage?id="+ id;
}




//查看詳情
function showPolicyManageById(object){
var id = object.id;
var temp = {};
var html = template("editDiv", temp);
$(html).dialog({
title : "管理制度與政策",
modal: true,
closeOnClickOutside : false,
onBeforeShow: function () {
initUpload(id);
// refreshUploadStatues();
},

});
loadDeptBu();
$("#fileIdEdit").hide();
$("#fileIdEditWorld").hide();
$("#displayNoneEdit").show();
$("#displayNoneEdit").removeAttr("style");
$("#titleEdit").attr("disabled","disabled");
$("#publishTypeEdit").attr("disabled","disabled");
$("#contentUrlEdit").attr("disabled","disabled");
$("#contentEdit").attr("disabled","disabled");
$("#deptbuNameEdit").attr("disabled","disabled");
$("#remarkEdit").attr("disabled","disabled");
$("#fileIdEditTr").show();
$("#contentEditTr").show();
$.ajax({          
   url: basePath + 'policyManage/showEditInfoById?random=' + Math.random(),
   type: "POST",  
   data: {
    "id":id
   },  
   success: function (data) {
    if (data) {
    data = JSON.parse(data);
    if(null == data || "" == data || undefined == data){
  zeroModal.error('沒有此條數據');
  return false;
    }
    $("#rowId").val(id);
    $("#titleEdit").val(data["title"]);
    $("#publishTypeEdit").val(data["publishType"]);
   
    if(null == data["contentUrl"] || "" == data["contentUrl"] || undefined == data["contentUrl"]){
    $(".fileIdEditTr").hide();
    }else{
    $("#contentUrlEdit").val(data["contentUrl"]);
    }
    if(null == data["content"] || "" == data["content"] || undefined == data["content"]){
    $(".contentEditTr").hide();
    }else{
    $("#contentEdit").text(data["content"]);
    }
    $("#deptbuNameEdit").val(data["deptbuId"]);
   
    $("#creatorIdEdit").val(data["creatorId"]);
    $("#creatorEdit").val(data["creator"]);
//     $("#updatorIdEdit").val(data["updatorId"]);
//     $("#updatorEdit").val(data["updator"]);
    $("#updateTimeEdit").val(data["updateTime"]);
    $("#remarkEdit").val(data["remark"]);
}
},
error : function(){
zeroModal.error('沒有查詢到數據');
}
})


}




//新增政策
function addButton(){
var title = $("#titleEdit").val();
var temp = {};
var html = template("editDiv", temp);
$(html).dialog({
title : "新增管理制度與政策",
modal: true,
closeOnClickOutside : false,
onBeforeShow: function () {
initUpload(title);
// refreshUploadStatues();
},
buttons : {
"確定" : function() {
var list= {};
var title = $("#titleEdit").val();
if(null == title || "" == title || undefined == title){
zeroModal.error('請輸入主題');
return false;
}
var publishType = $("#publishTypeEdit").val();
if(null == publishType || "" == publishType || undefined == publishType || "-1" == publishType){
zeroModal.error('請選擇發佈類型');
return false;
}
var deptbuName = $("#deptbuNameEdit").val();
if(null == deptbuName || "" == deptbuName || undefined == deptbuName || "-1" == deptbuName){
zeroModal.error('請選擇所屬業務線名稱');
return false;
}
var content = $("#contentEdit").val();
var fileId = $("#fileId").val();
var fileNameId = $("#fileName_id").val();
if(fileId !=null && fileId != ""){
if(fileNameId !=null && fileNameId != ""){
list.contentUrl = fileNameId;
}else{
zeroModal.error('請檢查您是否點擊上傳操作!');
return false;
}
}else if(null == content || "" == content || undefined == content ){
zeroModal.error('請選擇您的上傳文件或填寫制度內容!');
return false;
}
list.title = $("#titleEdit").val();
list.publishType = $("#publishTypeEdit").val();
list.content = $("#contentEdit").val();
list.deptbuId = $("#deptbuNameEdit").val();
// list.deptbuName = $("#deptbuNameEdit").val();
list.creatorId = user.workNum;
list.creator = user.name;
list.updatorId = user.workNum;
list.updator = user.name;
list.remark = $("#remarkEdit").val();
$.ajax({          
       url: basePath + 'policyManage/addPolicyManageInfo?random=' + Math.random(),
       type: "POST",  
       dataType: "json",  
       data: list,
       success: function (data) { 
        if(data==1){
        zeroModal.success("新增成功!");
        reloadTable({condition : null});
        $(this).dialog("close"); 
        }else{
        zeroModal.error("新增失敗!");
        }
    },
   });
},
"取消" : function() {
$(this).dialog("close"); 
}
}
});
$("#creatorIdEditTr").hide();
$("#creatorEditTr").hide();
$("#updateTimeEditTr").hide();
loadDeptBu();
}






//顯示編輯內容
function showEditInfoById(cellvalue){
$.ajax({          
      url: basePath + 'policyManage/showEditInfoById?random=' + Math.random(),
      type: "POST",  
      data: {
      "id":cellvalue
      },  
      success: function (data) {
      if (data) {
      data = JSON.parse(data);
      if(null == data || "" == data || undefined == data){
    zeroModal.error('沒有此條數據');
    return false;
    }
      $("#titleEdit").val(data["title"]);
      $("#publishTypeEdit").val(data["publishType"]);
      $("#contentEdit").text(data["content"]);
      $("#contentUrlEdit").val(data["contentUrl"]);
      $("#deptbuNameEdit").val(data["deptbuId"]);
      $("#creatorIdEdit").val(data["creatorId"]);
      $("#creatorEdit").val(data["creator"]);
      $("#updatorIdEdit").val(data["updatorId"]);
      $("#updatorEdit").val(data["updator"]);
      $("#updateTimeEdit").val(data["updateTime"]);
     
      $("#remarkEdit").val(data["remark"]);
  }
  },
  error : function(){
  zeroModal.error('沒有查詢到數據');
  }
  })
var temp = {};
var html = template("editDiv", temp);
$(html).dialog({
title : "編輯信息",
modal: true,
closeOnClickOutside : false,
onBeforeShow: function () {
initUpload();
// refreshUploadStatues();
},
buttons : {
"確定" : function() {
var list= {};
var title = $("#titleEdit").val();
if(null == title || "" == title || undefined == title){
zeroModal.error('請輸入主題');
return false;
}
var publishType = $("#publishTypeEdit").val();
if(null == publishType || "" == publishType || undefined == publishType || "-1" == publishType){
zeroModal.error('請選擇發佈類型');
return false;
}
var deptbuName = $("#deptbuNameEdit").val();
if(null == deptbuName || "" == deptbuName || undefined == deptbuName || "-1" == deptbuName){
zeroModal.error('請選擇所屬業務線名稱');
return false;
}
var content = $("#contentEdit").val();
var fileId = $("#fileId").val();
var fileNameId = $("#fileName_id").val();
if(fileId !=null && fileId != ""){
if(fileNameId !=null && fileNameId != ""){
list.contentUrl = fileNameId;
}else{
zeroModal.error('請檢查您是否點擊上傳操作!');
return false;
}
}else if(null == content || "" == content || undefined == content ){
zeroModal.error('請選擇您的上傳文件或填寫制度內容!');
return false;
}
list.id = cellvalue;
list.title = $("#titleEdit").val();
list.publishType = $("#publishTypeEdit").val();
list.content = $("#contentEdit").val();
list.deptbuId = $("#deptbuNameEdit").val();
list.updatorId = user.workNum;
list.updator = user.name;
list.remark = $("#remarkEdit").val();
$.ajax({          
       url: basePath + 'policyManage/savePolicyManageById?random=' + Math.random(),
       type: "POST",  
       dataType: "json",  
       data: list,
       success: function (data) { 
        if(data==1){
        zeroModal.success("編輯成功!");
        reloadTable({condition : null});
        $(this).dialog("close"); 
        }else{
        zeroModal.error("編輯失敗!");
        }
    },
   });
},
"取消" : function() {
$(this).dialog("close"); 
}
}
});
loadDeptBu();
  

}


//上傳簡歷
function initUpload(title) {
$("#fileId").fileinput(
{
uploadUrl : basePath + "policyManage/uploadFile?random="
+ Math.random(),
showUpload : true,
showPreview : false,
showRemove : false,
uploadAsync : true,
showCaption : true,
autoReplace : true,
browseClass : "btn btn-primary", // 按鈕樣式 ,
language : 'zh',
// maxFileCount: 10,
enctype : 'multipart/form-data',
allowedFileExtensions : [ "docx","pdf" ],
maxFileSize : 1024 * 3
// 單位kb
}).on('filepreupload', function(event, data, previewId, index) {
$("#fileName_id").val(data.filenames[0]);
});
}
function fileChange(target) {
  var fileSize = 0;         
  if ( !target.files) {     
    var filePath = target.value;     
    var fileSystem = new ActiveXObject("Scripting.FileSystemObject");        
    var file = fileSystem.GetFile (filePath);     
    fileSize = file.Size;    
  } else {   
  if(target.value != ""){
  fileSize = target.files[0].size;     
  }
   }   
 
   var name=target.value;
   var fileName = name.substring(name.lastIndexOf(".")+1).toLowerCase();
   if(fileName !="docx" && fileName !="pdf" ){
  zeroModal.alert("請選擇word.docx或者pdf格式文件上傳!");
       target.value="";
       return false;
   }
   var size = fileSize / 1024;    
   if(size>3000){  
  zeroModal.alert("附件不能大於3M");
       target.value="";
       return false;
   }



//取消按鈕
function cancelEditBtn(){
$("#editDiv").hide();
$("#loadDiv").show();
}


function reloadTable(postData){
$("#policyManageId").jqGrid('clearGridData');  //清空表格
$("#policyManageId").jqGrid('setGridParam',{  // 重新加載數據
postData: postData,
datatype:"json",
mtype:"post",
}).trigger("reloadGrid");
}


//查詢
function searchButton(){
num_status =1;
var title = $("#title").val();
var content = $("#content").val();
var deptbuName = $("#deptbu_name").val();
var creatorId = $("#creator_id").val();
var creator = $("#creator").val();
policyManageInfo = {};
policyManageInfo["title"] = title ;
policyManageInfo["content"] = content;
policyManageInfo["deptbuName"] = deptbuName;
policyManageInfo["creatorId"] = creatorId;
policyManageInfo["creator"] = creator;
$("#policyManageId").jqGrid('clearGridData');  //清空表格
$("#policyManageId").jqGrid('setGridParam',{  // 重新加載數據
postData: policyManageInfo,
datatype:"json",
mtype:"post",
}).trigger("reloadGrid");
}


//重置
function resetButton(postData){
num_status =0;
$("#title").val("");
$("#content").val("");
$("#deptbu_name").val("");
$("#creator_id").val("");
$("#creator").val("");
policyManageInfo = {};
policyManageInfo["title"] = "" ;
policyManageInfo["content"] = "";
policyManageInfo["deptbuName"] = "";
policyManageInfo["creatorId"] = "";
policyManageInfo["creator"] = "";
$("#policyManageId").jqGrid('clearGridData');  //清空表格
$("#policyManageId").jqGrid('setGridParam',{  // 重新加載數據
postData: policyManageInfo,
datatype:"json",
mtype:"post",
}).trigger("reloadGrid");

}


//批量刪除
function deleteInBatchesButton(){
var ids = $("#policyManageId").jqGrid('getGridParam','selarrrow');
if(null == ids || ids == ''){
zeroModal.alert("未選刪除信息,請選擇需要刪除的信息.");
}else{
zeroModal.confirm("確定要刪除所選定數據信息", function(){
$.ajax({
type : 'POST',
dataType : 'json',
url : basePath + 'policyManage/deleteInBatch?random=' + Math.random(),
data : {
"ids" : ids.toString()
},
success: function (data) { 
if(data==1){
        zeroModal.success("批量刪除成功!");
        reloadTable({condition : null});
        }else if(data==0){
        zeroModal.error("批量刪除失敗!");
        }
},
error : function(){
zeroModal.error("批量刪除失敗!");
}
});
})

}

}
//刪除
function deleteRow(cellvalue){
var rowData = $("#policyManageId").jqGrid("getRowData",cellvalue);
zeroModal.confirm("確定要刪除主題"+rowData.title, function(){
$.ajax({          
       url: basePath + 'policyManage/deletePolicyManageById?random=' + Math.random(),
       type: "POST",  
       dataType: "json",  
       data: {
        "id":cellvalue
       },  
       success: function (data) { 
        if(data==1){
        zeroModal.success("刪除成功!");
        reloadTable({condition : null});
        }else if(data==0){
        zeroModal.error("刪除失敗!");
        }
    }
   });

});
}


//加載列表
function loadtable(colName, colModel){
$("#policyManageId").jqGrid({
datatype: "json",
  mtype:'post',
  postData:{},
  url: basePath +'policyManage/getPolicyManageInfo?random=' + Math.random(),
  multiselect:true,
  height: true,
  autowidth:true,
  colNames: colName,
  colModel: colModel,
  sortable:true,
  sortname:'update_time',
  sortorder:'desc',
  viewrecords:true,
  rowNum:20,
  rowList:[20,40,80],
  pager:'#policyManagePager', //分頁渲染對象
  pgbuttons: true,
pginput:true,
// onSelectRow: function(rowid, status){  
// showQuestionBank(rowid);
// } ,
loadComplete: function(){
var re_records = $("#policyManageId").getGridParam('records');

if(num_status == 1&&(re_records == 0 || re_records == null)){
if($("#norecords11").html() ==null ){
           $("#policyManageId").parent().append("</pre><div id=\"norecords11\" style='text-align:center;color:red;font-size: 14px;height: 80px;background: #fff;line-height: 80px'>抱歉,沒有查到符合你條件的數據,請重新輸入條件查詢!</div><pre>");
       }
$("#norecords11").show();
num_status=0;
}else{//如果存在記錄,則隱藏提示信息。
$("#norecords11").hide();
}
},
//  caption: "用戶管理信息",
  altRows:false,
  jsonReader: {
          root: "rows",//記錄列表
          records: "records",//總記錄數
          page: "page", //當前頁碼
          total: "total", //總頁數
          repeatitems: false
   }
});
}


var num_status;
var colName = ['主題','發佈類型','發佈內容','部門名稱','文件','創建者工號','創建者名稱','備註','更新時間','操作'];
var colModel = [
{
name:'title',
index:'title',
width:"150",
align:"center",
sorttype:"string",
formatter: function (cellvalue, options, rowObject) {
//  return "<span id='"+rowObject.id+"' οnclick='showQuestionBank("+cellvalue+"\)' >"+cellvalue+"</span>";  
 return "<span οnclick='showPolicyManageById(" + JSON.stringify(rowObject) +"\)' >"+cellvalue+" </span>"; 
}
},
{
name:'publishType',
index:'publishType',
width:"100",
align:"center",
sorttype:"int",
formatter: function (cellvalue) {
var flag = "";
if(cellvalue ==1){
flag = "制度";
}else if(cellvalue ==2){
flag = "政策";
}
return flag;
}
},
{
name:'content',
index:'content',
width:"100",
align:"center",
sorttype:"string"
},
{
name:'deptbuName',
index:'deptbuName',
width:"100",
align:"center",
sorttype:"string"
},
{
name:'contentUrl',
index:'contentUrl',
width:"100",
align:"center",
sorttype:"string",
formatter: function (cellvalue, options, rowObject) {
return "<span οnclick='downloadPolicyManageTable(" + JSON.stringify(rowObject) +"\)' >"+cellvalue+" </span>";
}
},
{
name:'creatorId',
index:'creatorId',
width:"100",
align:"center",
sorttype:"string"
},

{
name:'creator',
index:'creator',
width:"100",
align:"center",
sorttype:"string"
},
{
name:'remark',
index:'remark',
width:"100",
align:"center",
sorttype:"string"
},
{
name:'updateTime',
index:'updateTime',
width:"100",
align:"center",
},
{
name:'id',
index:'id',
width:"100",
align:"center",
key:true,
sortable: false,
formatter: function (cellvalue) {
var html = "";
html += "<span title='編輯' οnclick='showEditInfoById("+cellvalue+"\)'><i class='fa fa-pencil tableIcon p1'></i></span>";
html += "<span title='刪除' οnclick='deleteRow("+cellvalue+"\)'><i class='fa fa-times tableIcon d1'></i></span>";
return html;
}
},
];


function checkTitle(id){
var title = $("#"+id).val().trim();
if( title== null||title ==""){
$("#"+id+"Error").text("主題不能爲空");
}else{
$("#"+id+"Error").text("");
return true;
}
}
function checkContent(id){
var content = $("#"+id).val().trim();
if( content== null||title ==""){
$("#"+id+"Error").text("製作內容不能爲空");
}else{
$("#"+id+"Error").text("");
return true;
}
}
function checktips(id){
document.getElementById(id+"Error").innerHTML="";
}


function loadDeptBu(){
$.ajax({
async:false,
type : "POST",
dataType : 'json',
url : basePath + "dept/getDeptBylevel?random=" + Math.random(),
data:{},
async: false,
success : function(data) {
if (data) {
var html = "<option  value='-1'>請選擇</option>";
$.each(data, function(i, trObj){
html += "<option  value='"+trObj.id+"'>"+trObj.name+"</option>";
});
$("#deptbuNameEdit").empty();
$('#deptbuNameEdit').append(html);
}
},
error : function(){
zeroModal.error('沒有查詢到數據');
}
});
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章