package com.controller;

import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Clear;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.model.Org;
import com.model.User;
import com.service.PrintService;
import com.utils.CommonUtils;
import com.utils.ExcelExportUtil;
import com.utils.ExcelExportUtil_template;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 常见打印菜单中的功能
 */
@ControllerInterface(path="print")
public class PrintController extends BaseController {
    private PrintService service = PrintService.me;
    Org orgDao = new Org().dao();


    /**
     * 书本式目录打印
     */
    public void shubenshimuludayin(){
        render("/view/print/shubenshimuludayin.html");
    }
    public void shubenshimuludayin_list(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            Map param = new HashMap();
            int libraryid = this.getParaToInt("libraryid", 0);
            if(libraryid >0){
                param.put("libraryid", libraryid);
            }
            String starttime = this.getPara("starttime");
            if (StringUtils.isNotBlank(starttime)) {
                param.put("starttime", starttime);
            }
            String endtime = this.getPara("endtime");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }
            int pageNumber = 1;
            if (this.getParaToInt("pageNumber", 0) > 0) {
                pageNumber = getParaToInt("pageNumber");
            }
            String field = this.getPara("field");
            if(StringUtils.isNotBlank(field)){
                if(field.indexOf("order by bookno desc") > -1) {
                    //param.put("field", "order by typecode,concat(typeid,shucihao),juanci desc");
                    param.put("field", "order by typecode desc ,shucihao desc,juanci desc,ceci desc");
                } else if(field.indexOf("order by bookno asc") > -1){
                    param.put("field", "order by typecode,shucihao,juanci,ceci");
                } else if(field.indexOf("order by title desc") > -1) {
                    param.put("field", "order by title desc");
                } else if(field.indexOf("order by title asc") > -1){
                    param.put("field", "order by title asc");
                } else {
                    param.put("field", field);
                }
            }else {
                param.put("field", "order by typecode,shucihao,juanci");
                //param.put("field", "order by typecode,concat(typeid,shucihao),juanci asc");
            }
            String bookno = this.getPara("bookno");
            if(StringUtils.isNotBlank(bookno)){
                param.put("bookno", bookno);
            }
            int pageSize = this.getParaToInt("pageSize", PAGESIZE);
            Page<Record> page = service.shubenshimuludayin_page(orgid,param,pageNumber,pageSize);
            success(page);
        }catch(Exception e){
            logger.error("",e);
            fail();
        }

    }


    public void shubenshimuludayin_list_print(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            Map param = new HashMap();
            int libraryid = this.getParaToInt("libraryid", 0);
            if(libraryid >0){
                param.put("libraryid", libraryid);
            }
            String starttime = this.getPara("starttime");
            if (StringUtils.isNotBlank(starttime)) {
                param.put("starttime", starttime);
            }
            String endtime = this.getPara("endtime");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }
            int pageNumber = 1;
            if (this.getParaToInt("pageNumber", 0) > 0) {
                pageNumber = getParaToInt("pageNumber");
            }
            String field = this.getPara("field");
            if(StringUtils.isNotBlank(field)){
                /*if(field.indexOf("null") > -1) {
                    param.put("field", "order by typecode,shucihao,p.juanci asc");
                } else {
                    param.put("field", field);
                }*/
                if(field.indexOf("order by bookno desc") > -1) {
                    //param.put("field", "order by typecode,concat(typeid,shucihao),juanci desc");
                    param.put("field", "order by typecode desc ,shucihao desc,juanci desc,ceci desc");
                } else if(field.indexOf("order by bookno asc") > -1){
                    param.put("field", "order by typecode,shucihao,juanci,ceci asc");
                } else if(field.indexOf("order by title desc") > -1) {
                    param.put("field", "order by title desc");
                } else if(field.indexOf("order by title asc") > -1){
                    param.put("field", "order by title asc");
                } else {
                    param.put("field", field);
                }
            }else {
                param.put("field", "order by typecode,shucihao,p.juanci,p.ceci");
            }
            String bookno = this.getPara("bookno");
            if(StringUtils.isNotBlank(bookno)){
                param.put("bookno", bookno);
            }
            int pageSize = this.getParaToInt("pageSize", PAGESIZE);
            List<Record> page = service.shubenshimuludayin_list_print(orgid,param);
            success(page);
        }catch(Exception e){
            logger.error("",e);
            fail();
        }

    }

    public void shubenshimuludayin_export(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            Map param = new HashMap();
            int libraryid = this.getParaToInt("libraryid", 0);
            if(libraryid >0){
                param.put("libraryid", libraryid);
            }
            String starttime = this.getPara("starttime");
            if (StringUtils.isNotBlank(starttime)) {
                param.put("starttime", starttime);
            }
            String endtime = this.getPara("endtime");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }
            String bookno = this.getPara("bookno");
            if(StringUtils.isNotBlank(bookno)){
                param.put("bookno", bookno);
            }
            String field = this.getPara("field");
            if(StringUtils.isNotBlank(field)){
                /*if(field.indexOf("null") > -1) {
                    param.put("field", "order by typecode,concat(typeid,shucihao),p.juanci asc");
                } else {
                    param.put("field", field);
                }*/
                if(field.indexOf("order by bookno desc") > -1) {
                    //param.put("field", "order by typecode,concat(typeid,shucihao),juanci desc");
                    param.put("field", "order by typecode desc ,shucihao desc,juanci desc,ceci desc");
                } else if(field.indexOf("order by bookno asc") > -1){
                    param.put("field", "order by typecode,shucihao,juanci,ceci asc");
                } else if(field.indexOf("order by title desc") > -1) {
                    param.put("field", "order by title desc");
                } else if(field.indexOf("order by title asc") > -1){
                    param.put("field", "order by title asc");
                } else {
                    param.put("field", field);
                }
            }else {
                param.put("field", "order by typecode,shucihao,p.juanci,p.ceci asc");
            }
            List list = service.shubenshimuludayin_export(orgid,param);
            LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
            headMap.put("bookno", "索书号");
            headMap.put("title", "正题名");
            headMap.put("author", "著者");
            headMap.put("publisher", "出版社");
            headMap.put("price", "定价（元）");
            headMap.put("booknum", "复本数");
            headMap.put("library", "馆藏地");
            headMap.put("isbn", "ISBN");
            headMap.put("edition", "版本版次");
            headMap.put("totalpages", "页数");

            try {
                ExcelExportUtil.listToExcel(list,headMap, "书本式目录打印", this.getResponse());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }catch(Exception e){
            logger.error("",e);
            fail();
        }
        renderNull();
    }

    /**
     * 图书注销报表
     */
    public void tushuzhuxiaobaobiao(){
        render("/view/print/tushuzhuxiaobaobiao.html");
    }
    public void tushuzhuxiaobaobiao_list(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            Map param = new HashMap();
            String starttime = this.getPara("starttime");
            if (StringUtils.isBlank(starttime)) {
                Calendar now = Calendar.getInstance();
                now.add(Calendar.DATE, -365);
                starttime = format1.format(now.getTime());
            }
            param.put("starttime", starttime);
            String endtime = this.getPara("endtime");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }
            int pageNumber = this.getParaToInt("pageNumber", 1);
            Page<Record> page = service.tushuzhuxiaobaobiao_page(orgid,param,pageNumber,this.getParaToInt("pageSize",PAGESIZE));
