package com.controller;

import com.alibaba.fastjson.JSON;
import com.config.BaseController;
import com.config.ControllerInterface;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
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.upload.UploadFile;
import com.model.*;
import com.service.*;
import com.tools.ISBNTools;
import com.tools.JwtUtils;
import com.utils.*;
import com.validator.BookValidator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import javax.sound.midi.SysexMessage;
import java.beans.IntrospectionException;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.List;

/**
 * 图书操作
 * 2018-10-23
 * zj
 */
@ControllerInterface(path="/book")
public class BookController extends BaseController {
    BookService service = BookService.me;
    BookYubianService yubianService = BookYubianService.me;
    BookPiciService bookpiciService = BookPiciService.me;
    LibraryService libraryService = LibraryService.me;
    SysConfigService sysConfigService = SysConfigService.me;
    DictService dictService = DictService.me;
    DictExtService dictExtService = DictExtService.me;


    public void index() {
        render("/view/index/index.html");
    }
    public void leakDetection() {
        render("/view/catalogue/leak-detection/barcode.html");
    }

    public void librarybook(){
        render("/view/library/librarybook.html");
    }

    public void librarybookSigle(){
        render("/view/library/librayBookSigle.html");
    }

    public void checkBookPage(){
        render("/view/list-manage/checkBookList.html");
    }

    /**
     * 临时用用
     */
    /*@Clear
    public void deletetemp(){

        Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                try {
                    List<Book> list = new Book().dao().find("select id from t_book where orgid=121294");
                    StringBuilder sb = new StringBuilder("");
                    for (Book b : list) {
                        sb.append(","+b.get("id"));
                    }
                    Db.delete("delete from t_book_detail where bookid in ("+sb.substring(1)+") ");
                    Db.delete("delete from t_book_plus where bookid in ("+ sb.substring(1)+")");
                    Db.delete("delete from t_book where orgid=121294");
                }catch(Exception e){
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
        });
        success();
    }*/

    public void uploadMarc() {
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if (operatorid == 0) {
            fail(3, "token错误");
            return;
        }

        List errorDataList = new ArrayList();
//        File targetFile =new File(getRequest().getRealPath("upload")+"/"+filename);
//        File targetFile =new File("D:/123.iso");
        int orgid = getParaToInt("orgid");
        Record orgRecord = Db.findById("t_org",orgid);
        OrgSetting orgSetting = sysConfigService.findOrgSetting(orgid);
        if(CommonUtils.isNullOrEmpty(orgSetting)) {
            fail(1,"数据异常!");
            return;
        }
        if(CommonUtils.isNullOrEmpty(orgRecord)) {
            fail(1,"数据异常!");
            return;
        }
        String orgname = orgRecord.getStr("orgname");
        UploadFile file =getFile();
        List<String> bookLineStrList = null;
        try {
            bookLineStrList = FileUtils.readLines(file.getFile(),"GBK");
        } catch (IOException e) {
            e.printStackTrace();
        }

        int libraryid = 0;
        String libraryname = "";
        Calendar calendar = Calendar.getInstance();

        Record libraryRecord = Db.findFirst("select * from t_library where orgid = ? order by id limit 0,1", orgid);
        if(CommonUtils.isNullOrEmpty(libraryRecord)){
            Library library = new Library();
            library.setOrgid(orgid);
            library.setLibrary(format1.format(calendar.getTime())+"MARC导入");
            library.setDefaultlibrary(1);
            library.setCreatetime(calendar.getTime());
            library.setIsopen(1);
            library.setArea(BigDecimal.TEN);
            library.save();
            libraryid =library.getId();
            libraryname = library.getLibrary();
        } else {
            libraryid = libraryRecord.getInt("id");
            libraryname = libraryRecord.get("library");
        }


        int piciid = 0;
        Record bookpiciRecord = Db.findFirst("select * from t_bookpici where orgid = ? and batchname = ?",orgid,format1.format(calendar.getTime())+"MARC导入批次");
        if(CommonUtils.isNullOrEmpty(bookpiciRecord)){
            Bookpici bookpici = new Bookpici();
            bookpici.setOrgid(orgid);
            bookpici.setDictid(52);
            bookpici.setBatchname(format1.format(calendar.getTime())+"MARC导入批次");
            bookpici.setCreatetime(calendar.getTime());
            bookpici.setOperatorid(1);
            bookpici.save();
            piciid = bookpici.getId();
        } else {
            piciid = bookpiciRecord.getInt("id");
        }

        Map<String,Integer> dictmap = dictService.dictmap();
        List<Record> expRecordList = Db.find("select CONCAT(fieldid,subfieldid) exp,sysfield formname from t_sysmkf where formname is not null");
        System.out.println("导入marc的总种类："+bookLineStrList.size());
        int total = 0;
        for (String bookStr : bookLineStrList){
            try {
                List<Map<String, String>> list = null;
                Record marcRecord;
                try {
                    list = MarcUtil.showMarc(bookStr.getBytes("GBK"));
                    if (list.size() == 0) {
                        System.out.println("marc导入失败：原因解析不出数据--》" + bookStr);
                        continue;
                    }
                    marcRecord = MarcUtil.mapToRecord(list.get(0), expRecordList);
                } catch (Exception e) {
                    System.out.println("marc导入失败：原因marc字符串转对象报错--》" + bookStr);
                    e.printStackTrace();
                    continue;
                }
                //处理馆藏地


                Book book = new Book();
                book.setOrgid(orgid);
                String typecode = marcRecord.get("typecode");
                if (CommonUtils.isNullOrEmpty(typecode)) {
                    logger.info("分类号不能为空");
                    System.out.println("marc导入失败：原因分类号不能为空--》" + bookStr);
                    continue;
                }
                book.setBooknum(0);
                book.setOperatorid(operatorid);
                book.setTypecode(typecode);
                book.setBookno(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("bookno")) ? marcRecord.getStr("bookno") : "");
                book.setTypeid(typecode.substring(0, 1));//22大类ID
                //book.setTypecommonid()  //通俗分类id
                try {
                    book.setShucihao(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("shucihao")) ? Integer.parseInt(marcRecord.getStr("shucihao")) : 1);
                } catch (Exception e) {
                    book.setShucihao(null);
                }
                book.setIsbn(ISBNTools.fmtisbn(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("isbn")) ? marcRecord.getStr("isbn") : ""));
                book.setTitle(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("title")) ? marcRecord.getStr("title") : "");
                book.setPublisher(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("publisher")) ? marcRecord.getStr("publisher") : "");
                book.setKeyword(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("keyword")) ? marcRecord.getStr("keyword") : "");
//                    book.setEdition(bookMap.get("版本版次"));
                book.setAuthor(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("author")) ? marcRecord.getStr("author") : "");

                book.setAuthorworkmodeid(dictmap.get(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("authorworkmode")) ? marcRecord.getStr("authorworkmode") : ""));
                if (book.getAuthorworkmodeid() == null) {
                    book.setAuthorworkmodeid(7);// 著作方式 默认编著
                }
