package com.service;


import com.jfinal.aop.Before;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.model.Book;
import com.model.BookDetail;
import com.model.BookPlus;
import com.tools.ISBNTools;
import com.utils.CommonUtils;
import org.apache.commons.lang3.StringUtils;

import java.sql.SQLException;
import java.util.*;

/**
 * 图书
 * 2018-10-23
 * zj
 */
/*
     1> 增加一本图书通过扫描条形码和ISBN去资源库带出本书相关信息
     2> 保存书本信息需要保存三张表 t_book,t_book_plus,t_book_detail,其中t_book_plus为书本附加信息（可不填写，但需要保存增加的书本记录）
     3> 同时增加新书时，需要判断该书是否重复，重复时保存复本
 */
public class BookService {

	public Log logger = Log.getLog(BookService.class);
	public static final BookService me = new BookService();
	private Book dao = new Book().dao();
	private BookPlus plusdao = new BookPlus().dao();
	private BookDetail detaildao = new BookDetail().dao();

	public Book findById(int id){
		return dao.findById(id);
	}

	public Record findBookInfoById(int id){
		return Db.findFirst("select b.id 'bean.id',b.bookno 'bean.bookno',b.isbn 'bean.isbn',(select count(1) from t_book_detail where bookid = b.id) 'bean.booknum',b.title 'bean.title',bp.bltitle 'beanPlus.bltitle',bp.subtitle 'beanPlus.subtitle',b.authorworkmodeid 'bean.authorworkmodeid',b.authorguobieid 'bean.authorguobieid',b.author 'bean.author',bp.otherauthor 'beanPlus.otherauthor'\n" +
				",bp.workmodeid 'beanPlus.workmodeid',bp.guobieid 'beanPlus.guobieid',b.publisher 'bean.publisher',b.publishaddress 'bean.publishaddress',b.publishdate 'bean.publishdate',b.edition 'bean.edition'\n" +
				",b.price 'bean.price',bp.sizeid 'beanPlus.sizeid',bp.id 'beanPlus.id',bp.filesurl 'beanPlus.filesurl',bp.languageid 'beanPlus.languageid',bp.totalpages 'beanPlus.totalpages',bp.bindingid 'beanPlus.bindingid'\n" +
				",bp.congshuming 'beanPlus.congshuming',bp.congshuauthor 'beanPlus.congshuauthor',b.newsource 'bean.newsource',b.keyword 'bean.keyword',bp.fuzhu 'beanPlus.fuzhu'\n" +
				",b.typecode 'bean.typecode',b.shucihao 'bean.shucihao',bp.juanci 'beanPlus.juanci',bp.ceci 'beanPlus.ceci' " +
				" from t_book b,t_book_plus bp where bp.bookid=b.id and b.id=? ",id);
	}

	/**
	 * 馆藏图书
	 * 直接显示booknum
	 * @param id
	 * @return
	 */
	public Record findBookInfo(int id){
		return Db.findFirst("select b.id 'bean.id',b.bookno 'bean.bookno',b.isbn 'bean.isbn',b.booknum 'bean.booknum',b.title 'bean.title',bp.bltitle 'beanPlus.bltitle',bp.subtitle 'beanPlus.subtitle',b.authorworkmodeid 'bean.authorworkmodeid',b.authorguobieid 'bean.authorguobieid',b.author 'bean.author',bp.otherauthor 'beanPlus.otherauthor'" +
				",bp.workmodeid 'beanPlus.workmodeid',bp.guobieid 'beanPlus.guobieid',b.publisher 'bean.publisher',b.publishaddress 'bean.publishaddress',b.publishdate 'bean.publishdate',b.edition 'bean.edition'" +
				",b.price 'bean.price',bp.sizeid 'beanPlus.sizeid',bp.id 'beanPlus.id',bp.filesurl 'beanPlus.filesurl',bp.languageid 'beanPlus.languageid',bp.totalpages 'beanPlus.totalpages',bp.bindingid 'beanPlus.bindingid'" +
				",bp.congshuming 'beanPlus.congshuming',bp.congshuauthor 'beanPlus.congshuauthor',b.newsource 'bean.newsource',b.keyword 'bean.keyword',bp.fuzhu 'beanPlus.fuzhu'" +
				",b.typecode 'bean.typecode',b.shucihao 'bean.shucihao',bp.juanci 'beanPlus.juanci',bp.ceci 'beanPlus.ceci' " +
				" from t_book b,t_book_plus bp where bp.bookid=b.id and b.id=? ",id);
	}

	public BookPlus findByIdPlus(int id){
		return plusdao.findById(id);
	}

	public BookDetail findByIdDetail(int id){
		return detaildao.findById(id);
	}

	public int findByBarcode(int orgid,String barcode) {
	    Record record = Db.findFirst("select count(1) barcodenum from t_book_detail d left join t_book b on d.bookid=b.id where barcode = ? and orgid = ?",barcode,orgid);
	    return record.getInt("barcodenum");
    }