//            if(page.getList() != null && page.getList().size()>0){
//                for(Record record : page.getList()){
//                    if(record.get("createtime") != null) {
//                        record.set("createtime", format1.format(record.getDate("createtime")));
//                    }
//                }
//            }
            success(page);
        }catch(Exception e){
            logger.error("",e);
            fail();
        }
    }

    public void tushuzhuxiaobaobiao_list_print(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            Map param = new HashMap();
            String starttime = this.getPara("starttime");
            if (StringUtils.isBlank(starttime)) {
                Calendar now = Calendar.getInstance();
                now.add(Calendar.DATE, -365);
                starttime = format1.format(now.getTime());
            }
            param.put("starttime", starttime);
            String endtime = this.getPara("endtime");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }
            List<Record> page = service.tushuzhuxiaobaobiao_list_print(orgid,param);
            success(page);
        }catch(Exception e){
            logger.error("",e);
            fail();
        }
    }
    /**
     * 图书注销报表金额合计
     */
    public void tushuzhuxiaobaobiao_totalprice(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            Map param = new HashMap();
            String starttime = this.getPara("starttime");
            if (StringUtils.isBlank(starttime)) {
                Calendar now = Calendar.getInstance();
                now.add(Calendar.DATE, -365);
                starttime = format1.format(now.getTime());
            }
            param.put("starttime", starttime);
            String endtime = this.getPara("endtime");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }
            success(service.tushuzhuxiaobaobiao_totalprice(orgid,param));
        }catch(Exception e){
            logger.error("",e);
            fail();
        }
    }

    public void tushuzhuxiaobaobiao_export(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            String orgname = new Org().dao().findById(orgid).getOrgname();

            Map param = new HashMap();
            String starttime = this.getPara("starttime");
            if (StringUtils.isBlank(starttime)) {
                Calendar now = Calendar.getInstance();
                now.add(Calendar.DATE, -365);
                starttime = format1.format(now.getTime());
            }
            param.put("starttime", starttime);
            String endtime = this.getPara("endtime");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }
            List list = service.tushuzhuxiaobaobiao_export(orgid,param);
            /*LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
            headMap.put("barcode", "图书条码");
            headMap.put("title", "正题名");
            headMap.put("author", "著者");
            headMap.put("publisher", "出版社");
            headMap.put("bookno", "索书号");
            headMap.put("price", "定价（元）");
            headMap.put("library", "馆藏地");
            headMap.put("reason", "注销原因");
            headMap.put("createtime", "注销日期");
            //headMap.put("realname", "操作员");*/
            String fields[] = {"barcode","isbn","title","author","publisher","publishdate","bookno","price","library","reason","createtime"};
            ExcelExportUtil_template.exportExcel("图书注销清单.xls",this.getResponse(),orgname+"图书注销清单",list,fields,2);
        }catch(Exception e){
            logger.error("",e);
            fail();
        }
        renderNull();
    }

    public void tushuzhuxiaobaobiao_forup_export(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            String orgname = new Org().dao().findById(orgid).getOrgname();

            Map param = new HashMap();
            String starttime = this.getPara("starttime");
            if (StringUtils.isBlank(starttime)) {
                Calendar now = Calendar.getInstance();
                now.add(Calendar.DATE, -365);
                starttime = format1.format(now.getTime());
            }
            param.put("starttime", starttime);
            String endtime = this.getPara("endtime");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }
            String select = "select d.barcode,b.title,b.author,b.isbn,b.publisher,b.bookno,b.publishdate,b.typecode,b.price,l.library,z.reason," +
                    "DATE_FORMAT(z.createtime,'%Y-%m-%d') as createtime,u.realname ";
            StringBuilder where = new StringBuilder("from t_book_zhuxiao z inner join t_book_detail d on z.bookdetailid=d.id " +
                    "inner join t_book b on b.id=z.bookid left join t_user u on u.id=z.operatorid " +
                    "inner join t_library l on l.id=d.libraryid where z.status = 0 AND z.flag = 0 AND z.orgid=? ");
            List values = new ArrayList();
            values.add(orgid);
            if(param.get("starttime") != null && !"".equals(param.get("starttime"))){
                where.append(" and z.createtime>=str_to_date('"+param.get("starttime")+" 00:00:00','%Y-%m-%d %H:%i:%S')");
            }
            if(param.get("endtime") != null && !"".equals(param.get("endtime"))){
                where.append(" and z.createtime <= str_to_date('"+param.get("endtime")+" 23:59:59','%Y-%m-%d %H:%i:%S')");
            }
            String sql = select+where.toString();
            List<Record> list = Db.find(sql,CommonUtils.listToArray(values));

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy.MM");
            for(int i=1;i<=list.size();i++){
                Record r  = list.get(i-1);
                r.set("xuhao",i);
                r.set("zhuxiaotype","");
                r.set("num",1);
                String publishdate = r.getStr("publishdate");
                try{
                    Date d = format2.parse(publishdate);
                    r.set("publishdate", format.format(d));
                }catch(Exception e){
                    r.set("publishdate","未知");
                }
                String isbn = r.getStr("isbn");
                try{
                    isbn = isbn.replaceAll("-","");
                    if(isbn.length() == 13 || isbn.length() == 10){
                        r.set("isbn",isbn);
                    }else{
                        r.set("isbn", "未知");
                    }
                }catch(Exception e){
                    r.set("isbn","未知");
                }
            }
            /*LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
            headMap.put("barcode", "图书条码");
            headMap.put("title", "正题名");
            headMap.put("author", "著者");
            headMap.put("publisher", "出版社");
            headMap.put("bookno", "索书号");
            headMap.put("price", "定价（元）");
            headMap.put("library", "馆藏地");
            headMap.put("reason", "注销原因");
            headMap.put("createtime", "注销日期");
            //headMap.put("realname", "操作员");*/
            String fields[] = {"xuhao","title","author","publisher","publishdate","isbn","typecode","num","zhuxiaotype"};
            ExcelExportUtil_template.exportExcel("馆藏清查模板.xls",this.getResponse(),"附件2\n" +
                    "馆藏清查导入说明：\n" +
                    "1、红色标记的列表列名是必填项\n" +
                    "2、出版日期字段值格式为：yyyy-MM，如：2014-09；如果年代久远，无法填写，则需填入“未知”；\n" +
                    "3、书号（ISBN）字段值格式为10位isbn编码或13位978开头的图书号；如果年代久远，无法填写，则需填入“未知”；\n" +
                    "4、图书分类：分类号即中图分类号，通常在图书的CIP页可以找到，如G792；\n" +
                    "5、清理类别为下拉选择项：只有三个值，即非法，不适宜，外观差、无保存价值",list,fields,4);
        }catch(Exception e){
            logger.error("",e);
            fail();
        }
        renderNull();
    }

    /**
     * 图书个别登记簿
     */
    public void tushugebiedengjibu(){
        render("/view/print/tushugebiedengjibu.html");
    }
    public void tushugebiedengjibu_list(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            Map param = new HashMap();
            String starttime = this.getPara("startDate");
            if(StringUtils.isNotBlank(starttime)){
                param.put("starttime", starttime);
            }
            String endtime = this.getPara("endDate");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }
            String guancangId = this.getPara("guancangId");
            if(StringUtils.isNotBlank(guancangId)){
                param.put("guancangId", guancangId);
            }
