package com.chengxusheji.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.UUID;
import org.apache.struts2.ServletActionContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.chengxusheji.utils.ExportExcelUtil;
import com.chengxusheji.dao.BookTypeDAO;
import com.chengxusheji.domain.BookType;

/**
 * 双鱼林SSH2_EasyUI图书管理系统  需要更多系统可以去我网站查询(各种开发语言都有)
 * 作者：双鱼林          QQ:254540457  网站: www.shuangyulin.com
 * Email: wangjianlin1985@126.com
 * Copyright (c) 2016-2050 All rights reserved.
 */


@Controller @Scope("prototype")
public class BookTypeAction extends ActionSupport {

    /*当前第几页*/
    private int page;
    public void setPage(int page) {
        this.page = page;
    }
    public int getPage() {
        return page;
    }

    /*每页显示多少条数据*/
    private int rows;
    public void setRows(int rows) {
    	this.rows = rows;
    }
    public int getRows() {
    	return this.rows;
    }
    /*一共多少页*/
    private int totalPage;
    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }
    public int getTotalPage() {
        return totalPage;
    }

    private int bookTypeId;
    public void setBookTypeId(int bookTypeId) {
        this.bookTypeId = bookTypeId;
    }
    public int getBookTypeId() {
        return bookTypeId;
    }

    /*要删除的记录主键集合*/
    private String bookTypeIds;
    public String getBookTypeIds() {
		return bookTypeIds;
	}
	public void setBookTypeIds(String bookTypeIds) {
		this.bookTypeIds = bookTypeIds;
	}
    /*当前查询的总记录数目*/
    private int recordNumber;
    public void setRecordNumber(int recordNumber) {
        this.recordNumber = recordNumber;
    }
    public int getRecordNumber() {
        return recordNumber;
    }

    /*业务层对象*/
    @Resource BookTypeDAO bookTypeDAO;

    /*待操作的BookType对象*/
    private BookType bookType;
    public void setBookType(BookType bookType) {
        this.bookType = bookType;
    }
    public BookType getBookType() {
        return this.bookType;
    }

    /*ajax添加BookType信息*/
    @SuppressWarnings("deprecation")
    public void ajaxAddBookType() throws IOException, JSONException {
    	String message = "";
    	boolean success = false;
        try {
            bookTypeDAO.AddBookType(bookType);
            success = true;
            writeJsonResponse(success, message); 
        } catch (Exception e) {
            e.printStackTrace();
            message = "BookType添加失败!";
            writeJsonResponse(success, message);
        }
    }

    /*向客户端输出操作成功或失败信息*/
	private void writeJsonResponse(boolean success,String message)
			throws IOException, JSONException {
		HttpServletResponse response=ServletActionContext.getResponse(); 
		response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter(); 
		//将要被返回到客户端的对象 
		JSONObject json=new JSONObject();
		json.accumulate("success", success);
		json.accumulate("message", message);
		out.println(json.toString());
		out.flush(); 
		out.close();
	}

    /*查询BookType信息*/
    public void ajaxQueryBookType() throws IOException, JSONException {
        if(page == 0) page = 1;
        if(rows != 0) bookTypeDAO.setRows(rows);
        List<BookType> bookTypeList = bookTypeDAO.QueryBookTypeInfo(page);
        /*计算总的页数和总的记录数*/
        bookTypeDAO.CalculateTotalPageAndRecordNumber();
        /*获取到总的页码数目*/
        totalPage = bookTypeDAO.getTotalPage();
        /*当前查询条件下总记录数*/
        recordNumber = bookTypeDAO.getRecordNumber();
        HttpServletResponse response=ServletActionContext.getResponse();
        response.setContentType("text/json;charset=UTF-8"); 
		PrintWriter out = response.getWriter();
		//将要被返回到客户端的对象
		JSONObject jsonObj=new JSONObject();
		jsonObj.accumulate("total", recordNumber);
		JSONArray jsonArray = new JSONArray();
		for(BookType bookType:bookTypeList) {
			JSONObject jsonBookType = new JSONObject();
			jsonBookType.accumulate("bookTypeId", bookType.getBookTypeId());
			jsonBookType.accumulate("bookTypeName", bookType.getBookTypeName());
			jsonBookType.accumulate("days", bookType.getDays());
			jsonArray.put(jsonBookType);
		}
		jsonObj.accumulate("rows", jsonArray);
		out.println(jsonObj.toString());
		out.flush();
		out.close();
    }

    /*查询BookType信息*/
    public void ajaxQueryAllBookType() throws IOException, JSONException {
        List<BookType> bookTypeList = bookTypeDAO.QueryAllBookTypeInfo();        HttpServletResponse response=ServletActionContext.getResponse();
        response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		//将要被返回到客户端的对象
		JSONArray jsonArray = new JSONArray();
		for(BookType bookType:bookTypeList) {
			JSONObject jsonBookType = new JSONObject();
			jsonBookType.accumulate("bookTypeId", bookType.getBookTypeId());
			jsonBookType.accumulate("bookTypeName", bookType.getBookTypeName());
			jsonArray.put(jsonBookType);
		}
		out.println(jsonArray.toString());
		out.flush();
		out.close();
    }

    /*查询要修改的BookType信息*/
    public void ajaxModifyBookTypeQuery() throws IOException, JSONException {
        /*根据主键bookTypeId获取BookType对象*/
        BookType bookType = bookTypeDAO.GetBookTypeByBookTypeId(bookTypeId);

        HttpServletResponse response=ServletActionContext.getResponse(); 
        response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter(); 
		//将要被返回到客户端的对象 
		JSONObject jsonBookType=new JSONObject();
		jsonBookType.accumulate("bookTypeId", bookType.getBookTypeId());
		jsonBookType.accumulate("bookTypeName", bookType.getBookTypeName());
		jsonBookType.accumulate("days", bookType.getDays());
		out.println(jsonBookType.toString()); 
		out.flush();
		out.close();
    };

    /*更新修改BookType信息*/
    public void ajaxModifyBookType() throws IOException, JSONException{
    	String message = "";
    	boolean success = false;
        try {
            bookTypeDAO.UpdateBookType(bookType);
            success = true;
            writeJsonResponse(success, message);
        } catch (Exception e) {
            message = "BookType修改失败!"; 
            writeJsonResponse(success, message);
       }
   }

    /*删除BookType信息*/
    public void ajaxDeleteBookType() throws IOException, JSONException {
    	String message = "";
    	boolean success = false;
        try { 
        	String _bookTypeIds[] = bookTypeIds.split(",");
        	for(String _bookTypeId: _bookTypeIds) {
        		bookTypeDAO.DeleteBookType(Integer.parseInt(_bookTypeId));
        	}
        	success = true;
        	message = _bookTypeIds.length + "条记录删除成功";
        	writeJsonResponse(success, message);
        } catch (Exception e) { 
            e.printStackTrace();
            message = "删除失败";
            writeJsonResponse(success, message);
        }
    }

    /*跳转到添加BookType视图*/
    public String AddView() {
        ActionContext ctx = ActionContext.getContext();
        return "add_view";
    }

    /*添加BookType信息*/
    @SuppressWarnings("deprecation")
    public String AddBookType() {
        ActionContext ctx = ActionContext.getContext();
        try {
            bookTypeDAO.AddBookType(bookType);
            ctx.put("message",  java.net.URLEncoder.encode("BookType添加成功!"));
            return "add_success";
        } catch (Exception e) {
            e.printStackTrace();
            ctx.put("error",  java.net.URLEncoder.encode("BookType添加失败!"));
            return "error";
        }
    }

    /*前台查询BookType信息*/
    public String FrontQueryBookType() {
        if(page == 0) page = 1;
        List<BookType> bookTypeList = bookTypeDAO.QueryBookTypeInfo(page);
        /*计算总的页数和总的记录数*/
        bookTypeDAO.CalculateTotalPageAndRecordNumber();
        /*获取到总的页码数目*/
        totalPage = bookTypeDAO.getTotalPage();
        /*当前查询条件下总记录数*/
        recordNumber = bookTypeDAO.getRecordNumber();
        ActionContext ctx = ActionContext.getContext();
        ctx.put("bookTypeList",  bookTypeList);
        ctx.put("totalPage", totalPage);
        ctx.put("recordNumber", recordNumber);
        ctx.put("page", page);
        return "front_query_view";
    }

    /*查询要修改的BookType信息*/
    public String ModifyBookTypeQuery() {
        ActionContext ctx = ActionContext.getContext();
        /*根据主键bookTypeId获取BookType对象*/
        BookType bookType = bookTypeDAO.GetBookTypeByBookTypeId(bookTypeId);

        ctx.put("bookType",  bookType);
        return "modify_view";
    }

    /*查询要修改的BookType信息*/
    public String FrontShowBookTypeQuery() {
        ActionContext ctx = ActionContext.getContext();
        /*根据主键bookTypeId获取BookType对象*/
        BookType bookType = bookTypeDAO.GetBookTypeByBookTypeId(bookTypeId);

        ctx.put("bookType",  bookType);
        return "front_show_view";
    }

    /*更新修改BookType信息*/
    public String ModifyBookType() {
        ActionContext ctx = ActionContext.getContext();
        try {
            bookTypeDAO.UpdateBookType(bookType);
            ctx.put("message",  java.net.URLEncoder.encode("BookType信息更新成功!"));
            return "modify_success";
        } catch (Exception e) {
            e.printStackTrace();
            ctx.put("error",  java.net.URLEncoder.encode("BookType信息更新失败!"));
            return "error";
       }
   }

    /*删除BookType信息*/
    public String DeleteBookType() {
        ActionContext ctx = ActionContext.getContext();
        try { 
            bookTypeDAO.DeleteBookType(bookTypeId);
            ctx.put("message",  java.net.URLEncoder.encode("BookType删除成功!"));
            return "delete_success";
        } catch (Exception e) { 
            e.printStackTrace();
            ctx.put("error",  java.net.URLEncoder.encode("BookType删除失败!"));
            return "error";
        }
    }

    /*后台导出到excel*/
    public String queryBookTypeOutputToExcel() { 
        List<BookType> bookTypeList = bookTypeDAO.QueryBookTypeInfo();
        ExportExcelUtil ex = new ExportExcelUtil();
        String title = "BookType信息记录"; 
        String[] headers = { "图书类别","类别名称","可借阅天数"};
        List<String[]> dataset = new ArrayList<String[]>(); 
        for(int i=0;i<bookTypeList.size();i++) {
        	BookType bookType = bookTypeList.get(i); 
        	dataset.add(new String[]{bookType.getBookTypeId() + "",bookType.getBookTypeName(),bookType.getDays() + ""});
        }
        /*
        OutputStream out = null;
		try {
			out = new FileOutputStream("C://output.xls");
			ex.exportExcel(title,headers, dataset, out);
		    out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		*/
		HttpServletResponse response = null;//创建一个HttpServletResponse对象 
		OutputStream out = null;//创建一个输出流对象 
		try { 
			response = ServletActionContext.getResponse();//初始化HttpServletResponse对象 
			out = response.getOutputStream();//
			response.setHeader("Content-disposition","attachment; filename="+"BookType.xls");//filename是下载的xls的名，建议最好用英文 
			response.setContentType("application/msexcel;charset=UTF-8");//设置类型 
			response.setHeader("Pragma","No-cache");//设置头 
			response.setHeader("Cache-Control","no-cache");//设置头 
			response.setDateHeader("Expires", 0);//设置日期头  
			String rootPath = ServletActionContext.getServletContext().getRealPath("/");
			ex.exportExcel(rootPath,title,headers, dataset, out);
			out.flush();
		} catch (IOException e) { 
			e.printStackTrace(); 
		}finally{
			try{
				if(out!=null){ 
					out.close(); 
				}
			}catch(IOException e){ 
				e.printStackTrace(); 
			} 
		}
		return null;
    }
}