//                    int guobieid = guobieMap.get(bookMap.get("国别、朝代"));
//                    if (guobieid == 0){
//                        errorDataList.add(bookMap);
//                        bookMap.put("失败原因","国别、朝代列的值不正确");
//                        continue;
//                    }
//                    book.setAuthorguobieid(guobieid);
                book.setPublishdate(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("publishdate")) ? marcRecord.getStr("publishdate") : "");
                book.setPublishaddress(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("publishaddress")) ? marcRecord.getStr("publishaddress") : "");
                try {
                    book.setPrice(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("price")) ? new BigDecimal(marcRecord.getStr("price")) : null);
                } catch (Exception e) {
                    book.setPrice(null);
                }

                book.setCreatetime(new Date());
                book.setOperatorid(operatorid);

//                    book.setNewsource(bookMap.get("图书新增来源"));
//                    book.setOperatorid(operatorid);
                BookPlus bookPlus = new BookPlus();
                bookPlus.setBltitle(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("bltitle")) ? marcRecord.getStr("bltitle") : null);
                bookPlus.setSubtitle(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("subtitle")) ? marcRecord.getStr("subtitle") : null);
                bookPlus.setOtherauthor(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("otherauthor")) ? marcRecord.getStr("otherauthor") : null);
                try {
                    bookPlus.setTotalpages(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("totalpages")) ? Integer.parseInt(marcRecord.getStr("totalpages")) : null);
                } catch (Exception e) {
                    bookPlus.setTotalpages(null);
                }
                bookPlus.setSizeid(dictmap.get(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("sizeid")) ? marcRecord.getStr("sizeid") : ""));
                bookPlus.setFilesurl(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("filesurl")) ? marcRecord.getStr("filesurl") : null);
                bookPlus.setBindingid(dictmap.get(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("bindingid")) ? marcRecord.getStr("bindingid") : ""));
                bookPlus.setCongshuming(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("congshuming")) ? marcRecord.getStr("congshuming") : null);
                bookPlus.setCongshuauthor(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("congshuauthor")) ? marcRecord.getStr("congshuauthor") : null);
                bookPlus.setJuanci(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("juanci")) ? marcRecord.getStr("juanci") : null);
                if (CommonUtils.isNotNullOrNotEmpty(marcRecord.get("fuzhu"))) {
                    if (marcRecord.getStr("fuzhu").length() > 100) {
                        bookPlus.setFuzhu(marcRecord.getStr("fuzhu").substring(0, 100));
                    } else {
                        bookPlus.setFuzhu(marcRecord.getStr("fuzhu"));
                    }
                }
//            bookPlus.setFuzhu(CommonUtils.isNotNullOrNotEmpty(marcRecord.get("fuzhu"))?marcRecord.getStr("fuzhu"):null);
//                    bookPlus.setMoneysource(bookMap.get("经费来源"));
////                    bookPlus.setArrivedate(bookMap.get("到馆日"));
                BookDetail bookDetail = new BookDetail();

                bookDetail.setPiciid(piciid);

                if (CommonUtils.isNullOrEmpty(marcRecord.get("barcode"))) {
                    logger.info("条形码不能为空");
                    System.out.println("marc导入失败：原因条形码为空--》" + bookStr);
                    continue;
                }
                int check = 0;
                Book checkBook = service.findBookByBooknoTitle(book.getOrgid(), book.getBookno(), book.getTitle(), book.getIsbn(), book.getPublisher(), book.getAuthor());
                if (CommonUtils.isNotNullOrNotEmpty(checkBook)) {
                    book = checkBook;
                    check = 1;
                }
                String barcodeStr = marcRecord.getStr("barcode");
                String[] barcodes = barcodeStr.split("\\|");
                total=barcodes.length;
                //System.out.println("marc:"+total);
                int one = 0;

                for (int i = 0; i < barcodes.length; i++) {
                    String barcode = barcodes[i];

                    if (StringUtils.isNotBlank(marcRecord.get("library"))) {
                        String librarynames = marcRecord.getStr("library");
                        String[] librarys = librarynames.split("\\|");

                        if (!libraryname.equals(librarys[i])) {
                            Record libraryRecord2 = Db.findFirst("select * from t_library where orgid = ? and library=? ", orgid, librarys[i]);
                            if (CommonUtils.isNullOrEmpty(libraryRecord2)) {
                                Library library = new Library();
                                library.setOrgid(orgid);
                                library.setLibrary(librarys[i]);
                                library.setDefaultlibrary(1);
                                library.setCreatetime(calendar.getTime());
                                library.setIsopen(1);
                                library.setArea(BigDecimal.TEN);
                                library.save();
                                libraryid = library.getId();
                                libraryname = library.getLibrary();
                            } else {
                                libraryid = libraryRecord2.getInt("id");
                                libraryname = libraryRecord2.get("library");
                            }
                        }

                    }
                    bookDetail.setLibraryid(libraryid);

                    barcode = CommonUtils.formatBarcode(barcode, orgSetting);
                    int count = service.findByBarcode(orgid, barcode);
                    if (count > 0) {
                        logger.info("条形码重复");
                        System.out.println("marc导入失败：原因条形码重复--》" + bookStr);
                        continue;
                    }
                    bookDetail.setId(null);
                    bookDetail.setBarcode(barcode);
                    bookDetail.setBookstatus(0);
                    bookDetail.setCreatetime(new Date());
                    bookDetail.setOperatorid(operatorid);
                    if (0 == check) {
                        try {
                            book.setBooknum(1);
                            book.save();
                            bookPlus.setBookid(book.getId());
                            bookPlus.save();
                            check = 1;
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("marc导入失败：原因保存报错--》" + bookStr);
                            break;
                        }
                    } else {
                        if (CommonUtils.isNullOrEmpty(book.getBooknum())) {
                            book.setBooknum(0);
                        }
                        book.setBooknum(book.getBooknum() + 1);
                        book.update();
                    }
                    bookDetail.setBookid(book.getId());
                    bookDetail.save();
                    //线程上传z3950
                    MyThread mt = new MyThread(barcode, book, bookPlus, orgname);    // 实例化对象
                    mt.start();
                    one++;
                }
                if(total>one){
                    System.out.println("marc又问题："+bookStr);
                }
            }catch(Exception e){
                System.out.println("marc导入失败：原因for循环里面报错--》"+bookStr);
                e.printStackTrace();
            }
        }
        System.out.println("marc导入完成");
        if(errorDataList.size() > 0) {
            success();
        }else {
            success("导入成功");
        }
    }


    public void list(){
        try{
            Book bean = getBean(Book.class,"bean");
            //根据时间排序 timesortd正序 timesorta倒序
            String orderby = this.getPara("orderby");
            String bookstatus = getPara("bookstatus");
            String status = getPara("status");
            Integer library = getParaToInt("library");
            String viewtype = getPara("viewtype");
            String startTime = this.getPara("startDate");
            String endTime = this.getPara("endDate");

            success(service.paginate(this.getParaToInt("pageNumber"),this.getParaToInt("pageSize"),this.getParaToInt("pageSize",PAGESIZE),orderby,bean,  bookstatus,status,library,viewtype,startTime,endTime));
        }catch(Exception e){
            e.printStackTrace();
            fail();
        }
    }





    public void getById(){
        int id =this.getParaToInt("bean.id", 0);
        if(id == 0){
            fail();
            return;
        }
        success(service.findById(id));
    }

    public void findBookInfoById(){
        int id =this.getParaToInt("id", 0);
        if(id == 0){
            fail();
            return;
        }
        success(service.findBookInfoById(id));
    }

    /**
     * 馆藏图书使用
     */
    public void findBookInfo(){
        int id =this.getParaToInt("id", 0);
        if(id == 0){
            fail();
            return;
        }
        success(service.findBookInfo(id));
    }

    public void formatISBN(){
        String isbn = getPara("isbn");
        success(ISBNTools.fmtisbn(isbn));
    }

    //增加
    @Before(BookValidator.class)
    public void addOrUpdate(){
        //必填信息
        Book bean = getBean(Book.class,"bean");
        if(CommonUtils.isNotNullOrNotEmpty(bean.getBookno())){
            bean.setBookno(bean.getBookno().toUpperCase());
        }
        //附加信息
        BookPlus beanPlus = getBean(BookPlus.class,"beanPlus");
        //图书明细信息(精确到复本)
        BookDetail beanDetail = getBean(BookDetail.class,"beanDetail");
        String token = this.getPara("token");
        String[] txm = this.getParaValues("barcode");
        String[] gcd = this.getParaValues("libraryid");
        try {
            int operatorid = JwtUtils.validateJWTForUserId(token);
            if(operatorid == 0){
                fail(3,"token错误");
                return;
            }
            service.addOrUpdate(bean,beanPlus,beanDetail,txm,gcd,operatorid);
            success();
        }catch(Exception e){
            e.printStackTrace();
            fail();
        }
    }

    public void addOrUpdateBookBaseInfo(){
        try{
            String token = this.getPara("token");
            int operatorid = JwtUtils.validateJWTForUserId(token);
            if(operatorid == 0){
                fail(3,"token错误");
                return;
            }
            Book bean = getBean(Book.class,"bean");
            bean.setTypeid(bean.getTypecode().substring(0,1)).setOperatorid(operatorid);
            //附加信息
            BookPlus beanPlus = getBean(BookPlus.class,"beanPlus");

            bean.update();

            beanPlus.update();
        }catch (Exception e){
            fail();
        }


        success();
    }

        //删除
    public void delete(){
        int id =this.getParaToInt("bean.id");
        service.deleteById(this.getParaToInt("bean.id", 0));
        success();
    }

    public void deleteBookByIds(){
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        String ids = getPara("ids");
        if(CommonUtils.isNullOrEmpty(ids)){
            fail(1,"请求参数不完整!");
            return;
        }
        Db.delete("delete from t_book_detail where bookid in ( select id from t_book where orgid = ? and id in ("+ids+")) and bookstatus = 0",orgid);
        success();
    }


    /**
     * 图书上架
     *
     */
    public void upperShelf(){
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        String catalogUserId = this.getPara("catalogUserId");
        String guancangId = this.getPara("guancangId");
        String startTime = this.getPara("startTime");
        String endTime = this.getPara("endTime");
        service.upperShelf(orgid,catalogUserId,guancangId,startTime,endTime);
        success();
    }

    /**
     * 编目统计  如果book表中的typeid不存在则会报错
     *
     */
    public void listCount(){
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        String startTime = this.getPara("startTime");
        String endTime = this.getPara("endTime");
        success(service.listCount(orgid,startTime,endTime));
    }
    /**
     * 编目统计合计
     */