//            int pageNumber = 1;
//            if (this.getParaToInt("pageNumber", 0) > 0) {
//                pageNumber = getParaToInt("pageNumber");
//            }

            Page<Record> page = service.tushugebiedengjibu_page(this.getParaToInt("pageNumber"),this.getParaToInt("pageSize"),orgid,param);
            if(page.getList() != null && page.getList().size()>0){
                for(Record record : page.getList()){
                    if(record.get("createtime") != null) {
                        record.set("createtime", format1.format(record.getDate("createtime")));
                    }

                }
            }
            success(page);
        }catch(Exception e){
            logger.error("",e);
            fail();
        }

    }
    //图书个别登记薄打印
    public void tushugebiedengjibu_list_print(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            Map param = new HashMap();
//            String starttime = this.getPara("starttime");
//            if (StringUtils.isBlank(starttime)) {
//                Calendar now = Calendar.getInstance();
//                now.add(Calendar.DATE, -365);
//                starttime = format1.format(now.getTime());
//            }
//            param.put("starttime", starttime);
//            String endtime = this.getPara("endtime");
//            if(StringUtils.isNotBlank(endtime)){
//                param.put("endtime", endtime);
//            }
            String guancangId = this.getPara("guancangId");
            if(StringUtils.isNotBlank(guancangId)){
                param.put("guancangId", guancangId);
            }
//            int pageNumber = 1;
//            if (this.getParaToInt("pageNumber", 0) > 0) {
//                pageNumber = getParaToInt("pageNumber");
//            }

            List<Record> page = service.tushugebiedengjibu_list_print(orgid,param);

            success(page);
        }catch(Exception e){
            logger.error("",e);
            fail();
        }

    }
    public void tushugebiedengjibu_export(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            String orgname = orgDao.findById(orgid).getOrgname();
            Map param = new HashMap();
            String starttime = this.getPara("starttime");
            if (StringUtils.isNotBlank(starttime)) {
                param.put("starttime", starttime);
            }
            String endtime = this.getPara("endtime");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }
            String guancangId = this.getPara("guancangId");
            if(StringUtils.isNotBlank(guancangId)){
                param.put("guancangId", guancangId);
            }
            List list = service.tushugebiedengjibu_export(orgid,param);
            /*LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
            headMap.put("createtime", "日期");
            headMap.put("barcode", "图书条码");
            headMap.put("title", "正题名");
            headMap.put("author", "著者");
            headMap.put("publisher", "出版社");
            headMap.put("publishdate", "出版年月");
            headMap.put("newsource", "图书来源");
            headMap.put("totalpages", "页数");
            headMap.put("price", "定价（元）");
            headMap.put("fuzhu", "附注");*/

