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.BookDAO;
import com.chengxusheji.domain.Book;
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 BookAction extends ActionSupport {

/*Book类字段photoBook参数接收*/
	 private File photoBookFile;
	 private String photoBookFileFileName;
	 private String photoBookFileContentType;
	 public File getPhotoBookFile() {
		return photoBookFile;
	}
	public void setPhotoBookFile(File photoBookFile) {
		this.photoBookFile = photoBookFile;
	}
	public String getPhotoBookFileFileName() {
		return photoBookFileFileName;
	}
	public void setPhotoBookFileFileName(String photoBookFileFileName) {
		this.photoBookFileFileName = photoBookFileFileName;
	}
	public String getPhotoBookFileContentType() {
		return photoBookFileContentType;
	}
	public void setPhotoBookFileContentType(String photoBookFileContentType) {
		this.photoBookFileContentType = photoBookFileContentType;
	}
    /*界面层需要查询的属性: 图书条形码*/
    private String barcode;
    public void setBarcode(String barcode) {
        this.barcode = barcode;
    }
    public String getBarcode() {
        return this.barcode;
    }

    /*界面层需要查询的属性: 图书名称*/
    private String bookName;
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
    public String getBookName() {
        return this.bookName;
    }

    /*界面层需要查询的属性: 图书所在类别*/
    private BookType bookType;
    public void setBookType(BookType bookType) {
        this.bookType = bookType;
    }
    public BookType getBookType() {
        return this.bookType;
    }

    /*界面层需要查询的属性: 出版日期*/
    private String publishDate;
    public void setPublishDate(String publishDate) {
        this.publishDate = publishDate;
    }
    public String getPublishDate() {
        return this.publishDate;
    }

    /*当前第几页*/
    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 String barcodes;
    public String getBarcodes() {
		return barcodes;
	}
	public void setBarcodes(String barcodes) {
		this.barcodes = barcodes;
	}
    /*当前查询的总记录数目*/
    private int recordNumber;
    public void setRecordNumber(int recordNumber) {
        this.recordNumber = recordNumber;
    }
    public int getRecordNumber() {
        return recordNumber;
    }

    /*业务层对象*/
    @Resource BookDAO bookDAO;

    @Resource BookTypeDAO bookTypeDAO;
    /*待操作的Book对象*/
    private Book book;
    public void setBook(Book book) {
        this.book = book;
    }
    public Book getBook() {
        return this.book;
    }

    /*ajax添加Book信息*/
    @SuppressWarnings("deprecation")
    public void ajaxAddBook() throws IOException, JSONException {
    	String message = "";
    	boolean success = false;
        /*验证图书条形码是否已经存在*/
        String barcode = book.getBarcode();
        Book db_book = bookDAO.GetBookByBarcode(barcode);
        if(null != db_book) {
        	message = "该图书条形码已经存在!";
        	writeJsonResponse(success, message);
        	return ;
        }
        try {
            BookType bookType = bookTypeDAO.GetBookTypeByBookTypeId(book.getBookType().getBookTypeId());
            book.setBookType(bookType);
            String path = ServletActionContext.getServletContext().getRealPath("/upload"); 
            /*处理图片上传*/
            String photoBookFileName = ""; 
       	 	if(photoBookFile != null) {
       	 		InputStream is = new FileInputStream(photoBookFile);
       			String fileContentType = this.getPhotoBookFileContentType();
       			if(fileContentType.equals("image/jpeg")  || fileContentType.equals("image/pjpeg"))
       				photoBookFileName = UUID.randomUUID().toString() +  ".jpg";
       			else if(fileContentType.equals("image/gif"))
       				photoBookFileName = UUID.randomUUID().toString() +  ".gif";
       			else {
       				message = "上传图片格式不正确!";
       				writeJsonResponse(success, message);
       				return ;
       			}
       			File file = new File(path, photoBookFileName);
       			OutputStream os = new FileOutputStream(file);
       			byte[] b = new byte[1024];
       			int bs = 0;
       			while ((bs = is.read(b)) > 0) {
       				os.write(b, 0, bs);
       			}
       			is.close();
       			os.close();
       	 	}
            if(photoBookFile != null)
            	book.setPhotoBook("upload/" + photoBookFileName);
            else
            	book.setPhotoBook("upload/NoImage.jpg");
            bookDAO.AddBook(book);
            success = true;
            writeJsonResponse(success, message); 
        } catch (Exception e) {
            e.printStackTrace();
            message = "Book添加失败!";
            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();
	}

    /*查询Book信息*/
    public void ajaxQueryBook() throws IOException, JSONException {
        if(page == 0) page = 1;
        if(barcode == null) barcode = "";
        if(bookName == null) bookName = "";
        if(publishDate == null) publishDate = "";
        if(rows != 0) bookDAO.setRows(rows);
        List<Book> bookList = bookDAO.QueryBookInfo(barcode, bookName, bookType, publishDate, page);
        /*计算总的页数和总的记录数*/
        bookDAO.CalculateTotalPageAndRecordNumber(barcode, bookName, bookType, publishDate);
        /*获取到总的页码数目*/
        totalPage = bookDAO.getTotalPage();
        /*当前查询条件下总记录数*/
        recordNumber = bookDAO.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(Book book:bookList) {
			JSONObject jsonBook = new JSONObject();
			jsonBook.accumulate("barcode", book.getBarcode());
			jsonBook.accumulate("bookName", book.getBookName());
			jsonBook.accumulate("bookType", book.getBookType().getBookTypeName());
			jsonBook.accumulate("price", book.getPrice());
			jsonBook.accumulate("count", book.getCount());
			jsonBook.accumulate("publish", book.getPublish());
			jsonBook.accumulate("publishDate", book.getPublishDate().length()>19?book.getPublishDate().substring(0,19):book.getPublishDate());
			jsonBook.accumulate("photoBook", book.getPhotoBook());
			jsonArray.put(jsonBook);
		}
		jsonObj.accumulate("rows", jsonArray);
		out.println(jsonObj.toString());
		out.flush();
		out.close();
    }

    /*查询Book信息*/
    public void ajaxQueryAllBook() throws IOException, JSONException {
        List<Book> bookList = bookDAO.QueryAllBookInfo();        HttpServletResponse response=ServletActionContext.getResponse();
        response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		//将要被返回到客户端的对象
		JSONArray jsonArray = new JSONArray();
		for(Book book:bookList) {
			JSONObject jsonBook = new JSONObject();
			jsonBook.accumulate("barcode", book.getBarcode());
			jsonBook.accumulate("bookName", book.getBookName());
			jsonArray.put(jsonBook);
		}
		out.println(jsonArray.toString());
		out.flush();
		out.close();
    }

    /*查询要修改的Book信息*/
    public void ajaxModifyBookQuery() throws IOException, JSONException {
        /*根据主键barcode获取Book对象*/
        Book book = bookDAO.GetBookByBarcode(barcode);

        HttpServletResponse response=ServletActionContext.getResponse(); 
        response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter(); 
		//将要被返回到客户端的对象 
		JSONObject jsonBook=new JSONObject();
		jsonBook.accumulate("barcode", book.getBarcode());
		jsonBook.accumulate("bookName", book.getBookName());
		jsonBook.accumulate("bookType", book.getBookType().getBookTypeId());
		jsonBook.accumulate("price", book.getPrice());
		jsonBook.accumulate("count", book.getCount());
		jsonBook.accumulate("publish", book.getPublish());
		jsonBook.accumulate("publishDate", book.getPublishDate().length()>19?book.getPublishDate().substring(0,19):book.getPublishDate());
		jsonBook.accumulate("photoBook", book.getPhotoBook());
		out.println(jsonBook.toString()); 
		out.flush();
		out.close();
    };

    /*更新修改Book信息*/
    public void ajaxModifyBook() throws IOException, JSONException{
    	String message = "";
    	boolean success = false;
        try {
            BookType bookType = bookTypeDAO.GetBookTypeByBookTypeId(book.getBookType().getBookTypeId());
            book.setBookType(bookType);
            String path = ServletActionContext.getServletContext().getRealPath("/upload"); 
            /*处理图片上传*/
            String photoBookFileName = ""; 
       	 	if(photoBookFile != null) {
       	 		InputStream is = new FileInputStream(photoBookFile);
       			String fileContentType = this.getPhotoBookFileContentType();
       			if(fileContentType.equals("image/jpeg") || fileContentType.equals("image/pjpeg"))
       				photoBookFileName = UUID.randomUUID().toString() +  ".jpg";
       			else if(fileContentType.equals("image/gif"))
       				photoBookFileName = UUID.randomUUID().toString() +  ".gif";
       			else {
       				message = "上传图片格式不正确!";
       				writeJsonResponse(success, message);
       				return ;
       			}
       			File file = new File(path, photoBookFileName);
       			OutputStream os = new FileOutputStream(file);
       			byte[] b = new byte[1024];
       			int bs = 0;
       			while ((bs = is.read(b)) > 0) {
       				os.write(b, 0, bs);
       			}
       			is.close();
       			os.close();
       			book.setPhotoBook("upload/" + photoBookFileName);
       	 	}
            bookDAO.UpdateBook(book);
            success = true;
            writeJsonResponse(success, message);
        } catch (Exception e) {
            message = "Book修改失败!"; 
            writeJsonResponse(success, message);
       }
   }

    /*删除Book信息*/
    public void ajaxDeleteBook() throws IOException, JSONException {
    	String message = "";
    	boolean success = false;
        try { 
        	String _barcodes[] = barcodes.split(",");
        	for(String _barcode: _barcodes) {
        		bookDAO.DeleteBook(_barcode);
        	}
        	success = true;
        	message = _barcodes.length + "条记录删除成功";
        	writeJsonResponse(success, message);
        } catch (Exception e) { 
            e.printStackTrace();
            message = "删除失败";
            writeJsonResponse(success, message);
        }
    }

    /*跳转到添加Book视图*/
    public String AddView() {
        ActionContext ctx = ActionContext.getContext();
        /*查询所有的BookType信息*/
        List<BookType> bookTypeList = bookTypeDAO.QueryAllBookTypeInfo();
        ctx.put("bookTypeList", bookTypeList);
        return "add_view";
    }

    /*添加Book信息*/
    @SuppressWarnings("deprecation")
    public String AddBook() {
        ActionContext ctx = ActionContext.getContext();
        /*验证图书条形码是否已经存在*/
        String barcode = book.getBarcode();
        Book db_book = bookDAO.GetBookByBarcode(barcode);
        if(null != db_book) {
            ctx.put("error",  java.net.URLEncoder.encode("该图书条形码已经存在!"));
            return "error";
        }
        try {
            if(true) {
            BookType bookType = bookTypeDAO.GetBookTypeByBookTypeId(book.getBookType().getBookTypeId());
            book.setBookType(bookType);
            }
            String path = ServletActionContext.getServletContext().getRealPath("/upload"); 
            /*处理图片上传*/
            String photoBookFileName = ""; 
       	 	if(photoBookFile != null) {
       	 		InputStream is = new FileInputStream(photoBookFile);
       			String fileContentType = this.getPhotoBookFileContentType();
       			if(fileContentType.equals("image/jpeg")  || fileContentType.equals("image/pjpeg"))
       				photoBookFileName = UUID.randomUUID().toString() +  ".jpg";
       			else if(fileContentType.equals("image/gif"))
       				photoBookFileName = UUID.randomUUID().toString() +  ".gif";
       			else {
       				ctx.put("error",  java.net.URLEncoder.encode("上传图片格式不正确!"));
       				return "error";
       			}
       			File file = new File(path, photoBookFileName);
       			OutputStream os = new FileOutputStream(file);
       			byte[] b = new byte[1024];
       			int bs = 0;
       			while ((bs = is.read(b)) > 0) {
       				os.write(b, 0, bs);
       			}
       			is.close();
       			os.close();
       	 	}
            if(photoBookFile != null)
            	book.setPhotoBook("upload/" + photoBookFileName);
            else
            	book.setPhotoBook("upload/NoImage.jpg");
            bookDAO.AddBook(book);
            ctx.put("message",  java.net.URLEncoder.encode("Book添加成功!"));
            return "add_success";
        } catch (Exception e) {
            e.printStackTrace();
            ctx.put("error",  java.net.URLEncoder.encode("Book添加失败!"));
            return "error";
        }
    }

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

    /*查询要修改的Book信息*/
    public String ModifyBookQuery() {
        ActionContext ctx = ActionContext.getContext();
        /*根据主键barcode获取Book对象*/
        Book book = bookDAO.GetBookByBarcode(barcode);

        List<BookType> bookTypeList = bookTypeDAO.QueryAllBookTypeInfo();
        ctx.put("bookTypeList", bookTypeList);
        ctx.put("book",  book);
        return "modify_view";
    }

    /*查询要修改的Book信息*/
    public String FrontShowBookQuery() {
        ActionContext ctx = ActionContext.getContext();
        /*根据主键barcode获取Book对象*/
        Book book = bookDAO.GetBookByBarcode(barcode);

        List<BookType> bookTypeList = bookTypeDAO.QueryAllBookTypeInfo();
        ctx.put("bookTypeList", bookTypeList);
        ctx.put("book",  book);
        return "front_show_view";
    }

    /*更新修改Book信息*/
    public String ModifyBook() {
        ActionContext ctx = ActionContext.getContext();
        try {
            if(true) {
            BookType bookType = bookTypeDAO.GetBookTypeByBookTypeId(book.getBookType().getBookTypeId());
            book.setBookType(bookType);
            }
            String path = ServletActionContext.getServletContext().getRealPath("/upload"); 
            /*处理图片上传*/
            String photoBookFileName = ""; 
       	 	if(photoBookFile != null) {
       	 		InputStream is = new FileInputStream(photoBookFile);
       			String fileContentType = this.getPhotoBookFileContentType();
       			if(fileContentType.equals("image/jpeg") || fileContentType.equals("image/pjpeg"))
       				photoBookFileName = UUID.randomUUID().toString() +  ".jpg";
       			else if(fileContentType.equals("image/gif"))
       				photoBookFileName = UUID.randomUUID().toString() +  ".gif";
       			else {
       				ctx.put("error",  java.net.URLEncoder.encode("上传图片格式不正确!"));
       				return "error";
       			}
       			File file = new File(path, photoBookFileName);
       			OutputStream os = new FileOutputStream(file);
       			byte[] b = new byte[1024];
       			int bs = 0;
       			while ((bs = is.read(b)) > 0) {
       				os.write(b, 0, bs);
       			}
       			is.close();
       			os.close();
            book.setPhotoBook("upload/" + photoBookFileName);
       	 	}
            bookDAO.UpdateBook(book);
            ctx.put("message",  java.net.URLEncoder.encode("Book信息更新成功!"));
            return "modify_success";
        } catch (Exception e) {
            e.printStackTrace();
            ctx.put("error",  java.net.URLEncoder.encode("Book信息更新失败!"));
            return "error";
       }
   }

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

    /*后台导出到excel*/
    public String queryBookOutputToExcel() { 
        if(barcode == null) barcode = "";
        if(bookName == null) bookName = "";
        if(publishDate == null) publishDate = "";
        List<Book> bookList = bookDAO.QueryBookInfo(barcode,bookName,bookType,publishDate);
        ExportExcelUtil ex = new ExportExcelUtil();
        String title = "Book信息记录"; 
        String[] headers = { "图书条形码","图书名称","图书所在类别","图书价格","库存","出版社","出版日期","图书图片"};
        List<String[]> dataset = new ArrayList<String[]>(); 
        for(int i=0;i<bookList.size();i++) {
        	Book book = bookList.get(i); 
        	dataset.add(new String[]{book.getBarcode(),book.getBookName(),book.getBookType().getBookTypeName(),
book.getPrice() + "",book.getCount() + "",book.getPublish(),book.getPublishDate(),book.getPhotoBook()});
        }
        /*
        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="+"Book.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;
    }
}