	public Page<Book> paginate(int pageNumber,int pagesize,int pageSize,String orderBy,Book bean, String bookstatus,String status,Integer library ,String viewtype){
		String select = "SELECT   a.id as bookid, a.bookno, a.orgid, typeid, typecode, typecommonid, shucihao, booknum, isbn, title, publisher, keyword, edition, author, authorworkmodeid," +
				" authorguobieid, publishdate,  publishaddress, price,   newsource,   c.id as bookdetailid,  libraryid, piciid, barcode, status, bookstatus, jieyuenums, yuyuenums, yujienums," +
				"   destroytime, destroyreason, putindate  ,   b.id as bookplusid,   b.bltitle, subtitle, otherauthor, totalpages, workmodeid, guobieid, sizeid, filesurl, languageid, bindingid," +
				" congshuming, congshuauthor, juanci," +
				"    ceci, b.imgurl, b.resourceurl, b.resourceopentimes, moneysource, arrivedate, fuzhu ,d.library ";
		StringBuilder where = new StringBuilder(" from t_book a inner JOIN t_book_plus b ON a.id = b.bookid " +
				" inner JOIN t_book_detail c on a.id=c.bookid" +
				" inner JOIN t_library d  ON c.libraryid = d.id " +
				" where a.booknum>0 and a.orgid =?");


		List<Object> paramList =new ArrayList<Object>();
		paramList.add(bean.getOrgid());
		if (bean.getIsbn() !=null && !bean.getIsbn().equals("")){
			where.append(" and isbn = ? ");
			paramList.add(ISBNTools.fmtisbn(bean.getIsbn()));
		}

		if (bean.getTitle() !=null && !bean.getTitle().equals("")){
			where.append(" and title like ? ");
			paramList.add("%"+bean.getTitle()+"%");
		}

		if (bean.getAuthor() !=null && !bean.getAuthor().equals("")){
			where.append(" and author like ? ");
			paramList.add("%"+bean.getAuthor()+"%");
		}
		if (bean.getPublisher() !=null && !bean.getPublisher().equals("")){
			where.append(" and publisher like ? ");
			paramList.add("%"+bean.getPublisher()+"%");
		}
		if (bean.getBookno() !=null && !bean.getBookno().equals("")){
			where.append(" and a.bookno like ? ");
			paramList.add("%"+bean.getBookno()+"%");
		}
		if (bean.getTypeid() !=null){
			where.append(" and typeid =? ");
			paramList.add(bean.getTypeid());
		}
		if(StringUtils.isNotBlank(bookstatus)){
			where.append(" and c.bookstatus =? ");
			paramList.add(bookstatus);
		}
		if(StringUtils.isNotBlank(status)){
			where.append(" and c.status =? ");
			paramList.add(status);
		}

		if (library !=null){
			where.append(" and c.libraryid =? ");
			paramList.add(library);
		}

		if (viewtype !=null && "on".equals(viewtype)){
			//单本显示
		}else {
			where.append(" group by a.id");
		}


		if(StringUtils.isNotBlank(orderBy)){
			where.append(" order by ").append(orderBy);
		}
		if (viewtype !=null && "on".equals(viewtype)){
			//单本显示
			return dao.paginate(pageNumber,pageSize,select,where.toString(),paramList.toArray(new Object[0]));
		}else {
			return dao.paginateByFullSql(pageNumber, pageSize,true,"select count(distinct a.id)  "+where.toString(),select+where.toString(),paramList.toArray(new Object[0]));
		}
	}

	public Page<Book> paginate(int pageNumber,int pagesize,int pageSize,String orderBy,Book bean, String bookstatus,String status,Integer library ,String viewtype,String starttime,String endtime){
		String select = "SELECT   a.id as bookid, a.bookno, a.orgid, typeid, typecode, typecommonid, shucihao, booknum, isbn, title, publisher, keyword, edition, author, authorworkmodeid," +
				" authorguobieid, publishdate,  publishaddress, price,   newsource,   c.id as bookdetailid,  libraryid, piciid, barcode, status, bookstatus, jieyuenums, yuyuenums, yujienums," +
				"   destroytime, destroyreason, putindate  ,   b.id as bookplusid,   b.bltitle, subtitle, otherauthor, totalpages, workmodeid, guobieid, sizeid, filesurl, languageid, bindingid," +
				" congshuming, congshuauthor, juanci," +
				"    ceci, b.imgurl, b.resourceurl, b.resourceopentimes, moneysource, arrivedate, fuzhu ,d.library ";
		StringBuilder where = new StringBuilder(" from t_book a inner JOIN t_book_plus b ON a.id = b.bookid " +
				" inner JOIN t_book_detail c on a.id=c.bookid" +
				" inner JOIN t_library d  ON c.libraryid = d.id " +
				" where a.booknum>0 and a.orgid =?");


		List<Object> paramList =new ArrayList<Object>();
		paramList.add(bean.getOrgid());
		if (bean.getIsbn() !=null && !bean.getIsbn().equals("")){
			where.append(" and isbn = ? ");
			paramList.add(ISBNTools.fmtisbn(bean.getIsbn()));
		}

		if (bean.getTitle() !=null && !bean.getTitle().equals("")){
			where.append(" and title like ? ");
			paramList.add("%"+bean.getTitle()+"%");
		}

		if(CommonUtils.isNotNullOrNotEmpty(starttime)) {
			where.append(" and a.createtime >= ? ");
			starttime += " 00:00:00";
			paramList.add(starttime);
		}

		if(CommonUtils.isNotNullOrNotEmpty(endtime)) {
			where.append(" and a.createtime <= ? ");
			endtime += " 23:59:59";
			paramList.add(endtime);
		}

		if (bean.getAuthor() !=null && !bean.getAuthor().equals("")){
			where.append(" and author like ? ");
			paramList.add("%"+bean.getAuthor()+"%");
		}
		if (bean.getPublisher() !=null && !bean.getPublisher().equals("")){
			where.append(" and publisher like ? ");
			paramList.add("%"+bean.getPublisher()+"%");
		}
		if (bean.getBookno() !=null && !bean.getBookno().equals("")){
			where.append(" and a.bookno like ? ");
			paramList.add("%"+bean.getBookno()+"%");
		}
		if (bean.getTypeid() !=null){
			where.append(" and typeid =? ");
			paramList.add(bean.getTypeid());
		}
		if(StringUtils.isNotBlank(bookstatus)){
			where.append(" and c.bookstatus =? ");
			paramList.add(bookstatus);
		}
		if(StringUtils.isNotBlank(status)){
			where.append(" and c.status =? ");
			paramList.add(status);
		}

		if (library !=null){
			where.append(" and c.libraryid =? ");
			paramList.add(library);
		}

		if (viewtype !=null && "on".equals(viewtype)){
			//单本显示
		}else {
			where.append(" group by a.id");
		}


		if(StringUtils.isNotBlank(orderBy)){
			where.append(" order by ").append(orderBy);
		}
		if (viewtype !=null && "on".equals(viewtype)){
			//单本显示
			return dao.paginate(pageNumber,pageSize,select,where.toString(),paramList.toArray(new Object[0]));
		}else {
			return dao.paginateByFullSql(pageNumber, pageSize,true,"select count(distinct a.id)  "+where.toString(),select+where.toString(),paramList.toArray(new Object[0]));
		}
	}