//            String fields[] = {"createtime","bookno","title","author","publisher","publishdate","newsource","totalpages","price","fuzhu"};
            String fields[] = {"createtime","barcode","title","author","edition","newsource","price"};
            ExcelExportUtil_template.exportExcel_2007("图书个别登记薄.xlsx",this.getResponse(),orgname+"图书个别登记簿",list,fields,2);
        }catch(Exception e){
            logger.error("",e);
            fail();
        }
        renderNull();
    }
    /**
     * 图书总括登记簿
     */
        public void tushuzongkuodengjibu(){
        render("/view/print/tushuzongkuodengjibu.html");
    }
    public void tushuzongkuodengjibu_list(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            Map param = new HashMap();
            String starttime = this.getPara("starttime");
            if (StringUtils.isBlank(starttime)) {
                Calendar now = Calendar.getInstance();
                now.add(Calendar.DATE, -365);
                starttime = format1.format(now.getTime());
            }
            param.put("starttime", starttime);
            String endtime = this.getPara("endtime");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }

            List<Record> result = service.tushuzongkuodengjibu_list(orgid,param);

            Page page = new Page(result, 1, 10000, 1, result.size());
            success(page);
        }catch(Exception e){
            logger.error("",e);
            fail();
        }
    }

    public void tushuzongkuodengjibu_list_print(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            Map param = new HashMap();
            String starttime = this.getPara("starttime");
            if (StringUtils.isBlank(starttime)) {
                Calendar now = Calendar.getInstance();
                now.add(Calendar.DATE, -365);
                starttime = format1.format(now.getTime());
            }
            param.put("starttime", starttime);
            String endtime = this.getPara("endtime");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }

            List<Record> list = service.tushuzongkuodengjibu_list(orgid,param);

            success(list);
        }catch(Exception e){
            logger.error("",e);
            fail();
        }
    }
    public void tushuzongkuodengjibu_export(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();
            String orgname = new Org().dao().findById(orgid).getOrgname();
            Map param = new HashMap();
            String starttime = this.getPara("starttime");
            if (StringUtils.isBlank(starttime)) {
                Calendar now = Calendar.getInstance();
                now.add(Calendar.DATE, -365);
                starttime = format1.format(now.getTime());
            }
            param.put("starttime", starttime);
            String endtime = this.getPara("endtime");
            if(StringUtils.isNotBlank(endtime)){
                param.put("endtime", endtime);
            }
            List list = service.tushuzongkuodengjibu_list(orgid,param);
            String fields[] = {"createtime","batchname","zongzhongshu","zongceshu","totalprice","type1_cs","type1_zs","type2_cs","type2_zs",
                    "type3_cs","type3_zs","type4_cs","type4_zs","type5_cs","type5_zs",};
            ExcelExportUtil_template.exportExcel("图书总括登记薄.xls",this.getResponse(),orgname+"图书总括登记薄",list,fields,3);


        }catch(Exception e){
            logger.error("",e);
            fail();
        }
        renderNull();
    }
    private <T> void fillSheet(
            WritableSheet sheet,
            List<T> list,
            LinkedHashMap<String,String> fieldMap,
            int firstIndex,
            int lastIndex
    )throws Exception{

        //定义存放英文字段名和中文字段名的数组
        String[] enFields=new String[fieldMap.size()];
        String[] cnFields=new String[fieldMap.size()];

        //填充数组
        int count=0;
        for(Map.Entry<String,String> entry:fieldMap.entrySet()){
            enFields[count]=entry.getKey();
            cnFields[count]=entry.getValue();
            count++;
        }
        sheet.addCell(new Label(5,0,"A马列主义毛泽东思想"));
        sheet.addCell(new Label(7,0,"B 哲学、宗教"));
        sheet.addCell(new Label(9,0,"C-K 社会科学"));
        sheet.addCell(new Label(11,0,"N-X 自然科学"));
        sheet.addCell(new Label(13,0,"Z 综合性图书"));
        //填充表头
        for(int i=0;i<cnFields.length;i++){
            if(i<5){
                sheet.addCell(new Label(i,0,cnFields[i]));
            }else{
                sheet.addCell(new Label(i,1,cnFields[i]));
            }

        }

        sheet.mergeCells(0,0,0,1);
        sheet.mergeCells(1,0,1,1);
        sheet.mergeCells(2,0,2,1);
        sheet.mergeCells(3,0,3,1);
        sheet.mergeCells(4,0,4,1);
        sheet.mergeCells(5,0,6,0);
        sheet.mergeCells(7,0,8,0);
        sheet.mergeCells(9,0,10,0);
        sheet.mergeCells(11,0,12,0);
        sheet.mergeCells(13,0,14,0);
        //填充内容
        int rowNo=2;
        for(int index=firstIndex;index<=lastIndex;index++){
            //获取单个对象
            T item=list.get(index);
            for(int i=0;i<enFields.length;i++){
                Object objValue=ExcelExportUtil.getFieldValueByNameSequence(enFields[i], item);
                String fieldValue=objValue==null ? "" : objValue.toString();
                Label label =new Label(i,rowNo,fieldValue);
                sheet.addCell(label);
            }

            rowNo++;
        }

        //设置自动列宽
        ExcelExportUtil.setColumnAutoSize(sheet, 5);
    }


    public void book_export(){
        try {
            Map param = new HashMap();
            param.put("isbn",getPara("isbn"));
            param.put("orgid",getPara("orgid"));
            param.put("typeid",getPara("typeid"));
            param.put("title",getPara("title"));
            param.put("author",getPara("author"));
            param.put("publisher",getPara("publisher"));
            param.put("bookno",getPara("bookno"));
            param.put("bookstatus",getPara("bookstatus"));
            List<Record> list = service.book_export(param);

            LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
            headMap.put("isbn", "ISBN");
            headMap.put("title", "正题名");
            headMap.put("author", "著者");
            headMap.put("publisher", "出版社");
            headMap.put("publishaddress", "出版地");
            headMap.put("price", "定价（元）");
            headMap.put("bookno", "索书号");
            headMap.put("booknum", "复本数");
            try {
                ExcelExportUtil.listToExcel(list,headMap, "馆藏图书清单", this.getResponse());
            } catch (Exception e) {
                e.printStackTrace();
            }
            success();
        }catch(Exception e){
            logger.error("",e);
            fail();
        }
    }

    public void periodical_export(){
        try {
            int orgid = ((User) this.getSessionAttr("userInfo")).getOrgid();

            Map param = new HashMap();

            if(CommonUtils.isNotNullOrNotEmpty(getPara("issnorkanming"))){
                param.put("issnorkanming",getPara("issnorkanming"));
            }
            if(CommonUtils.isNotNullOrNotEmpty(getPara("chubanpinlv"))) {
                param.put("chubanpinlv",getPara("chubanpinlv"));
            }
            if(CommonUtils.isNotNullOrNotEmpty(getPara("issn")) && !"null".equals(getPara("issn"))) {
                param.put("issn",getPara("issn"));
            }
            param.put("orgid",getPara("orgid"));

            List<Record> list = service.periodical_export(orgid,param);

            LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
            headMap.put("kanming", "刊名");
            headMap.put("bianjibu", "编辑部");
            headMap.put("issn", "ISSN");
            headMap.put("tongyikanhao", "统一刊号");
            headMap.put("youfadaihao", "邮发代号");
            headMap.put("chubanpinlv", "出版频率");
            headMap.put("bookno", "索刊号");
            headMap.put("niandu", "年度");
            headMap.put("qizhiqi", "起止期");
            headMap.put("price", "价格");
            headMap.put("num", "复本数");
            try {
                ExcelExportUtil.listToExcel(list,headMap, "馆藏期刊清单", this.getResponse());
            } catch (Exception e) {
                e.printStackTrace();
            }
            success();
        }catch(Exception e){
            logger.error("",e);
            fail();
        }
    }

    public void mulukadayinPage(){
        render("/view/print/mulukadayin.html");
    }

    public void mulukadayin(){
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        String title = getPara("title");
        String isbn = getPara("isbn");
        String bookno = getPara("bookno");
        String publisher = getPara("publisher");
        //String title = getPara("title");
        String typecode = getPara("typecode");

        int pageNumber = 1;
        if (this.getParaToInt("pageNumber", 0) > 0) {
            pageNumber = getParaToInt("pageNumber");
        }
        int pageSize = this.getParaToInt("pageSize", PAGESIZE);
        Page<Record> page = service.mulukadayin(orgid,title,isbn,bookno,publisher,typecode,pageNumber,pageSize);

        Record r = Db.findFirst("SELECT * FROM t_org_setting WHERE orgid = ?",orgid);
        List reList = new ArrayList();
        for(Record record : page.getList()) {
            int id = record.getInt("id");
            List<Record> recordList = Db.find("SELECT cast(REPLACE(b.barcode,(select ifnull(tstiaoxingmaqianzhui,'') from t_org_setting where orgid = a.orgid), '') as UNSIGNED INTEGER) barcode FROM t_book a INNER JOIN t_book_detail b ON a.id = b.bookid where bookid=? order by barcode asc",id);
            List<Record> detailList = barcodeOrder(recordList,r);
            record.set("barcodeList",detailList);
            reList.add(record);
        }
        success(page);
    }

    public void mulukadayin_all(){
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        String title = getPara("title");
        String isbn = getPara("isbn");
        String bookno = getPara("bookno");
        String publisher = getPara("publisher");
        String typecode = getPara("typecode");
        List<Record> list= service.mulukadayin(orgid,title,isbn,bookno,publisher,typecode);
        Record r = Db.findFirst("SELECT * FROM t_org_setting WHERE orgid = ?",orgid);
        List reList = new ArrayList();
        for(Record record : list) {
            int id = record.getInt("id");
            List<Record> recordList = Db.find("SELECT cast(REPLACE(b.barcode,(select ifnull(tstiaoxingmaqianzhui,'') from t_org_setting where orgid = a.orgid), '') as UNSIGNED INTEGER) barcode FROM t_book a INNER JOIN t_book_detail b ON a.id = b.bookid where bookid=? order by barcode asc",id);
            List<Record> detailList = barcodeOrder(recordList,r);
            record.set("barcodeList",detailList);
            reList.add(record);
        }
        success(reList);
    }

    private List barcodeOrder(List<Record> barcodeList,Record settingRecord){
        String tstiaoxingmaqianzhui = settingRecord.getStr("tstiaoxingmaqianzhui");
        if(CommonUtils.isNullOrEmpty(tstiaoxingmaqianzhui)) {
            tstiaoxingmaqianzhui = "";
        }
        int tstiaoxinmaweishu = settingRecord.getInt("tstiaoxinmaweishu");
        List reList = new ArrayList();
        StringBuffer barcodeStr = new StringBuffer();
        BigInteger check = BigInteger.ZERO;
        for (int i = 0; i < barcodeList.size(); i ++) {
            BigInteger start = (barcodeList.get(i)).get("barcode");
            if(i == 0) {
                check = start;
            }
            if(barcodeList.size() > i+1) {
                BigInteger next = (barcodeList.get(i+1)).get("barcode");
                //如果下个条码-1 等于当前条码 则说明是连续的。
                if(check.compareTo(next.subtract(BigInteger.ONE)) == 0) {
                    check = next;
                    if ("".equals(barcodeStr.toString())) {
                        barcodeStr.append(formatBarcode(start, tstiaoxinmaweishu, tstiaoxingmaqianzhui));
                    }
                } else {
                    if ("".equals(barcodeStr.toString())) {
                        barcodeStr.append(formatBarcode(start, tstiaoxinmaweishu, tstiaoxingmaqianzhui));
                    }else {
                        barcodeStr.append("-").append(formatBarcode(check, tstiaoxinmaweishu, tstiaoxingmaqianzhui));
                    }
                    reList.add(barcodeStr.toString());
                    barcodeStr = new StringBuffer();
                    check = next;
                }
            } else {
                if(barcodeList.size() == 1) {
                    barcodeStr.append(formatBarcode(start, tstiaoxinmaweishu, tstiaoxingmaqianzhui));
                    reList.add(barcodeStr.toString());
                    barcodeStr = new StringBuffer();
                }else{
                    if ("".equals(barcodeStr.toString())) {
                        barcodeStr.append(formatBarcode(start, tstiaoxinmaweishu, tstiaoxingmaqianzhui));
                    }else {
                        barcodeStr.append("-").append(formatBarcode(check, tstiaoxinmaweishu, tstiaoxingmaqianzhui));
                    }
                    reList.add(barcodeStr.toString());
                }
            }
        }
        return reList;
    }

    public String formatBarcode(BigInteger bi, int tiaomaweishu, String tiaomaqianzui){
        if(CommonUtils.isNullOrEmpty(tiaomaqianzui)){
            tiaomaqianzui = "";
        }
        String barcode = bi+"";
        String zerostr = "0000000000000000000000000000";
        int bulingcount = tiaomaweishu - barcode.length();
        if(bulingcount>=0) {
            String tempStr = zerostr.substring(0,bulingcount);
            return tiaomaqianzui + tempStr + barcode;
        }else {
            return "";
        }
    }


}