//    public void listCountTotal(){
//        int orgid = this.getParaToInt("orgid",0);
//        if(orgid == 0) {
//            fail(1,"请求参数不完整!");
//            return;
//        }
//        String startTime = this.getPara("startTime");
//        String endTime = this.getPara("endTime");
//        success(service.listCountTotal(orgid,startTime,endTime));
//    }

    /**
     * 书标打印列表
     *
     */
    public void bookmarkPrinting(){
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        Integer libraryid = this.getParaToInt("libraryid");
        Integer piciid = this.getParaToInt("piciid");
        Integer username = this.getParaToInt("username");
        Integer upperShelf = this.getParaToInt("upperShelf");
        String title = this.getPara("title");
        String barcode1 = this.getPara("barcode1");
        String barcode2 = this.getPara("barcode2");
        String startDate = this.getPara("startDate");
        String endDate = this.getPara("endDate");
        Integer ordertype = this.getParaToInt("ordertype",0);
        Integer orderby = this.getParaToInt("orderby",0);
        success(service.bookmarkPrinting(this.getParaToInt("pageNumber"),this.getParaToInt("pageSize"),orgid,libraryid,piciid,username,upperShelf,title,barcode1,barcode2,startDate,endDate,ordertype,orderby));

    }
    /**
     * 书标打印 打印
     *
     */
    public void bookmarkPrintingS(){
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        Integer libraryid = this.getParaToInt("libraryid");
        Integer piciid = this.getParaToInt("piciid");
        Integer username = this.getParaToInt("username");
        Integer upperShelf = this.getParaToInt("upperShelf");
        String title = this.getPara("title");
        String barcode1 = this.getPara("barcode1");
        String barcode2 = this.getPara("barcode2");
        String startDate = this.getPara("startDate");
        String endDate = this.getPara("endDate");
        success(service.bookmarkPrintingS(orgid,libraryid,piciid,username,upperShelf,title,barcode1,barcode2,startDate,endDate));

    }

    /**
     * 通过(ISBN或正题名)和机构id获取图书信息(包括馆藏，回溯和Z39.50服务数据)
     * queryStr 查询字段
     * queryType 查询类型 1：ISBN 2：正题名
     */
    public void findBookListByISBNOrZTM(){
        String queryStr = this.getPara("queryStr");
        String queryType = this.getPara("queryType");
        Integer pageSize = this.getParaToInt("pageSize",100);
        Integer pageNumber = this.getParaToInt("pageNumber",1);
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        //z39.50服务获取相关信息
        Map result = new HashMap();
        List guancangList = new ArrayList();
        List yubianList = new ArrayList();
        Record record = Db.findFirst("select * from t_org_setting where orgid = ?",orgid);
        String username = null;
        String password = null;
        if(CommonUtils.isNotNullOrNotEmpty(record)) {
            username = record.get("username");
            password = record.get("password");
        }
        String queryZTMUrl = null;
        try {
            queryZTMUrl = PropKit.get("z3950url")+"/marcdata/index?ztm=" + URLEncoder.encode(queryStr,"UTF-8") + "&pageSize="+pageSize + "&pageNumber="+pageNumber;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Map reMap = new HashMap();
        if("1".equals(queryType)) {
            queryStr = ISBNTools.fmtisbn(queryStr.trim());
            String queryISBNUrl = PropKit.get("z3950url")+"/marcdata/index?isbn=" + queryStr+ "&pageSize="+pageSize + "&pageNumber="+pageNumber;
            result = CommonUtils.z3950serverTolist(queryISBNUrl);
            guancangList = service.findByISBN(orgid,queryStr);
            yubianList = yubianService.findByISBN(orgid,queryStr);
            if(queryStr.length() == 17){
                queryStr = queryStr.substring(4);
            }
            if(queryStr.length() == 13) {
                Record publisherRecord = Db.findFirst("select * from t_isbn where LOCATE(isbn,?)>0",queryStr.substring(0,queryStr.indexOf("-",2)));
                reMap.put("publisher",publisherRecord);
            }
        }else if("2".equals(queryType)) {
            result = CommonUtils.z3950serverTolist(queryZTMUrl);
            guancangList = service.findByZTM(orgid,queryStr);
            yubianList = yubianService.findByZTM(orgid,queryStr);
        }
        reMap.put("guancangList",guancangList);
        reMap.put("yubianList",yubianList);
        reMap.put("zList",result);
        if(null == username || null == password) {
            reMap.put("z3950Status",0);
        } else {
            reMap.put("z3950Status",1);
        }
        success(reMap);
    }

    /**
     * 抓取z3950服务数据
     */
    public void getZ3950Server(){
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        Record record = Db.findFirst("select * from t_org_setting where orgid = ?",orgid);
        if(CommonUtils.isNullOrEmpty(record)) {
            fail(1,"抱歉，您尚未购买Z39.50服务，不能下载书目信息! 若需购买此服务，欢迎联系客服咨询。QQ：2212730512，电话号码：0731-85357311");
            return;
        }
        String username = record.get("username");
        String pswd = record.get("password");
        if(null == username || null == pswd) {
            fail(1,"抱歉，您尚未购买Z39.50服务，不能下载书目信息! 若需购买此服务，欢迎联系客服咨询。QQ：2212730512，电话号码：0731-85357311");
            return;
        }
        String z3950serverid = getPara("z3950serverid");
        String getUrl = PropKit.get("z3950url")+"/marcdata/getById?username="+username+"&password="+pswd+"&id=" + z3950serverid;
        String z3950str = CommonUtils.requestUrl(getUrl);
        List<Record> expRecordList = Db.find("select CONCAT(fieldid,subfieldid) exp,formname from t_sysmkf where formname is not null");
        try {
            Map result = (Map)JSON.parse(z3950str);
            //调用成功
            if ("200".equals(result.get("code")+"")){
                Map data = (Map) result.get("data");
                String marcf = data.get("marcf")+"";
                byte[] bytes = marcf.getBytes("GBK");
                List<Map<String,String>> list = MarcUtil.showMarc(bytes);
                if(null == list || list.size() != 1) {
                    fail(1,"数据异常!");
                    return;
                }
                Record marcRecord = MarcUtil.mapToRecord(list.get(0),expRecordList);
                if (CommonUtils.isNotNullOrNotEmpty(data.get("lastdate"))){
                    marcRecord.set("lastdate",data.get("lastdate"));
                }
                success(marcRecord);
            }else {
                fail(1,result.get("msg")+"");
                return;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public void notRemindZ3950(){
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        Record record = Db.findFirst("select * from t_org_setting where orgid = ?",orgid);
        if(CommonUtils.isNullOrEmpty(record)) {
            fail(1,"抱歉，您尚未购买Z39.50服务，不能下载书目信息! 若需购买此服务，欢迎联系客服咨询。QQ：2212730512，电话号码：0731-85357311");
            return;
        }
        String username = record.get("username");
        String psd = record.get("password");
        if(null == username || null == psd) {
            fail(1,"抱歉，您尚未购买Z39.50服务，不能下载书目信息! 若需购买此服务，欢迎联系客服咨询。QQ：2212730512，电话号码：0731-85357311");
            return;
        }
        String getUrl = PropKit.get("z3950url")+"/marcdata/notRemind?username="+username+"&password="+psd;
        String z3950str = CommonUtils.requestUrl(getUrl);
        Map result = (Map)JSON.parse(z3950str);
        //调用成功
        if ("200".equals(result.get("code")+"")){
            success("操作成功");
        }else {
            fail(1,result.get("msg")+"");
            return;
        }
    }

    /**
     * 通过条件查询编目书本列表
     */
    public void findBookList(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        String catalogUserId = this.getPara("catalogUserId");
        String barcode = this.getPara("barcode");
        String startTime = this.getPara("startTime");
        String endTime = this.getPara("endTime");
        String title = this.getPara("titlestr");
        String author = this.getPara("authorstr");
        String publisher = this.getPara("publisherstr");
        Page page = service.findBookList_bianmu(this.getParaToInt("pageNumber"),this.getParaToInt("pageSize"),orgid,catalogUserId,barcode,startTime,endTime,title,author,publisher,operatorid);
        success(page);
    }

    public void exportBookList(){
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        String catalogUserId = this.getPara("catalogUserId");
        String guancangId = this.getPara("guancangId");
        String startTime = this.getPara("startTime");
        String endTime = this.getPara("endTime");
        List list = service.findBookList(orgid,catalogUserId,guancangId,startTime,endTime);

        LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("isbn", "ISBN");
        headMap.put("title", "正题名");
        headMap.put("author", "著者");
        headMap.put("publisher", "出版社");
        headMap.put("price", "定价");
        headMap.put("bookno", "索书号");
        headMap.put("counts", "复本数");
        headMap.put("createtime", "编目时间");
        headMap.put("realname", "编目人");

        try {
            ExcelExportUtil.listToExcel(list,headMap, "图书编目清单", this.getResponse());
        } catch (Exception e) {
            e.printStackTrace();
        }
        success();
    }

    /**
     * 根据机构id获取到该机构下的管理员列表和馆藏地址列表
     */
    public void initBookList(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        success(service.initBookList(orgid,operatorid));
    }

    /**
     * 查询配置信息
     */
    public void orgSetting(){
        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        Record record = Db.findFirst("select * from t_org_setting where orgid = ?",orgid);
        record.set("banben",PropKit.get("banben"));
        if(CommonUtils.isNotNullOrNotEmpty(record)) {
            success(record);
        } else {
            fail();
        }
    }

    /**
     * 编目信息保存
     */
    @Before(BookValidator.class)
    public synchronized void saveBookInfo(){
        String beanStr = getPara("bean");
        String beanPlusStr = getPara("beanPlus");
        logger.info("编目保存书籍信息 beanStr："+beanStr);
        logger.info("编目保存书籍信息 beanPlusStr："+beanPlusStr);
        Boolean uploadFlag = this.getParaToBoolean("upload");
        List<Book> bookList = JSON.parseArray("["+beanStr+"]",Book.class);
        if(null == bookList || bookList.size() != 1 || CommonUtils.isNullOrEmpty(uploadFlag)) {
            fail(1,"请求参数不完整!");
            return;
        }
        Book bean = bookList.get(0);
        List<BookPlus> bookPlusList = JSON.parseArray("["+beanPlusStr+"]",BookPlus.class);
        if(null == bookPlusList || bookPlusList.size() != 1) {
            fail(1,"请求参数不完整!");
            return;
        }
        if(CommonUtils.isNotNullOrNotEmpty(bean.get("authorworkmodeid"))) {
            bean.put("workmodeid",bean.get("authorworkmodeid"));
        }
        if(CommonUtils.isNotNullOrNotEmpty(bean.get("authorguobieid"))) {
            bean.put("guobieid",bean.get("authorguobieid"));
        }
        BookPlus beanPlus = bookPlusList.get(0);

        String jstr = this.getPara("bookDetailJsonStr");
        logger.info("编目保存书籍信息 jstr："+jstr);
        String token = this.getPara("token");
        Map userinfo = JwtUtils.validateJWTForMap(token);
        if(userinfo == null){
            fail(3,"token错误");
            return;
        }
        String orgname = (String)userinfo.get("orgname");
        int operatorid = (Integer)userinfo.get("userid");
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }

        int orgid = this.getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(1,"请求参数不完整!");
            return;
        }
        StringBuffer bookno = new StringBuffer();
        bookno.append(bean.getTypecode());
        if(CommonUtils.isNotNullOrNotEmpty(bean.getShucihao())) {
            bean.setTypeid(bean.getTypecode().substring(0,1));
            bookno.append("/").append(bean.getShucihao());
            if(CommonUtils.isNotNullOrNotEmpty(bean.getEdition()) && Integer.parseInt(bean.getEdition()) > 1) {
                bookno.append("-").append(bean.getEdition());
            }
            if(CommonUtils.isNotNullOrNotEmpty(beanPlus.getJuanci())) {
                bookno.append(":").append(beanPlus.getJuanci());
                if(CommonUtils.isNotNullOrNotEmpty(beanPlus.getCeci())) {
                    bookno.append("(").append(beanPlus.getCeci()).append(")");
                }
            } else {
                if(CommonUtils.isNotNullOrNotEmpty(beanPlus.getCeci())) {
                    bookno.append(":").append(beanPlus.getCeci());
                }
            }
        }
        bean.setBookno(bookno.toString().toUpperCase());
        bean.setOrgid(orgid);

        //bean.put("org",)
        Book checkBook = service.findBookByBooknoTitle(bean.getOrgid(),bean.getBookno(),bean.getTitle(),bean.getIsbn(),bean.getPublisher(),bean.getAuthor());
        if(CommonUtils.isNullOrEmpty(bean.getId()) && CommonUtils.isNotNullOrNotEmpty(checkBook)) {
            bean = checkBook;
        }
        List<BookDetail> bookDetailList = JSON.parseArray(jstr,BookDetail.class);
        if(null == bookDetailList) {
            bookDetailList = new ArrayList();
        }
        List<BookDetail> checksuccessBookDetailList = new ArrayList();
        StringBuffer errorBarcode = new StringBuffer();
        for(BookDetail bookDetail:bookDetailList){
            int count = service.findByBarcode(orgid,bookDetail.getBarcode());
            if (count > 0) {
                errorBarcode.append(bookDetail.getBarcode()).append(",");
            } else{
                checksuccessBookDetailList.add(bookDetail);
            }
        }
        Date date = new Date();
        bean.setCreatetime(date);
        bean.setOperatorid(operatorid);
        if(CommonUtils.isNotNullOrNotEmpty(bean.getPublishdate())){
            if(bean.getPublishdate().length()==6){
                StringBuffer stringBuffer = new StringBuffer(bean.getPublishdate());
                stringBuffer.insert(4,".");
                bean.setPublishdate(stringBuffer.toString());
            }
        }
        if(!"".equals(errorBarcode.toString())) {
            success(errorBarcode.toString());
        } else {
            service.saveBookInfo(bean, beanPlus, checksuccessBookDetailList, operatorid);
            String isbn = bean.getIsbn();
            if(CommonUtils.isNotNullOrNotEmpty(isbn) && isbn.length() == 17){
                isbn = isbn.substring(4);
            }
            if(CommonUtils.isNotNullOrNotEmpty(isbn) && isbn.length() == 13) {
                String querystr = isbn.substring(0,isbn.indexOf("-",2));
                Record publisherRecord = Db.findFirst("select * from t_isbn where LOCATE(isbn,?)>0",querystr);
                if(CommonUtils.isNullOrEmpty(publisherRecord)){
                    Isbn isbnObj = new Isbn();
                    isbnObj.setIsbn(querystr);
                    isbnObj.setPublisher(bean.getPublisher());
                    isbnObj.setAddress(bean.getPublishaddress());
                    isbnObj.save();
                } else if(publisherRecord.get("publisher").toString().length() < bean.getPublisher().length()) {
                    publisherRecord.set("address",bean.getPublishaddress());
                    publisherRecord.set("publisher",bean.getPublisher());
                    Db.update("t_isbn",publisherRecord);
                }
            }
            //上传编目止z3950
            if (uploadFlag){
                try {
                    String getUrl = PropKit.get("z3950url")+"/bookyubian/addBookYubian";
                    Map<String,String> param  = CommonUtils.convertBeanToMap(bean);
                    if (CommonUtils.isNullOrEmpty(param)){
                        param = new HashMap();
                    }
                    Map bookPlus = CommonUtils.convertBeanToMap(beanPlus);
                    if (CommonUtils.isNotNullOrNotEmpty(bookPlus)){
                        param.putAll(bookPlus);
                    }
                    param.put("org",orgname);
                    getUrl = CommonUtils.buildUrl(getUrl,param);
                    String z3950str = CommonUtils.requestUrl(getUrl);
                    Map result = (Map)JSON.parse(z3950str);
                    //上传失败
                    if (!"200".equals(result.get("code")+"")){
                        logger.error("上传数据到z3950失败："+result.get("msg"));
                    }
                }catch (Exception e){
                    logger.error("上传数据到z3950失败："+ e);
                }

            }
            success("success");
        }
    }

    public void uploadFileToBook(){

        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if (operatorid == 0) {
            fail(3, "token错误");
            return;
        }

        Map userinfo = JwtUtils.validateJWTForMap(token);
        int orgid = getParaToInt("orgid");
        Map<String,Integer> piciMap = bookpiciService.bookpiciNameToIDMap(orgid);
        Map<String,Integer> libraryMap = libraryService.libraryNameToIDMap(orgid);
        OrgSetting orgSetting = sysConfigService.findOrgSetting(orgid);
        if(null == orgSetting) {
            fail(1,"数据异常!");
            return;
        }
        String orgname = (String)userinfo.get("orgname");
        List<Map<String,String>> errorDataList = new ArrayList<Map<String,String>>();
        UploadFile file =getFile();
        try {
            List<Map<String,String>> bookList= ExcelUtil.readExcel(new FileInputStream(file.getFile()));
            for (Map<String,String> bookMap : bookList) {
                try{
                    Map urlmap=new HashMap();


                    StringBuffer bookno = new StringBuffer();
                    Book book=new Book();
                    book.setOrgid(orgid);
                    String typecode= bookMap.get("分类号");
                    if (CommonUtils.isNullOrEmpty(typecode)){
                        logger.info("分类号不能为空");
                        bookMap.put("失败原因","分类号不能为空");
                        errorDataList.add(bookMap);
                        continue;
                    }
                    book.setBooknum(0);
                    book.setOperatorid(operatorid);
                    book.setTypecode(typecode);
                    bookno.append(typecode);
                    book.setTypeid(typecode.substring(0,1));//22大类ID

                    book.setIsbn(ISBNTools.fmtisbn(bookMap.get("ISBN")));
                    if (CommonUtils.isNullOrEmpty(bookMap.get("正题名"))){
                        logger.info("正题名不能为空");
                        bookMap.put("失败原因","正题名不能为空");
                        errorDataList.add(bookMap);
                        continue;
                    }
                    book.setTitle(bookMap.get("正题名"));
                    logger.info("导入-正题名："+bookMap.get("正题名"));
                    if (CommonUtils.isNullOrEmpty(bookMap.get("出版社"))){
                        logger.info("出版社不能为空");
                        bookMap.put("失败原因","出版社不能为空");
                        errorDataList.add(bookMap);
                        continue;
                    }
                    book.setPublisher(bookMap.get("出版社"));
//                    book.setKeyword(bookMap.get("主题词"));
//                    book.setEdition(bookMap.get("版本版次"));
                    if (CommonUtils.isNullOrEmpty(bookMap.get("著者"))){
                        logger.info("著者不能为空");
                        bookMap.put("失败原因","著者不能为空");
                        errorDataList.add(bookMap);
                        continue;
                    }
                    book.setAuthor(bookMap.get("著者"));

                    int shucihao = 1;
                    Record record = Db.findFirst("select shucihao from t_book where orgid = ? and typecode= ? order by shucihao desc limit 1",orgid,typecode);
                    if(CommonUtils.isNotNullOrNotEmpty(record) && CommonUtils.isNotNullOrNotEmpty(record.get("shucihao"))){
                        Record bookRecord;
                        if(CommonUtils.isNullOrEmpty(book.getIsbn())){
                            bookRecord = Db.findFirst("select id from t_book where (isbn = ? or isbn is null) and title = ? and publisher = ? and author = ? and orgid = ?","",book.getTitle(),book.getPublisher(),book.getAuthor(),orgid);
                        } else {
                            bookRecord = Db.findFirst("select id from t_book where isbn = ? and title = ? and publisher = ? and author = ? and orgid = ?",book.getIsbn(),book.getTitle(),book.getPublisher(),book.getAuthor(),orgid);
                        }
                        shucihao = record.getInt("shucihao");
                        if(CommonUtils.isNullOrEmpty(bookRecord)){
                            shucihao ++;
                        } else {
                            book.setId(bookRecord.getInt("id"));
                        }
                    }
                    book.setShucihao(shucihao);
                    bookno.append("/").append(shucihao);
//                    book.setBooknum(Integer.parseInt(bookMap.get("副本数量")));
//                    if(CommonUtils.isNullOrEmpty(bookMap.get("ISBN"))){
//                        logger.info("ISBN不能为空");
//                        bookMap.put("失败原因","ISBN不能为空");
//                        errorDataList.add(bookMap);
//                        continue;
//                    }
//
//                    int zzfsid = workmodeidMap.get(bookMap.get("著作方式"));
//                    if (zzfsid == 0){
//                        errorDataList.add(bookMap);
//                        bookMap.put("失败原因","著作方式列的值不正确");
//                        continue;
//                    }
//                    book.setAuthorworkmodeid(zzfsid);
//
//                    int guobieid = guobieMap.get(bookMap.get("国别、朝代"));
//                    if (guobieid == 0){
//                        errorDataList.add(bookMap);
//                        bookMap.put("失败原因","国别、朝代列的值不正确");
//                        continue;
//                    }
//                    book.setAuthorguobieid(guobieid);
                    if (CommonUtils.isNullOrEmpty(bookMap.get("出版年月"))){
                        logger.info("出版年月不能为空");
                        bookMap.put("失败原因","出版年月不能为空");
                        errorDataList.add(bookMap);
                        continue;
                    }
                    book.setPublishdate(bookMap.get("出版年月"));
                    if (CommonUtils.isNullOrEmpty(bookMap.get("出版地"))){
                        logger.info("出版地不能为空");
                        bookMap.put("失败原因","出版地不能为空");
                        errorDataList.add(bookMap);
                        continue;
                    }
                    book.setPublishaddress(bookMap.get("出版地"));
                    if (CommonUtils.isNullOrEmpty(bookMap.get("定价（元）"))){
                        logger.info("定价不能为空");
                        bookMap.put("失败原因","定价不能为空");
                        errorDataList.add(bookMap);
                        continue;
                    }
                    book.setCreatetime(new Date());
                    book.setOperatorid(operatorid);

                    book.setPrice(new BigDecimal(bookMap.get("定价（元）")));
//                    book.setNewsource(bookMap.get("图书新增来源"));
//                    book.setOperatorid(operatorid);
                    BookPlus bookPlus = new BookPlus();
//                    bookPlus.setBltitle(bookMap.get("并列题名"));
//                    bookPlus.setSubtitle(bookMap.get("副题名"));
//                    bookPlus.setOtherauthor(bookMap.get("其他责任者"));
                    if(CommonUtils.isNotNullOrNotEmpty(bookMap.get("页数"))) {
                        try{
                            int index = bookMap.get("页数").indexOf("页");
                            if(index > -1) {
                                String yeshu = bookMap.get("页数").replace("页","");
                                bookPlus.setTotalpages(Integer.parseInt(yeshu));
                            } else {
                                bookPlus.setTotalpages(Integer.parseInt(bookMap.get("页数").replace("页","")));
                            }
                        }catch (Exception e) {
                            logger.info("页数格式异常");
                            bookMap.put("失败原因","页数格式异常");
                            errorDataList.add(bookMap);
                            continue;
                        }
                    }
//
//                    int zzfs2id = workmodeidMap.get(bookMap.get("著作方式2"));
//                    if (zzfs2id == 0){
//                        errorDataList.add(bookMap);
//                        bookMap.put("失败原因","著作方式2列的值不正确");
//                        continue;
//                    }
//                    bookPlus.setWorkmodeid(zzfs2id);
//
//                    int gbcd2id = guobieMap.get(bookMap.get("国别、朝代2"));
//                    if (gbcd2id == 0){
//                        errorDataList.add(bookMap);
//                        bookMap.put("失败原因","国别、朝代2列的值不正确");
//                        continue;
//                    }
//                    bookPlus.setGuobieid(gbcd2id);
//
//                    int sizeid = sizeidMap.get(bookMap.get("尺寸"));
//                    if (sizeid == 0){
//                        errorDataList.add(bookMap);
//                        bookMap.put("失败原因","尺寸列的值不正确");
//                        continue;
//                    }
//                    bookPlus.setSizeid(sizeid);
//                    bookPlus.setFilesurl(bookMap.get("附件"));
//
//                    int languageid = languageidMap.get(bookMap.get("语种"));
//                    if (languageid == 0){
//                        errorDataList.add(bookMap);
//                        bookMap.put("失败原因","语种列的值不正确");
//                        continue;
//                    }
//                    bookPlus.setLanguageid(languageid);
//
//                    int bindingid = bindingidMap.get(bookMap.get("装订形式"));
//                    if (bindingid == 0){
//                        errorDataList.add(bookMap);
//                        bookMap.put("失败原因","装订形式列的值不正确");
//                        continue;
//                    }
//                    bookPlus.setBindingid(bindingid);
//                    bookPlus.setCongshuming(bookMap.get("丛书名"));
//                    bookPlus.setCongshuauthor(bookMap.get("丛书责任者"));

                    if(CommonUtils.isNotNullOrNotEmpty(bookMap.get("卷次"))) {
                        bookPlus.setJuanci(bookMap.get("卷次"));
                        bookno.append(":").append(bookMap.get("卷次"));
                    }

                    if(CommonUtils.isNullOrEmpty(bookMap.get("卷次")) && CommonUtils.isNotNullOrNotEmpty(bookMap.get("册次"))) {
                        bookPlus.setCeci(bookMap.get("册次"));
                        bookno.append(":").append(bookMap.get("册次"));
                    } else if(CommonUtils.isNotNullOrNotEmpty(bookMap.get("册次"))) {
                        bookPlus.setCeci(bookMap.get("册次"));
                        bookno.append("(").append(bookMap.get("册次")).append(")");
                    }

                    book.setBookno(bookno.toString().toUpperCase());
//                    bookPlus.setMoneysource(bookMap.get("经费来源"));
////                    bookPlus.setArrivedate(bookMap.get("到馆日"));
//                    bookPlus.setFuzhu(bookMap.get("附注"));
                    BookDetail bookDetail = new BookDetail();

                    if (CommonUtils.isNullOrEmpty(bookMap.get("馆藏地"))){
                        logger.info("馆藏地不能为空");
                        bookMap.put("失败原因","馆藏地不能为空");
                        errorDataList.add(bookMap);
                        continue;
                    }
                    try {
                        int libraryid = libraryMap.get(bookMap.get("馆藏地"));
                        if (libraryid == 0) {
                            logger.info("馆藏地列的值不正确");
                            bookMap.put("失败原因", "馆藏地列的值不正确");
                            errorDataList.add(bookMap);
                            continue;
                        }
                        bookDetail.setLibraryid(libraryid);
                    }catch (Exception e) {
                        logger.info("馆藏地不正确");
                        bookMap.put("失败原因","馆藏地不正确");
                        errorDataList.add(bookMap);
                        continue;
                    }
                    if (CommonUtils.isNullOrEmpty(bookMap.get("图书批次"))){
                        logger.info("图书批次不能为空");
                        bookMap.put("失败原因","图书批次不能为空");
                        errorDataList.add(bookMap);
                        continue;
                    }
                    try{
                        int piciid = piciMap.get(bookMap.get("图书批次"));
                        if (piciid == 0){
                            logger.info("批次列的值不正确");
                            bookMap.put("失败原因","批次列的值不正确");
                            errorDataList.add(bookMap);
                            continue;
                        }
                        bookDetail.setPiciid(piciid);
                    }catch (Exception e) {
                        logger.info("图书批次不正确");
                        bookMap.put("失败原因","图书批次不正确");
                        errorDataList.add(bookMap);
                        continue;
                    }
                    if (CommonUtils.isNullOrEmpty(bookMap.get("条形码"))){
                        logger.info("条形码不能为空");
                        bookMap.put("失败原因","条形码不能为空");
                        errorDataList.add(bookMap);
                        continue;
                    }
                    String barcode = CommonUtils.formatBarcode(bookMap.get("条形码"),orgSetting);
                    int count = service.findByBarcode(orgid,barcode);
                    if (count > 0) {
                        logger.info("条形码重复");
                        bookMap.put("失败原因","条形码重复");
                        errorDataList.add(bookMap);
                        continue;
                    }
//                    Book checkBook = service.findBookByBooknoTitle(book.getOrgid(),book.getBookno(),book.getTitle(),book.getIsbn(),book.getPublisher(),book.getAuthor());
//                    if(CommonUtils.isNotNullOrNotEmpty(checkBook)){
//                        book = checkBook;
//                    }
                    bookDetail.setBarcode(barcode);
                    bookDetail.setBookstatus(0);
                    bookDetail.setCreatetime(new Date());
                    bookDetail.setOperatorid(operatorid);
                    if(CommonUtils.isNullOrEmpty(book.getId())) {
                        book.save();
                        bookPlus.setBookid(book.getId());
                        bookPlus.save();
                    } else {
                        book.update();
                    }
                    bookDetail.setBookid(book.getId());
                    bookDetail.save();

                    //线程上传z3950
                    MyThread mt = new MyThread(barcode,book,bookPlus,orgname);    // 实例化对象
                    mt.start();

                }catch (Exception e){
                    logger.info("导入失败");
                    bookMap.put("失败原因","导入失败");
                    errorDataList.add(bookMap);
                }
            }
            String filename="";
            logger.info("图书未导入数量："+ errorDataList.size());
            if (errorDataList.size()>0){
                filename="图书未导入列表"+ DateUtils.getNowTimeNo()+".xls";
                File targetFile =new File(getRequest().getRealPath("upload")+ File.separator+filename);
                ExcelUtil.writeExcel(targetFile,errorDataList,"图书未导入列表");
            }
            success(filename);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据isbn查询出版社和地址 t_isbn
     */
    public void queryPublisherByIsbn(){
        try{
            String isbn = this.getPara("isbn");
            service.queryPublisherByIsbn(isbn);
        }catch(Exception e){
            e.printStackTrace();
            fail();
        }
    }

    /**
     *
     */
    public void bookMarkPrintToPDF(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        Map map = JwtUtils.validateJWTForMap(token);
        if (operatorid == 0) {
            fail(3, "token错误");
            return;
        }
        Integer orgid = (Integer)map.get("orgid");
        if(CommonUtils.isNullOrEmpty(orgid) || orgid == 0){
            fail(3, "token错误");
            return;
        }

        float bili = 2.83333333333f;

        Integer number = getParaToInt("number");
        Float hight = Float.parseFloat(getPara("hight"));
        Float totalmove = Float.parseFloat(getPara("totalmove"));
        Float width = Float.parseFloat(getPara("width"));
        Float totalwidth = Float.parseFloat(getPara("totalwidth"));
        Integer rownumber = getParaToInt("rownumber");
        Integer fontsize = getParaToInt("fontsize",14);
        Integer model = getParaToInt("model");
        String ids = getPara("ids","");
        String fonttype = getPara("fonttype");
        Integer boldflag = getParaToInt("boldflag",0);
        Integer ordertype = getParaToInt("ordertype",0);
        Integer orderby = getParaToInt("orderby",0);
        String sql = "select bookno,typecode,shucihao,barcode from t_book_detail d left join t_book b on d.bookid = b.id where orgid = " + orgid;
        if(CommonUtils.isNotNullOrNotEmpty(ids)){
            sql += " and d.id in ("+ids+")  ";
        }

//        if(CommonUtils.isNotNullOrNotEmpty(ids)){
//            sql += " and d.id in ("+ids+") order by barcode asc ";
//        } else {
//            sql +=" order by d.createtime desc,barcode desc ";
//        }
        if(ordertype == 0) {
            sql += "order by d.barcode ";
            if(orderby == 0) {
                sql +=" desc ";
            } else {
                sql +=" asc ";
            }
        } else if(ordertype == 1) {
            sql +=" order by d.createtime ";
            if(orderby == 0) {
                sql +=" desc ";
            } else {
                sql +=" asc ";
            }
        } else if(ordertype == 2) {
            sql +=" order by d.createtime ";
            if(orderby == 0) {
                sql +=" desc ";
            } else {
                sql +=" asc ";
            }
            sql +=" , d.barcode ";
            if(orderby == 0) {
                sql +=" desc ";
            } else {
                sql +=" asc ";
            }
        }
        List<Record> list = Db.find(sql);

        String path = PathKit.getWebRootPath()+ File.separator+"pointPDF";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        String refilename = orgid+"_"+format1.format(new Date())+"_BookMarkPoint.pdf";
        File checkfile = new File(path+File.separator+refilename);
        if (!checkfile.exists()) {
            try {
                checkfile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            String basefondpath = PathKit.getWebRootPath()+ File.separator+"lib"+ File.separator+"fonts"+File.separator;
            fonttype = basefondpath + fonttype + ".ttf";
            BaseFont bfChinese = BaseFont.createFont(fonttype, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            float[] tbfloat = new float[number];
            for(int index = 0; index < number; index ++){
                tbfloat[index] = width*bili;
            }
            Font textfont;
            if(boldflag == 0) {
                textfont = new Font(bfChinese, fontsize, Font.NORMAL);
            } else {
                textfont = new Font(bfChinese, fontsize, Font.BOLD);
            }

            String fileNameStr = "";
            int pagenumber = rownumber*number; //每页总数量
            int page = 1; // 页数
            int i = 0;
            while (i < list.size()) {
                if(page * pagenumber <= list.size()-i) { // 如果剩余的数据还有一页那么多
                    String fileName = CommonUtils.randownStr(5)+"_"+format1.format(new Date())+"_BookMarkPoint.pdf";

                    // 2.建立一个书写器(Writer)与document对象关联
                    file = new File(path+File.separator+fileName);
                    if (file.exists()) {
                        file.delete();
                    }
                    // 1.新建document对象
                    Document document = new Document(new RectangleReadOnly(totalwidth*bili, rownumber*hight*bili+totalmove*bili));// 建立一个Document对象
                    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
                    // 3.打开文档
                    document.open();
                    PdfPTable table = PdfUtil.createTable(tbfloat);

                    for(int j = 0; j < rownumber; j ++) { // 循环每一页的行数
                        for(int k = 0; k < number; k ++) {
                            String content = "";
                            if(model == 1){
                                content = list.get(j*number + k+i).getStr("typecode")+"\n"+list.get(j*number + k+i).getStr("shucihao")+"\n"+list.get(j*number + k+i).getStr("barcode");
                            } else if (model == 2){
                                content = list.get(j*number + k+i).getStr("typecode")+"\n"+list.get(j*number + k+i).getStr("shucihao");
                            } else if (model == 3){
                                content = list.get(j*number + k+i).getStr("bookno");
                            } else if (model == 4){
                                content = list.get(j*number + k+i).getStr("bookno")+"\n"+list.get(j*number + k+i).getStr("barcode");
                            }
                            table.addCell(PdfUtil.createCell(content, textfont,hight*bili));
                        }
                    }
                    PdfContentByte canvas = writer.getDirectContent();
                    table.setTotalWidth(number*width*bili);
                    table.writeSelectedRows(0, -1, (totalwidth-(number*width))/2*bili, rownumber*hight*bili, canvas);

                    document.setMargins(0,0,-111f,111f);
                    document.close();
                    writer.close();
                    i = i + page * pagenumber;
                    if("".equals(fileNameStr)){
                        fileNameStr = fileName;
                    } else {
                        fileNameStr = fileNameStr+","+fileName;
                    }
                } else {
                    String fileName = CommonUtils.randownStr(5)+"_"+format1.format(new Date())+"_BookMarkPoint.pdf";

                    // 2.建立一个书写器(Writer)与document对象关联
                    file = new File(path+File.separator+fileName);
                    if (file.exists()) {
                        file.delete();
                    }
                    // 1.新建document对象

                    Document document = new Document(new RectangleReadOnly(totalwidth*bili, rownumber*hight*bili+totalmove*bili));// 建立一个Document对象
                    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
                    // 3.打开文档
                    document.open();
                    PdfPTable table = PdfUtil.createTable(tbfloat);

                    flag:
                    {
                        for (int j = 0; j < rownumber; j++) { // 循环每一页的行数
                            for (int k = 0; k < number; k++) {
                                try {
                                    list.get(j * number + k+i);
                                } catch (Exception e) {
                                    for(int l = k; l < number; l ++) {
                                        table.addCell(PdfUtil.createCell("", textfont, hight * bili));
                                    }
                                    break flag;
                                }
                                String content = "";
                                if(model == 1){
                                    content = list.get(j*number + k+i).getStr("typecode")+"\n"+list.get(j*number + k+i).getStr("shucihao")+"\n"+list.get(j*number + k+i).getStr("barcode");
                                } else if (model == 2){
                                    content = list.get(j*number + k+i).getStr("typecode")+"\n"+list.get(j*number + k+i).getStr("shucihao");
                                } else if (model == 3){
                                    content = list.get(j*number + k+i).getStr("bookno");
                                } else if (model == 4){
                                    content = list.get(j*number + k+i).getStr("bookno")+"\n"+list.get(j*number + k+i).getStr("barcode");
                                }
                                table.addCell(PdfUtil.createCell(content, textfont, hight * bili));
                            }
                        }
                    }
                    PdfContentByte canvas = writer.getDirectContent();
                    table.setTotalWidth(number*width*bili);
                    table.writeSelectedRows(0, -1, (totalwidth-(number*width))/2*bili, rownumber*hight*bili, canvas);
                    document.close();
                    writer.close();
                    i = list.size();
                    if("".equals(fileNameStr)){
                        fileNameStr = fileName;
                    } else {
                        fileNameStr = fileNameStr+","+fileName;
                    }
                }
            }
            if(fileNameStr.indexOf(",")>-1){
                String[] files = fileNameStr.split(",");
                PdfUtil.mergePDF(files,path,refilename);
            } else {
                refilename = fileNameStr;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        success(refilename);
    }


    /**
     * 接口调用:暂时没用了
     */
//    public String doPost(String url, String params) {
//        CloseableHttpClient httpclient = HttpClients.createDefault();
//        HttpPost httpPost = new HttpPost(url);// 创建httpPost
//        httpPost.setHeader("Accept", "application/json");    //接收报文类型
//        httpPost.setHeader("Content-Type", "application/json");   //发送报文类型
//        if(params != null && !"".equals(params)){
//            StringEntity entity = new StringEntity(params, "UTF-8");
//            httpPost.setEntity(entity);
//        }
//        CloseableHttpResponse response = null;
//        try {
//            response = httpclient.execute(httpPost);
//            StatusLine status = response.getStatusLine();
//            int state = status.getStatusCode();
//            if (state == HttpStatus.SC_OK) {
//                HttpEntity responseEntity = response.getEntity();
//                String jsonString = EntityUtils.toString(responseEntity,"UTF-8");
//                return jsonString;
//            }
//            else{
//                System.out.println(state);
//            }
//        } catch (ClientProtocolException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        finally {
//            try {
//                if (response != null)response.close();
//                httpclient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return null;
//    }
}

class MyThread extends Thread{  // 继承Thread类，作为线程的实现类
    private String name ;
    private Book book ;
    private BookPlus bookPlus ;
    private String orgname ;

    public MyThread(String name,Book book,BookPlus bookPlus,String orgname){
        this.name = name ;
        this.book = book ;
        this.bookPlus = bookPlus ;
        this.orgname = orgname ;
    }


    public void run(){  // 覆写run()方法，作为线程 的操作主体
        try {
            String getUrl = PropKit.get("z3950url")+"/bookyubian/addBookYubian";//PropKit.get("z3950url")+
            Map<String,String> param  = CommonUtils.convertBeanToMap(book);
            if (CommonUtils.isNullOrEmpty(param)){
                param = new HashMap();
            }

            Map MbookPlus = CommonUtils.convertBeanToMap(bookPlus);
            if (CommonUtils.isNotNullOrNotEmpty(MbookPlus)){
                param.putAll(MbookPlus);
            }

            param.put("org",orgname);
            getUrl = CommonUtils.buildUrl(getUrl,param);
            String z3950str = CommonUtils.requestUrl(getUrl);
            Map result = (Map)JSON.parse(z3950str);
            //上传失败
            if (!"200".equals(result.get("code")+"")){
            }
        }catch (Exception e){

        }
    }
};