	public void deleteById(int id) {
		dao.deleteById(id);
	}

	public void addOrUpdate(Book bean, BookPlus beanPlus, BookDetail beanDetail,String[] txm,String[] gcd, int operatorid){
		Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				if(bean.getId()== null){
					Record user = Db.findFirst("select orgid from t_user WHERE id =?",operatorid);
					int orgid = user.getInt("orgid");
					//判断是否为复本
					bean.setOrgid(orgid).setCreatetime(new Date()).setOperatorid(operatorid).save();
					for(int i=0;i<txm.length;i++){
						beanDetail.setId(null);
						String barcode = txm[i];
						int libraryid = Integer.parseInt(gcd[i]);
						beanDetail.setBarcode(barcode).setLibraryid(libraryid).setBookid(bean.getId()).setStatus(0).setPutindate(new Date()).setCreatetime(new Date()).setOperatorid(operatorid).save();
					}
					if(beanPlus != null){
						beanPlus.setBookid(bean.getId()).save();
					}
				}else {
					Book old = findById(bean.getId());
					bean.setCreatetime(old.getCreatetime()).setOperatorid(old.getOperatorid()).setUpdatetime(new Date()).setUpdateuserid(operatorid).update();
					if(beanDetail != null){
						BookDetail bookDetail1Old = findByIdDetail(beanDetail.getId());
						beanDetail.setCreatetime(bookDetail1Old.getCreatetime()).setOperatorid(bookDetail1Old.getOperatorid()).setUpdatetime(new Date()).setUpdateuserid(operatorid).update();
					}
					if(beanPlus != null){
						beanPlus.update();
					}
				}
				return true;
			}
		});
	}

    /**
     * 通过机构id和isbn获取馆藏图书列表
     * @param orgid
     * @param isbnCode
     */
    public List<Record> findByISBN(int orgid,String isbnCode){
        List<Record> bookList = Db.find("select b.id,b.isbn 'bean.isbn',b.title 'bean.title',bp.bltitle 'beanPlus.bltitle',bp.subtitle 'beanPlus.subtitle',b.author 'bean.author',b.authorworkmodeid 'bean.authorworkmodeid',b.authorguobieid 'bean.authorguobieid',bp.otherauthor 'beanPlus.otherauthor'\n" +
				",bp.workmodeid 'beanPlus.workmodeid',bp.guobieid 'beanPlus.guobieid',b.publisher 'bean.publisher',b.publishaddress 'bean.publishaddress',b.publishdate 'bean.publishdate',b.edition 'bean.edition'\n" +
				",b.price 'bean.price',bp.sizeid 'beanPlus.sizeid',bp.filesurl 'beanPlus.filesurl',bp.languageid 'beanPlus.languageid',bp.totalpages 'beanPlus.totalpages',bp.bindingid 'beanPlus.bindingid'\n" +
				",bp.congshuming 'beanPlus.congshuming',bp.congshuauthor 'beanPlus.congshuauthor',b.newsource 'bean.newsource',b.keyword 'bean.keyword',bp.fuzhu 'beanPlus.fuzhu'\n" +
				",b.typecode 'bean.typecode',b.shucihao 'bean.shucihao',bp.juanci 'beanPlus.juanci',bp.ceci 'beanPlus.ceci'\n" +
				" from t_book b,t_book_plus bp where bp.bookid=b.id and b.isbn=? and b.orgid =?",isbnCode,orgid);
        return bookList;
    }

    /**
     * 通过机构id和正题名获取馆藏图书列表
     * @param orgid
     * @param ztmStr
     */
    public List<Record> findByZTM(int orgid,String ztmStr){
        List<Record> bookList = Db.find("select b.id,b.isbn 'bean.isbn',b.title 'bean.title',bp.bltitle 'beanPlus.bltitle',bp.subtitle 'beanPlus.subtitle',b.author 'bean.author',bp.otherauthor 'beanPlus.otherauthor'" +
				",bp.workmodeid 'beanPlus.workmodeid',bp.guobieid 'beanPlus.guobieid',b.publisher 'bean.publisher',b.publishaddress 'bean.publishaddress',b.publishdate 'bean.publishdate',b.edition 'bean.edition'" +
				",b.price 'bean.price',bp.sizeid 'beanPlus.sizeid',bp.filesurl 'beanPlus.filesurl',bp.languageid 'beanPlus.languageid',bp.totalpages 'beanPlus.totalpages',bp.bindingid 'beanPlus.bindingid'" +
				",bp.congshuming 'beanPlus.congshuming',bp.congshuauthor 'beanPlus.congshuauthor',b.newsource 'bean.newsource',b.keyword 'bean.keyword',bp.fuzhu 'beanPlus.fuzhu'" +
				",b.typecode 'bean.typecode',b.shucihao 'bean.shucihao',bp.juanci 'beanPlus.juanci',bp.ceci 'beanPlus.ceci'" +
				" from t_book  b left join t_book_plus bp on bp.bookid=b.id where b.title like '%"+ztmStr+"%' and b.orgid ="+orgid);
        return bookList;
    }

	public Page<Record> findBookList_bianmu(int pageNumber,int pagesize,int orgid,String catalogUserId,String barcode,String startTime,String endTime,String title,String author,String publisher,int operatorid){

		String select = "select DISTINCT(b.id) id,b.isbn,b.title,b.author,b.publisher,b.price,b.bookno,(select count(1) from t_book_detail where bookid = b.id) counts,b.createtime,u.realname";
		StringBuilder where = new StringBuilder(" from t_book b inner join t_book_detail d on b.id=d.bookid inner join t_user u on b.operatorid=u.id where (d.bookstatus = 0 or d.bookstatus is null) and b.orgid= ? ");
		List list = new ArrayList();
		list.add(orgid);
		if(StringUtils.isNotBlank(catalogUserId)){
			if(catalogUserId.equals("1")){
				where.append(" and b.operatorid=?");
				list.add(operatorid);
			}else {
				where.append(" and b.operatorid=?");
				list.add(catalogUserId);
			}
		}
		if(StringUtils.isNotBlank(barcode)){
			where.append(" and d.barcode =?");
			list.add(barcode);
		}
        if(StringUtils.isNotBlank(title)){
            where.append(" and b.title like '%"+title+"%' ");
        }
        if(StringUtils.isNotBlank(author)){
            where.append(" and b.author like '%"+author+"%' ");
        }
        if(StringUtils.isNotBlank(publisher)){
            where.append(" and b.publisher like '%"+publisher+"%' ");
        }
		if(StringUtils.isNotBlank(startTime)){
			where.append(" and b.createtime >'"+startTime+"'");
		}
		if(StringUtils.isNotBlank(endTime)){
			where.append(" and b.createtime <='"+endTime+" 23:59:59'");
		}
		Page page = Db.paginate(pageNumber, pagesize,select,where.toString(),CommonUtils.listToArray(list));
		Page page2 = Db.paginate(1, 1000000,select,where.toString(),CommonUtils.listToArray(list));
		Page repage = new Page(page.getList(),page.getPageNumber(),page.getPageSize(),page.getTotalPage(),page2.getList().size());
		return  repage;
	}

	public Page<Record> findBookList(int pageNumber,int pagesize,int orgid,String catalogUserId,String guancangId,String startTime,String endTime){

		String select = "select b.id,b.isbn,b.title,b.author,b.publisher,b.price,b.bookno,b.booknum counts,b.createtime,u.realname";
		StringBuilder where = new StringBuilder("from t_book b inner join t_book_detail d on b.id=d.bookid inner join t_user u on b.operatorid=u.id where (d.bookstatus = 0 or d.bookstatus is null) and b.orgid= ? ");
		List list = new ArrayList();
		list.add(orgid);
		if(StringUtils.isNotBlank(catalogUserId)){
			where.append(" and b.operatorid=?");
			list.add(catalogUserId);
		}
		if(StringUtils.isNotBlank(guancangId)){
			where.append(" and d.libraryid =?");
			list.add(guancangId);
		}
		if(StringUtils.isNotBlank(startTime)){
			where.append(" and b.createtime >'"+startTime+"'");
		}
		if(StringUtils.isNotBlank(endTime)){
			where.append(" and b.createtime <='"+endTime+" 23:59:59'");
		}
		where.append(" group by b.id");
		return  Db.paginate(pageNumber, pagesize,select,where.toString(),CommonUtils.listToArray(list));
	}

	public List findBookList(int orgid,String catalogUserId,String guancangId,String startTime,String endTime){

		String select = "select DISTINCT(b.id) id,b.isbn,b.title,b.author,b.publisher,b.price,b.bookno,(select count(1) from t_book_detail where bookid = b.id) counts,DATE_FORMAT(b.createtime,'%Y-%m-%d') createtime,u.realname";
		StringBuilder where = new StringBuilder(" from t_book b inner join t_book_detail d on b.id=d.bookid inner join t_user u on b.operatorid=u.id where (d.bookstatus = 0 or d.bookstatus is null) and b.orgid= ? ");
		List list = new ArrayList();
		list.add(orgid);
		if(StringUtils.isNotBlank(catalogUserId)){
			where.append(" and b.operatorid="+catalogUserId);
		}
		if(StringUtils.isNotBlank(guancangId)){
			where.append(" and d.libraryid ="+guancangId);
		}
		if(StringUtils.isNotBlank(startTime)){
			where.append(" and b.createtime >'"+startTime+"'");
		}
		if(StringUtils.isNotBlank(endTime)){
			where.append(" and b.createtime <='"+endTime+" 23:59:59'");
		}
		String sql = select+where.toString();
		return Db.find(sql,list.toArray());
	}

	/**
	 * 书标打印列表
	 * @param pageNumber
	 * @return
	 */
	public Page<Record> bookmarkPrinting(int pageNumber,int pagesize,int orgid,Integer libraryid,Integer piciid,Integer username,Integer upperShelf,String title,
										 String barcode1,String barcode2,String startDate,String endDate,Integer ordertype,Integer orderby){
		String select = "SELECT b.id detailid,a.id,b.barcode,a.bookno,a.isbn,a.title,a.author,a.publisher ";
		StringBuilder where = new StringBuilder("FROM t_book a right JOIN t_book_detail b ON a.id = b.bookid WHERE a.orgid = ?");
		List list = new ArrayList();
		list.add(orgid);
		if(libraryid != null){
			where.append(" AND b.libraryid = ?");
			list.add(libraryid);
		}
		if(piciid != null){
			where.append(" AND b.piciid = ?");
			list.add(piciid);
		}
		if(username != null){
			where.append(" AND a.operatorid = ?");
			list.add(username);
		}
		if(upperShelf != null){
			if(upperShelf == 0){
				where.append(" AND b.bookstatus = 0");
			}
			if(upperShelf == 1){
				where.append(" AND b.bookstatus = 1");
			}
		}
		if(StringUtils.isNotBlank(title)){
			where.append(" AND a.title LIKE ?");
			list.add("%"+title+"%");
		}
		if(StringUtils.isNotBlank(barcode1)){
			StringBuffer tempSql = new StringBuffer();
			String[] barcodes =barcode1.split(",");
			for (String barcode : barcodes){
				if (tempSql.length()> 0){
					tempSql.append(" OR ");
				}
				String[] between=barcode.split("-");
				if (between.length==2){
					tempSql.append(" b.barcode between '").append(between[0]).append("' AND '").append(between[1]).append("'");
				}else {
					tempSql.append(" b.barcode= '").append(between[0]).append("' ");
				}
			}
			where.append(" AND ( ").append(tempSql.toString()).append(" )");
		}
		if(StringUtils.isNotBlank(barcode2)){
			where.append(" AND b.barcode <= ?");
			list.add(barcode2);
		}
		if(StringUtils.isNotBlank(startDate)){
			where.append(" AND DATE_FORMAT(b.createtime,'%Y-%m-%d') >= ?");
			list.add(startDate);
		}
		if(StringUtils.isNotBlank(endDate)){
			where.append(" AND DATE_FORMAT(b.createtime,'%Y-%m-%d') <= ?");
			list.add(endDate);
		}

		where.append(" AND (b.status is null or (b.status != 3 AND b.status != 4))");
		if(ordertype == 0) {
			where.append(" order by b.barcode ");
			if(orderby == 0) {
				where.append(" desc ");
			} else {
				where.append(" asc ");
			}
		} else if(ordertype == 1) {
			where.append(" order by b.createtime ");
			if(orderby == 0) {
				where.append(" desc ");
			} else {
				where.append(" asc ");
			}
		}else if(ordertype == 2) {
			where.append(" order by b.createtime ");
			if(orderby == 0) {
				where.append(" desc ");
			} else {
				where.append(" asc ");
			}
			where.append(" ,b.barcode ");
			if(orderby == 0) {
				where.append(" desc ");
			} else {
				where.append(" asc ");
			}
		}

//		if(StringUtils.isNotBlank(barcode1)){
//			where.append(" order by b.barcode ");
//		} else {
//			where.append(" order by b.createtime desc,b.barcode desc");
//		}
		return  Db.paginate(pageNumber, pagesize,select,where.toString(),CommonUtils.listToArray(list));
	}

	/**
	 * 书标打印 打印
	 */
	public List<Record> bookmarkPrintingS(int orgid,Integer libraryid,Integer piciid,Integer username,Integer upperShelf,String title,
										 String barcode1,String barcode2,String startDate,String endDate){
		String select = "SELECT b.barcode,a.bookno,a.isbn,a.shucihao,a.typecode,a.title,a.author,a.publisher ";
		StringBuilder where = new StringBuilder("FROM t_book a INNER JOIN t_book_detail b ON a.id = b.bookid WHERE a.orgid = ?");
		List list = new ArrayList();
		list.add(orgid);
		if(libraryid != null){
			where.append(" AND b.libraryid = ?");
			list.add(libraryid);
		}
		if(piciid != null){
			where.append(" AND b.piciid = ?");
			list.add(piciid);
		}
		if(username != null){
			where.append(" AND a.operatorid = ?");
			list.add(username);
		}
		if(upperShelf != null){
			if(upperShelf == 0){
				where.append(" AND b.bookstatus = 0");
			}
			if(upperShelf == 1){
				where.append(" AND b.bookstatus = 1");
			}
		}
		if(StringUtils.isNotBlank(title)){
			where.append(" AND a.title LIKE ?");
			list.add("%"+title+"%");
		}
		if(StringUtils.isNotBlank(barcode1)){
			StringBuffer tempSql = new StringBuffer();
			String[] barcodes =barcode1.split(",");
			for (String barcode : barcodes){
				if (tempSql.length()> 0){
					tempSql.append(" OR ");
				}
				String[] between=barcode.split("-");
				if (between.length==2){
					tempSql.append(" b.barcode between '").append(between[0]).append("' AND '").append(between[1]).append("'");
				}else {
					tempSql.append(" b.barcode= '").append(between[0]).append("' ");
				}
			}
			where.append(" AND ( ").append(tempSql.toString()).append(" )");
		}
		if(StringUtils.isNotBlank(barcode2)){
			where.append(" AND b.barcode <= ?");
			list.add(barcode2);
		}
		if(StringUtils.isNotBlank(startDate)){
			where.append(" AND DATE_FORMAT(b.createtime,'%Y-%m-%d') >= ?");
			list.add(startDate);
		}
		if(StringUtils.isNotBlank(endDate)){
			where.append(" AND DATE_FORMAT(b.createtime,'%Y-%m-%d') <= ?");
			list.add(endDate);
		}
		where.append(" AND (b.status is null or (b.status != 3 AND b.status != 4))");
		List<Record> r = Db.find(select+where+" order by b.createtime,b.barcode",CommonUtils.listToArray(list));

		return r;
	}

	/**
	 * 图书上架
	 * @param
	 * @param orgid
	 * @param catalogUserId
	 * @param guancangId
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@Before(Tx.class)
	public void upperShelf(int orgid,String catalogUserId,String guancangId,String startTime,String endTime){

		String select = "select d.id,b.id bookid ";
		StringBuilder where = new StringBuilder(" from t_book b,t_user u,t_book_detail d " +
				"where b.operatorid=u.id and b.id=d.bookid AND d.bookstatus = 0 and b.orgid= ?");
		List list = new ArrayList();
		list.add(orgid);
		if(StringUtils.isNotBlank(catalogUserId)){
			where.append(" and u.id=?");
			list.add(catalogUserId);
		}
		if(StringUtils.isNotBlank(guancangId)){
			where.append(" and d.libraryid =?");
			list.add(guancangId);
		}
		if(StringUtils.isNotBlank(startTime)){
			where.append(" and b.createtime >?");
			list.add(startTime);
		}
		if(StringUtils.isNotBlank(endTime)){
			where.append(" and b.createtime <=?");
			list.add(endTime+" 23:59:59");
		}
		List<Record> r = Db.find(select+where,CommonUtils.listToArray(list));
		for(Record ids : r){
			Integer id = ids.getInt("id");
			Integer bookid = ids.getInt("bookid");
			Db.update("UPDATE t_book_detail SET bookstatus = 1,shangjiatime = now(),status=0 WHERE id = ?",id);
			Db.update("UPDATE t_book SET booknum = booknum+1 WHERE id = ?",bookid);
		}
	}

	public Map initBookList(int orgid,int operatorid){
		Map map = new HashMap();
		List<Record> userList = Db.find("select id,realname from t_user where orgid ="+orgid);
		List<Record> libraryList = Db.find("select id,library from t_library where orgid="+orgid);
		List<Record> piciList = Db.find("SELECT id,batchname from t_bookpici where orgid = ? ORDER BY createtime desc",orgid);
		if(CommonUtils.isNullOrEmpty(userList)) {
			userList = new ArrayList<>();
		}
		if(CommonUtils.isNullOrEmpty(libraryList)) {
			libraryList = new ArrayList<>();
		}
		if(CommonUtils.isNullOrEmpty(piciList)) {
			piciList = new ArrayList<>();
		}
		map.put("userList",userList);
		map.put("libraryList",libraryList);
		map.put("piciList",piciList);
		map.put("operatorid",operatorid);
		return map;
	}

    /**
     * 漏码检测 图书条形码
     * @param orgid
     */
	public Map leakDetectionBarcode(int orgid) {
		List<String> list = Db.query("SELECT b.barcode FROM t_book a INNER JOIN t_book_detail b ON a.id = b.bookid " +
				"WHERE a.orgid = ? ORDER BY b.barcode", orgid);
		List result = new ArrayList();
		if (list == null || list.size() == 0) {
			return null;
		}
		List<Integer> values = new ArrayList<>();
		List<String> exceptionBarcode = new ArrayList<>();
		//获取条形码位数
		Record r = Db.findFirst("SELECT tstiaoxinmaweishu,tstiaoxingmaqianzhui FROM t_org_setting WHERE orgid = ?", orgid);
		Integer ws = r.getInt("tstiaoxinmaweishu");
		String qz = r.get("tstiaoxingmaqianzhui");
		for (int i = 0; i < list.size(); i++) {
			if (ws != null) {
				String barcode = list.get(i);
				if (StringUtils.isNotBlank(qz)){
					barcode = barcode.substring(1);
				}
				if(StringUtils.isNotBlank(barcode)){
					barcode.substring(barcode.length() - ws);
					try {
						values.add(Integer.parseInt(barcode));
					}catch(Exception e){
						result.add(1);
						exceptionBarcode.add(barcode);
						continue;
					}
				}else {
					result.add(1);
					return null;
				}
			} else {
				values.add(Integer.parseInt(list.get(i)));
			}
		}
		int max = Collections.max(values);
		int min = Collections.min(values);
		List<Integer> all = new ArrayList();
		for(int j=min;j<max;j++){
			all.add(j);
		}
		all.removeAll(values);

		if(all != null){
			BookService service = new BookService();
			result = service.convert(all, ws);
			if(StringUtils.isNotBlank(qz)){
				for(int i=0;i<result.size();i++){
					String str = (String) result.get(i);
					StringBuffer sb = new StringBuffer(str);
					if(sb.length()>ws){
						sb.insert(ws+1,qz);
						sb.insert(0,qz);
					}else {
						sb.insert(0,qz);
					}
					result.set(i,sb.toString());
				}
			}

		}
		Map map = new HashMap();
		map.put("barcodeList",result);
		map.put("exceptionBarcode",exceptionBarcode);
		return map;
	}

	/**
	 * 漏码检测 期刊条形码
	 * @param
	 */
	public List leakDetectionBarcodeQ(int orgid) {
		List<String> list = Db.query("SELECT b.barcode FROM t_periodical_zhengding a INNER JOIN t_periodical_detail b ON a.id = b.periodicalid " +
				"WHERE a.orgid = ? ORDER BY b.barcode", orgid);
		List result = new ArrayList();
		if (list == null || list.size() == 0) {
			return null;
		}
		List<Integer> values = new ArrayList<>();

		//获取条形码位数
		Record r = Db.findFirst("SELECT qktiaoxingmaweishu,qktiaoxingmaqianzhui FROM t_org_setting WHERE orgid = ?", orgid);
		Integer ws = r.getInt("qktiaoxingmaweishu");
		String qz = r.get("qktiaoxingmaqianzhui");
		for (int i = 0; i < list.size(); i++) {
			if (ws != null) {
				String barcode = list.get(i);
				if(StringUtils.isNotBlank(qz)){
					barcode = barcode.substring(1);
				}
				if(StringUtils.isNotBlank(barcode)){
					barcode.substring(barcode.length() - ws);
					try {
						values.add(Integer.parseInt(barcode));
					}catch(Exception e){
						result.add(1);
						return result;
					}
				}else {
					result.add(1);
					return result;
				}
			} else {
				values.add(Integer.parseInt(list.get(i)));
			}
		}
		int max = Collections.max(values);
		int min = Collections.min(values);
		List<Integer> all = new ArrayList();
		for(int j=min;j<max;j++){
			all.add(j);
		}
		all.removeAll(values);

		if(all != null){
			BookService service = new BookService();
			result = service.convert(all, ws);
			if(StringUtils.isNotBlank(qz)){
				for(int i=0;i<result.size();i++){
					String str = (String) result.get(i);
					StringBuffer sb = new StringBuffer(str);
					if(sb.length()>ws){
						sb.insert(ws+1,qz);
						sb.insert(0,qz);
					}else {
						sb.insert(0,qz);
					}
					result.set(i,sb.toString());
				}
			}

		}
		return result;
	}

	/**
	 * 漏码检测 书次号
	 * @param orgid
	 */
	public String leakDetectionshucihao(int orgid){
		List<Record> list = Db.find("SELECT  DISTINCT a.typecode,a.shucihao FROM t_book a WHERE a.orgid = ? order by typecode,a.shucihao",orgid);
		StringBuffer sb = new StringBuffer();
		if(list != null){
			String nexttypecode="";
			Integer nextShucihao=null;
			StringBuffer subStr =new StringBuffer();
			for (Record record : list){
				String  typecode =record.get("typecode");
				Integer shucihao =record.get("shucihao");

				if(StringUtils.isNotBlank(typecode) && CommonUtils.isNotNullOrNotEmpty(shucihao)){
					if (nexttypecode.equals("") || !nexttypecode.equals(typecode)){
						if (subStr.length()>0){
							sb.append("分类号&nbsp;"+nexttypecode).append("&nbsp;缺失&nbsp;").append(subStr).append("/<br>");
							subStr.setLength(0);
						}
						nextShucihao =shucihao+1;
						nexttypecode =typecode;
					}else if (!nextShucihao.equals(shucihao)) {
						if(nextShucihao == shucihao-1){
							subStr.append(nextShucihao).append(",");
							nextShucihao=shucihao+1;
						}else {
							subStr.append(nextShucihao).append("-").append(shucihao-1).append(",");
							nextShucihao=shucihao+1;
						}
					}
					nextShucihao =shucihao+1;
				}else {
					sb.append("书本分类号或书次号为空").append("/<br>");
				}
			}
			if(StringUtils.isNotBlank(nexttypecode) && StringUtils.isNotBlank(subStr.toString())){
				sb.append("分类号&nbsp;"+nexttypecode).append("&nbsp;缺失&nbsp;").append(subStr.toString());
			}
		}else {
			sb.append("没有漏码");
		}
		return sb.toString();
	}
	/**
	 * 漏码检测 期刊书次号
	 * @param orgid
	 */
	public String leakDetectionshucihaoQ(int orgid){
		List<Record> list = Db.find("SELECT  DISTINCT a.typecode,a.zhongcihao FROM t_periodical_zhengding a WHERE a.orgid = ? order by typecode,a.zhongcihao",orgid);
		StringBuffer sb = new StringBuffer();
		if(list != null){
			String nexttypecode="";
			Integer nextShucihao=null;
			StringBuffer subStr =new StringBuffer();
			for (Record record : list){
				String  typecode =record.get("typecode");
				Integer shucihao =record.get("zhongcihao");

				if(StringUtils.isNotBlank(typecode) && CommonUtils.isNotNullOrNotEmpty(shucihao)){
					if (nexttypecode.equals("") || !nexttypecode.equals(typecode)){
						if (subStr.length()>0){
							sb.append("分类号&nbsp;"+nexttypecode).append("&nbsp;缺失&nbsp;").append(subStr).append("/<br>");
							subStr.setLength(0);
						}
						nextShucihao =shucihao+1;
						nexttypecode =typecode;
					}else if (!nextShucihao.equals(shucihao)) {
						if(nextShucihao == shucihao-1){
							subStr.append(nextShucihao).append(",");
							nextShucihao=shucihao+1;
						}else {
							subStr.append(nextShucihao).append("-").append(shucihao-1).append(",");
							nextShucihao=shucihao+1;
						}
					}
					nextShucihao =shucihao+1;
				}else {
					sb.append("书本分类号或书次号为空").append("/<br>");
				}
			}
			if(StringUtils.isNotBlank(nexttypecode) && StringUtils.isNotBlank(subStr.toString())){
				sb.append("分类号&nbsp;"+nexttypecode).append("&nbsp;缺失&nbsp;").append(subStr.toString());
			}
		}else {
			sb.append("没有漏码");
		}
		return sb.toString();
	}

	//转换连续数字
	public List convert(List<Integer> list,Integer ws){
	//public static void main(String[] args) {
		//int[] NoNum = {6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21};
		Integer[] NoNum = list.toArray(new Integer[list.size()]);
		List results = new ArrayList();
		int state = 0;
		String result = "";
		for (int i = 0; i < NoNum.length; i++) {
			if (i == NoNum.length - 1) state = 2;
			if (state == 0) {
				if (NoNum[i + 1] == NoNum[i] + 1) {
					String str = Integer.toString(NoNum[i]);
					while (str.length() < ws) {
						str = "0"+str;
					}
					result += str;
					result += "-";
					state = 1;
				} else {
					String str = Integer.toString(NoNum[i]);
					while (str.length() < ws) {
						str = "0"+str;
					}
					result += str;
					result += ",";
				}
			} else if (state == 1) {
				if (NoNum[i + 1] != NoNum[i] + 1) {
					String str = Integer.toString(NoNum[i]);
					while (str.length() < ws) {
						str = "0"+str;
					}
					result += str;
					result += ",";
					state = 0;
				}
			} else {
				String str = Integer.toString(NoNum[i]);
				while (str.length() < ws) {
					str = "0"+str;
				}
				result += str;
			}
		}
		String str[] = result.split(",");
		results = Arrays.asList(str);
		return results;
	}

	/**
	 * 编目统计
	 * @param orgid
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public List<Record> listCount(int orgid,String startTime,String endTime){
		String select = "SELECT a.typeid as id,COUNT(d.id) as cs,COUNT(DISTINCT a.shucihao,a.typecode) as zs,SUM(a.price) as price ";
		StringBuilder where = new StringBuilder(" from t_book a LEFT JOIN t_book_detail d ON a.id = d.bookid " +
				"LEFT join t_booktype bt on bt.id=a.typeid  WHERE a.orgid = ?");
		List list = new ArrayList();
		list.add(orgid);
		if(StringUtils.isNotBlank(startTime)){
			where.append(" AND a.createtime >= ?");
			list.add(startTime+" 00:00:00");
		}
		if (StringUtils.isNotBlank(endTime)){

			where.append(" AND a.createtime <= ?");
			list.add(endTime+" 23:59:59");
		}
		where.append(" group by id ");
		List<Record> r = Db.find(select+where,CommonUtils.listToArray(list));
		return r;
	}

	/**
	 * 编目统计合计
	 * @param orgid
	 * @return
	 */
//	public List<Record> listCountTotal(int orgid,String startTime,String endTime){
//		String select = "SELECT left(bt.id,1) as gname,COUNT(d.id) as zcs,COUNT(DISTINCT a.shucihao,a.typeid) as zs,SUM(a.price) as price ";
//		StringBuilder where = new StringBuilder(" from t_book a LEFT JOIN t_book_detail d ON a.id = d.bookid " +
//				"LEFT join t_booktype bt on bt.id=a.typeid  WHERE a.orgid = ?");
//		List list = new ArrayList();
//		list.add(orgid);
//		if(StringUtils.isNotBlank(startTime)){
//			where.append(" AND a.createtime > '"+startTime+"'");
//		}
//		if (StringUtils.isNotBlank(endTime)){
//			where.append(" AND a.createtime < '"+endTime+"'");
//		}
//		List<Record> r = Db.find(select+where,CommonUtils.listToArray(list));
//		return r;
//	}

	public Book findBookByBooknoTitle(int orgid,String bookno,String title,String isbn,String publisher,String author){
		return dao.findFirst("select * from t_book where orgid=? and bookno = ? and title = ? and isbn = ? and publisher = ? and author = ?",orgid,bookno,title,isbn,publisher,author);
	}
	/**
	 * 保存编目信息
	 * @param book
	 * @param bookPlus
	 * @param list
	 * @param operatorid
	 */
	@Before(Tx.class)
	public void saveBookInfo(Book book,BookPlus bookPlus,List<BookDetail> list,int operatorid){
		if(CommonUtils.isNotNullOrNotEmpty(book)&&CommonUtils.isNotNullOrNotEmpty(book.getIsbn())) {
			book.setIsbn(ISBNTools.fmtisbn(book.getIsbn()));
		}
		int check = 0;
		if(null == book.getId()) { //如果能够在数据库查询出相同的书籍信息则不新增信息
			Book checkbook = findBookByBooknoTitle(book.getOrgid(),book.getBookno(),book.getTitle(),book.getIsbn(),book.getPublisher(),book.getAuthor());
			if(CommonUtils.isNotNullOrNotEmpty(checkbook)) {
				book = checkbook;
//				book.setBooknum(checkbook.getBooknum() + list.size());
				book.update();
				check = 1;
			} else {
//				book.setBooknum(list.size());
				book.save();
			}
		} else {
//			Record record = Db.findFirst("select count(1) number from t_book_detail where bookid = ?",book.getId());
//			book.setBooknum(record.getInt("number") + list.size());
			book.update();
		}
		if(check == 0) { //如果是新增或修改书籍信息则保存
			bookPlus.setBookid(book.getId());
			if (null == bookPlus.getId()) {
				//删除所有编目信息后，bookPlus没有删除，回溯数据会增加一条bookPlus，多出一条记录出错。
				List<Record> recordList=Db.find("SELECT id FROM t_book_plus where bookid = ?",book.getId());
				if (recordList !=null && !recordList.isEmpty()){
					bookPlus.setId(recordList.get(0).getInt("id"));
					bookPlus.update();
				}else{
					bookPlus.save();
				}
			} else {
				bookPlus.update();
			}
		}
		for (BookDetail bookDetail : list) {
			bookDetail.setCreatetime(new Date());
			bookDetail.setOperatorid(operatorid);
			bookDetail.setBookid(book.getId());
			bookDetail.setBookstatus(0);
			bookDetail.setPutindate(new Date());
			try {
				bookDetail.save();
			}catch (Exception e){
				logger.info("编目保存数据异常 bookid:"+bookDetail.getBookid()+" barcode:"+bookDetail.getBarcode()+" listsize:"+list.size());
				continue;
			}
		}
	}

	public Record queryPublisherByIsbn(String isbn){
		Record r = Db.findFirst("SELECT * FROM t_isbn WHERE isbn = ?",isbn);
		return r;
	}

}
