package com.controller;

import com.alibaba.fastjson.JSON;
import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.upload.UploadFile;
import com.model.*;
import com.service.*;
import com.tools.JwtUtils;
import com.utils.*;
import com.validator.JieyueValidator;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 借阅信息
 * 2018-10-19
 * zjfloatingBookreprot
 */
@ControllerInterface(path="/jieyue")
public class JieyueController extends BaseController {
    JieyueService service = JieyueService.me;
    BookService bookService = BookService.me;

    BookPenaltyService bookPenaltyService = BookPenaltyService.me;
    BookDetailService bookDetailService = BookDetailService.me;
    SysConfigService sysConfigService = SysConfigService.me;

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

    public void list() {
        try {
            Jieyue bean = getBean(Jieyue.class, "bean");
            String realname = this.getPara("bean.realname");
            success(service.paginate(this.getParaToInt("pageNumber"), this.getParaToInt("pageSize"), bean, realname));
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }

    public void jieyuerecord() {
        try {
            Jieyue bean = getBean(Jieyue.class, "bean");
            Integer readerid = this.getParaToInt("readerid");
            String beginDate = getPara("beginDate");
            String endDate = getPara("endDate");
            String type = getPara("type");

            success(service.jieyuerecord(this.getParaToInt("pageNumber"), this.getParaToInt("pageSize"), bean, readerid, beginDate, endDate, type));
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }
    public void jieyuetotal() {
        try {
            Map result = new HashMap();
            int orgid= getParaToInt("orgid",0);
            int deptid = getParaToInt("deptid",0);
            int libraryid = getParaToInt("library", 0);

            String beginDate = getPara("kssj");
            String endDate = getPara("jssj");
            if(StringUtils.isBlank(beginDate) || StringUtils.isBlank(endDate)){
                success(result);
                return;
            }
            StringBuilder sb = new StringBuilder("select count(j.id) as num from t_jieyue j left join t_book_detail d on d.id=j.bookdetailid where orgid=? and j.createtime>=? and j.createtime<=?");
            List values = new ArrayList();
            values.add(orgid);
            values.add(beginDate);
            values.add(endDate);

           /* if(deptid >0){
                sb.append(" and deptid=?");
                values.add(deptid);
            }*/
            if(libraryid >0){
                sb.append(" and d.libraryid=?");
                values.add(libraryid);
            }
            Record jieshu = Db.findFirst(sb.toString(), listToArray(values));
            result.put("jieshu",jieshu.get("num"));
            Record huanshu = Db.findFirst(sb.toString()+" and returntime is null", listToArray(values));
            result.put("huanshu",jieshu.getInt("num")-huanshu.getInt("num"));
            List list = new ArrayList();
            list.add(result);

            success(list);
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }

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

    /**
     * 快速流通 /还书
     */
    public void returnBook() {
        String deviceNo = getPara("deviceNo");
        String barcode = this.getPara("barcode");
        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 || null == barcode) {
            fail(1, "请求参数不完整!");
            return;
        }
        int bookType = 0;
        //如果是期刊
        String kind = this.getPara("kind");
        if (CommonUtils.isNotNullOrNotEmpty(kind) && "1".equals(kind)) {
            bookType = 1;
        }
        //查询出该本书的状态
        Record bookInfoRecord = service.findByBarCode(barcode, bookType, orgid);
        Map remap = new HashMap();
        if (CommonUtils.isNullOrEmpty(bookInfoRecord)) {
            remap.put("type", "查询不到书籍信息");
            success(remap);
            return;
        }
        if (bookInfoRecord.getInt("isopen") == 0) {
            remap.put("type", "该书所在馆藏地禁止借阅");
            success(remap);
            return;
        }
        if (bookInfoRecord.getInt("bookstatus") == 3) {
            remap.put("type", "该书已注销");
            success(remap);
            return;
        }
        if (bookInfoRecord.getInt("bookstatus") == 4) {
            remap.put("type", "该书已丢失");
            success(remap);
            return;
        }
        int detailid = bookInfoRecord.get("detailid");
        remap.put("bookType", bookType);
        remap.put("bookInfo", bookInfoRecord);
        if (null == bookInfoRecord.get("status") || bookInfoRecord.getInt("status") == 1) {//如果该书的借阅信息为空或者借阅状态为1 则说明该书为在馆状态 则是借书
            remap.put("type", "借书");
        } else if (bookInfoRecord.getInt("status") == 0) { //还书
            int readerid = bookInfoRecord.getInt("readerid");


            Record jieyueRecord = Db.findFirst("select * from t_jieyue where readerid=? and bookdetailid = ? and status=0 ORDER BY createtime desc", readerid, detailid);
            Record authRecord = Db.findFirst("select a.* from t_reader r left join t_reader_auth a on r.readerauthid=a.id where r.id=?",readerid);
            if (null == jieyueRecord || null == authRecord) {
                fail(1, "请求参数不完整!");
                return;
            }
            int yujieRecordId = jieyueRecord.get("id");
            Timestamp duetime = jieyueRecord.get("duetime");
            long currentTime = System.currentTimeMillis();
            if (currentTime > duetime.getTime()) { // 超期
                Map fakuanMap = chaoqifakuan(currentTime, duetime.getTime(), authRecord.get("chaoqifakuan"), authRecord.get("chaoqifakuanxiane"));
                if(new BigDecimal(fakuanMap.get("amount").toString()).compareTo(BigDecimal.ZERO) == 0){
                    service.findOverdueInfo(readerid);
                    service.returnBook(yujieRecordId, readerid, detailid, operatorid, bookType);
                    remap.put("type", "还书成功");
                } else {
                    remap.put("day", fakuanMap.get("day"));
                    remap.put("amount", fakuanMap.get("amount"));
                    remap.put("type", "超期");
                }
            } else {
                service.returnBook(yujieRecordId, readerid, detailid, operatorid, bookType);
                service.findOverdueInfo(readerid);
                remap.put("type", "还书成功");
            }
            Record bookrecord = Db.findById("t_book",bookInfoRecord.getInt("bookid"));
            Calendar calendar = Calendar.getInstance();
            Calendar calendar1 = Calendar.getInstance();
            calendar.setTime(jieyueRecord.getDate("createtime"));

            long diffDays = (calendar1.getTimeInMillis() - calendar.getTimeInMillis())/ (1000 * 60 * 60 * 24);
            Record readerRecord = service.findReaderInfoByCardnum(readerid, orgid);
            remap.put("readerInfo", readerRecord);
            Map map = new HashMap();
            map.put("jieyuetype","2");
            map.put("orgid",orgid+"");
            map.put("booktype",bookType+"");
            map.put("isbn",bookrecord.getStr("isbn"));
            map.put("title",bookInfoRecord.getStr("title"));
            map.put("publisher",bookInfoRecord.getStr("publisher"));
            map.put("author",bookInfoRecord.getStr("author"));
            map.put("price",bookInfoRecord.getStr("price"));
            map.put("typecode",bookrecord.getStr("typecode"));
            map.put("sex",readerRecord.getStr("sex"));
            map.put("grade",authRecord.getStr("name"));
//            map.put("readertype","authorauthor");
            map.put("jieyueid",yujieRecordId+"");
            map.put("jieyueday",diffDays+"");
            Thread t = new Thread() {
                public void run() {
                    HttpKit.get(PropKit.get("borrowLogServiceUrl"), map);
                }
            };
            t.start();
        } else if (bookInfoRecord.getInt("status") == 2) { //丢失
            remap.put("type", "书籍已被预约");
        } else if (bookInfoRecord.getInt("status") == 3) { //丢失
            remap.put("type", "书籍已注销");
        } else if (bookInfoRecord.getInt("status") == 4) { //丢失
            remap.put("type", "书籍丢失");
        }

        success(remap);
    }


    /**
     * 借书 如果有条码 则直接借书如果没有条码则返回用户信息和借书信息列表
     */
    public void borrowBooks() {
        String deviceNo = getPara("deviceNo");
        String barcode = this.getPara("barcode");
        String cardnumber = this.getPara("cardnumber");
        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;
        }

        if(121283 ==orgid && cardnumber.trim().length() == 6){
            fail(0,"老读者证号不允许借书！");
            return;
        }
        //查询读者信息
        Record readerRecord = Db.findFirst("select * from t_reader where (cardnumber = ? or readcardcode=?) and orgid=?",cardnumber,cardnumber,orgid);
        if (CommonUtils.isNullOrEmpty(readerRecord) || CommonUtils.isNullOrEmpty(readerRecord.get("id"))) {
            success("获取不到读者信息");

            return;
        }
        if (readerRecord.getInt("status") == 2) {
            success("读者证已挂失");

            return;
        } else if (readerRecord.getInt("status") == 3) {
            success("读者证已停借");

            return;
        } else if (readerRecord.getInt("status") == 4) {
            success("读者证已注销");

            return;
        } else if (readerRecord.getInt("status") == 5) {
            success("读者证已超借");

            return;
        } else if (readerRecord.getInt("status") != 1) {
            success("读者证状态异常");

            return;
        }
        Record readerAuthRecord = Db.findById("t_reader_auth",readerRecord.getInt("readerauthid"));
        if(CommonUtils.isNullOrEmpty(readerAuthRecord) || CommonUtils.isNullOrEmpty(readerAuthRecord.getStr("id"))){
            success("该读者未设置借阅权限，请先设置！");
            //WebSocketController.faceDeviceNotice(orgid, deviceNo,"该读者未设置借阅权限，请先设置！");
            return;
        }
        if (null != barcode) { //如果条码不为空 这说明是快速流通借书
            int bookType = 0;
            //如果是期刊
            String kind = this.getPara("kind");
            if (CommonUtils.isNotNullOrNotEmpty(kind) && "1".equals(kind)) {
                bookType = 1;
            }
            int readerid = readerRecord.get("id");

            // 查询该书的detailid 和状态 如果是预约状态 则判断
            Record detailRecord = null;
            if (bookType == 0) {
                detailRecord = Db.findFirst("select d.* from t_book_detail d left join t_book b on d.bookid=b.id where d.barcode =? and b.orgid=? and d.bookstatus=1",barcode,orgid);
            } else {
                detailRecord = Db.findFirst("select d.* from t_periodical_detail d left join t_periodical_zhengding p on d.periodicalid=p.id where d.barcode =? and p.orgid=? and d.bookstatus=1",barcode,orgid);
            }
            if (null == detailRecord) {
                success("获取不到书籍信息");
                return;
            }

            int status = detailRecord.get("status");
            if (status == 1) { //该书已借出
                success("该书已借出");

                return;
            } else if(status == 3){
                success("该书已注销");
                return;
            } else if(status == 4){
                success("该书已丢失");
                return;
            }
            int bookid = 0;
            String querySqlStr = "select d.id,d.barcode from t_book_detail d where d.bookid=? and d.status = 0 and d.bookstatus = 1";
            if (bookType == 0) {
                bookid = detailRecord.get("bookid");
            } else {
                bookid = detailRecord.get("periodicalid");
                querySqlStr = "select d.id,d.barcode from t_periodical_detail d where d.periodicalid=? and d.status =0 and d.bookstatus = 1";
            }
            List countList = Db.find(querySqlStr, bookid);
            if (CommonUtils.isNullOrEmpty(countList) || countList.size() == 0) {
                success("借书失败，数据异常。");
                return;
            }


            int detailid = detailRecord.get("id");
            Record yuyueRecord;
            if (bookType == 0) {
                yuyueRecord = Db.findFirst(
                        "select 'yujie' yuyuetype,id,readerid,bookdetailid,bookid,createtime,endtime,status,operatorid from t_yujie y where y.deletestatus=0 and y.bookdetailid=? and y.status = 1 \n" +
                                " order by createtime asc", detailid);
            } else {
                yuyueRecord = Db.findFirst(
                        "select 'yuyue' yuyuetype,id,readerid,bookdetailid,bookid,createtime,endtime,status,operatorid from t_yuyue where deletestatus=0 and bookdetailid=? and status = 1 \n" +
                                " order by createtime asc", detailid);
            }

            Record authRecord = Db.findFirst("select a.* from t_reader r left join t_reader_auth a on r.readerauthid=a.id where (r.cardnumber=? or r.readcardcode=?) and r.orgid=?",cardnumber,cardnumber,orgid);
            if(CommonUtils.isNullOrEmpty(authRecord)){
                success("该读者未设置借阅权限，请先设置！");
                return;
            }
            int borrowType = 0; //0 正常借书 1 预约借书 非预约借书(有多余的副本的情况下)borrowType为detailid
            if (status == 0) {
                jieshu(deviceNo, authRecord, readerRecord, readerid, detailRecord, bookType, operatorid, yuyueRecord, borrowType);
                return;
            } else if (status == 1) { //该书已借出
                success("该书已借出");
                return;
            } else if (status == 2) { // 已预约
                Record detailExistRecord = service.findDetailListByBookIdAndExist(bookid);
                int yuyueReaderid = yuyueRecord.getInt("readerid");
                if (readerid == yuyueReaderid) { // 如果当前用户和预约用户是同一人 则 bowrowType = 1 为预约借书
                    borrowType = 1;
                } else {
                    if (null == detailExistRecord || null == detailExistRecord.get("id") || "".equals(detailExistRecord.get("id"))) { //如果没有额外在馆的副本 则不允许借书
                        success("该书已被预约或预借");
                        return;
                    } else {
                        borrowType = detailExistRecord.get("id");
                    }
                }
                jieshu(deviceNo, authRecord, readerRecord, readerid, detailRecord, bookType, operatorid, yuyueRecord, borrowType);
            } else if (status == 3) { // 该书已注销
                success("该书已注销");
                return;
            } else if (status == 4) { // 该书已丢失
                success("该书已丢失");
                return;
            }
        } else { //没有条码则说明是借书标签中请求 返回用户信息以及借书列表
            Map map = service.findReaderInfoAndJieyueListByCardnumber(cardnumber, orgid, true);
//            if(CommonUtils.isNullOrEmpty(this.getPara("timestamp"))) {
            map.put("jieshu", "ok");
//            }
            success(map);
        }
    }

    public void findJieyueListByCardnumber() {
        String cardnumber = this.getPara("cardnumber");
        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.findJieyueListByCardnumber(this.getParaToInt("pageNumber"), this.getParaToInt("pageSize"), cardnumber, orgid));
    }




    private void jieshu(String deviceNo,Record authRecord, Record readerRecord, int readerid, Record detailRecord, int bookType, int operatorid, Record yuyueRecord, int borrowType) {
        if (jieshucheck(authRecord, readerRecord, readerid, detailRecord.getInt("id"), bookType)) {
            int orgid = authRecord.getInt("orgid");
            String barcode = detailRecord.getStr("barcode");
            Jieyue jieyue = zuzhuangJieyue(authRecord, readerRecord, detailRecord, bookType, operatorid);
            service.borrowBooks(jieyue, bookType, borrowType, yuyueRecord, readerid, detailRecord.getInt("id"));
            Record readerRecordInfo = service.findReaderInfoByCardnum(readerid, orgid);
            Record bookInfoRecord = service.findByBarCode(barcode, bookType, orgid);
            if (bookInfoRecord.getInt("isopen") == 0) {

                success("该书所在馆藏地禁止借阅");
                return;
            }
            Map map = new HashMap();
            map.put("readerInfo", readerRecordInfo);
            map.put("bookInfo", bookInfoRecord);
            map.put("message", "借书成功");
            Record bookrecord = Db.findById("t_book",bookInfoRecord.getInt("bookid"));
            Map jieyuemap = new HashMap();
            jieyuemap.put("jieyuetype","1");
            jieyuemap.put("orgid",orgid+"");
            jieyuemap.put("booktype",bookType+"");
            jieyuemap.put("isbn",bookrecord.getStr("isbn"));
            jieyuemap.put("title",bookInfoRecord.getStr("title"));
            jieyuemap.put("publisher",bookInfoRecord.getStr("publisher"));
            jieyuemap.put("author",bookInfoRecord.getStr("author"));
            jieyuemap.put("price",bookInfoRecord.getStr("price"));
            jieyuemap.put("typecode",bookrecord.getStr("typecode"));
            jieyuemap.put("sex",readerRecord.getStr("sex"));
            jieyuemap.put("grade",authRecord.getStr("name"));
//            map.put("readertype","authorauthor");
            jieyuemap.put("jieyueid",jieyue.getId()+"");
            Thread t = new Thread() {
                public void run() {
                    try {
                        HttpKit.get(PropKit.get("borrowLogServiceUrl"), jieyuemap);
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            };
            t.start();
            success(map);
        } else {
//            success("该读者未设置借阅权限，请先设置！");
            return;
        }
    }

    private Jieyue zuzhuangJieyue(Record authRecord, Record readerRecord, Record detailRecord, int bookType, int operatorid) {
        int jieyuetianshu = authRecord.getInt("jieyuetianshu");
        Calendar calendar = Calendar.getInstance();
        Jieyue jieyue = new Jieyue();
        jieyue.setReaderid(readerRecord.get("id"));
        jieyue.setOrgid(authRecord.getInt("orgid"));
        jieyue.setBookdetailid(detailRecord.get("id"));
        jieyue.setFlag(bookType);
        jieyue.setStatus(0);
        jieyue.setContinuenum(0);
        jieyue.setCreatetime(calendar.getTime());
        calendar.add(Calendar.DATE, jieyuetianshu);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String datestr = sdf.format(calendar.getTime());
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            jieyue.setDuetime(sdf2.parse(datestr + " 23:59:59"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        jieyue.setOperatorid(operatorid);
        return jieyue;
    }

    private boolean jieshucheck(Record authRecord, Record readerRecord, int readerid, int detailid, int booktype) {
        Timestamp losedate = readerRecord.get("losedate");
        long currentTime = System.currentTimeMillis();
        if (currentTime > losedate.getTime()) { //如果当前时间大于有效期 则说明已过期
            success("读者证已过期");
            return false;
        }
        int readerStatus = readerRecord.get("status");
        if (readerStatus != 1) {
            success("读者证状态异常");
            return false;
        }
        if(CommonUtils.isNullOrEmpty(authRecord) || CommonUtils.isNullOrEmpty(authRecord.get("id"))){
            success("该读者未设置借阅权限，请先设置！");
            return false;
        }
        int shifounengchaoqijieshu = authRecord.get("shifounengchaoqijieshu");
        int shifounengqiankuanjieshu = authRecord.get("shifounengqiankuanjieshu");
        int jieyueshuliang = authRecord.get("jieyueshuliang");
        String jinzhijieyueguangcangdi = authRecord.getStr("jinzhijieyueguangcangdi");
        if (1 == shifounengchaoqijieshu) {
            if (null != readerRecord.get("overdue")) {
                int overdue = readerRecord.get("overdue");
                if (1 == overdue) {
                    //yuyueService.yuyueInvalid(yuyueRecord.getInt("id"),detailRecord.getInt("id"));
                    success("超期不允许借书");
                    return false;
                }
            }
        }
        if (1 == shifounengqiankuanjieshu) {
            Record qiankuanRecord = Db.findFirst("select count(1) qiankuannum from t_book_penalty where penaltystatus = 0 and penaltyamount > 0 and readerid=?", readerid);
            int qiankuannum = qiankuanRecord.getInt("qiankuannum");
            if (qiankuannum > 0) {
                success("欠款不允许借书");
                return false;
            }
        }
        int jieyuenum = service.countJieyueBooks(readerid);
        if (jieyuenum >= jieyueshuliang) {
            //是否需要将借阅记录改为失效？
            //yuyueService.yuyueInvalid(yuyueRecord.getInt("id"),detailRecord.getInt("id"));
            success("超过借书最大数量");
            return false;
        }
        String tablename = "t_book_detail";
        if (1 == booktype) {
            tablename = "t_periodical_detail";
        }
        if (0 == detailid) {
            return true;
        }
        Record record = Db.findFirst("select libraryid,ifnull(isopen,1) isopen from " + tablename + " d left join t_library l on d.libraryid = l.id where d.id=?" ,detailid);
        if (record.getInt("isopen") == 0) {
            success("该书所在馆藏地禁止借阅");
            return false;
        }
        if (CommonUtils.isNotNullOrNotEmpty(jinzhijieyueguangcangdi)) {
            if (jinzhijieyueguangcangdi.indexOf(record.getStr("libraryid")) > -1) {
                success("该书所在馆藏地禁止借阅");
                return false;
            }
        }
        return true;
    }

    public void sunshu() {
        String cardnumber = this.getPara("cardnumber");
        int orgid = this.getParaToInt("orgid", 0);
        if (orgid == 0) {
            fail(1, "请求参数不完整!");
            return;
        }
        Map remap = service.findReaderInfoAndJieyueListByCardnumber(cardnumber, orgid, true);
        if (CommonUtils.isNullOrEmpty(remap) || CommonUtils.isNullOrEmpty(remap.get("userInfo"))) {
            success("查询不到读者信息");
            return;
        }
        Record authRecord = Db.findFirst("select a.* from t_reader r left join t_reader_auth a on r.readerauthid=a.id where r.cardnumber=? and r.orgid=?", cardnumber, orgid);
        remap.put("sunshumeiyefakuan", authRecord.get("sunshumeiyefakuan"));
        remap.put("sunshufakuanxiane", authRecord.get("sunshufakuanxiane"));
        success(remap);
    }

    /**
     * 其他操作 如续借补还
     */
    @Clear
    public void bookOther() {
        String type = this.getPara("type"); //类型 xujie buhuan
        String barcode = this.getPara("barcode");
        String cardnumber = this.getPara("cardnumber");
        if (null == type) {
            fail(1, "请求参数不完整!");
            return;
        }
        if ("xujie".equals(type) && null == barcode) {
            fail(1, "请求参数不完整!");
            return;
        }
        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;
        }
        Map remap = service.findReaderInfoAndJieyueListByCardnumber(cardnumber, orgid, false);
        int bookType = 0;
        //如果是期刊
        String kind = this.getPara("kind");
        if (CommonUtils.isNotNullOrNotEmpty(kind) && "1".equals(kind)) {
            bookType = 1;
        }
        //查询出该本书的状态
        Record bookInfoRecord = null;
        if ("buhuan".equals(type)) {
            bookInfoRecord = service.findByBarCode(barcode, bookType, orgid, 2);
            if (CommonUtils.isNullOrEmpty(bookInfoRecord)) {
                remap.put("buhuanerror", "查询不到丢失记录");
                success(remap);
                return;
            }
        } else {
            bookInfoRecord = service.findByBarCode(barcode, bookType, orgid, 0);
            if (CommonUtils.isNullOrEmpty(bookInfoRecord)) {
                remap.put("xujie", "查询不到借阅记录");
                success(remap);
                return;
            }
            if (bookInfoRecord.getInt("isopen") == 0) {
                remap.put("xujie", "该书所在馆藏地禁止借阅");
                success(remap);
                return;
            }
        }
        int jieyueid = bookInfoRecord.get("id");
        int detailid = bookInfoRecord.get("bookdetailid");
        remap.put("bookType", bookType);
        remap.put("bookInfo", bookInfoRecord);
        int readerid = bookInfoRecord.getInt("readerid");
        Record readerRecord = service.findReaderInfoByCardnum(readerid, orgid);
        if (CommonUtils.isNullOrEmpty(readerRecord) || CommonUtils.isNullOrEmpty(readerRecord.get("id"))) {
            remap.put("xujie", "获取不到读者信息");
            success(remap);
            return;
        }
        if (readerRecord.getInt("status") == 2) {
            remap.put("xujie", "读者证已挂失");
            success(remap);
            return;
        } else if (readerRecord.getInt("status") == 3) {
            remap.put("xujie", "读者证已停借");
            success(remap);
            return;
        } else if (readerRecord.getInt("status") == 4) {
            remap.put("xujie", "读者证已注销");
            success(remap);
            return;
        } else if (readerRecord.getInt("status") == 5) {
            remap.put("xujie", "读者证已超借");
            success(remap);
            return;
        } else if (readerRecord.getInt("status") != 1) {
            remap.put("xujie", "读者证状态异常");
            success(remap);
            return;
        }
        remap.put("readerInfo", readerRecord);

        Record authRecord = Db.findFirst("select a.* from t_reader r left join t_reader_auth a on r.readerauthid=a.id where r.id=?",readerid);
        if ("xujie".equals(type)) {
            long currentTime = System.currentTimeMillis();
            int xujietianshu = authRecord.get("xujietianshu"); //用户当前权限下续借一次的天数
            Timestamp duetime = bookInfoRecord.get("duetime");
            int shifounengchaoqijieshu = authRecord.get("shifounengchaoqijieshu");
            if (1 == shifounengchaoqijieshu) {
                if (currentTime > duetime.getTime()) { //超期
                    remap.put("xujie", "超期不允许续借");
                    success(remap);
                    return;
                }
            }

            int shifounengqiankuanjieshu = authRecord.get("shifounengqiankuanjieshu");
            if (1 == shifounengqiankuanjieshu) {
                List list = bookPenaltyService.weijiaofakuan(readerid);
                if (CommonUtils.isNotNullOrNotEmpty(list) && list.size() > 0) {
                    remap.put("xujie", "欠款不允许续借");
                    success(remap);
                    return;
                }
            }
            long residualtime = duetime.getTime() - currentTime;
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, xujietianshu);
            long youxiaoshijian = residualtime + calendar.getTimeInMillis();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String str = sdf.format(youxiaoshijian);
            try {
                Date temp = sdf2.parse(str + " 23:59:59");
                int xujiecishu = authRecord.get("xujiecishu");
                int jieyueNumber = service.findJieyueNumber(readerid, detailid);
                if (xujiecishu > jieyueNumber) {
                    Jieyue jieyue = new Jieyue();
                    jieyue.setReaderid(readerid);
                    jieyue.setOrgid(orgid);
                    jieyue.setBookdetailid(detailid);
                    jieyue.setFlag(bookType);
                    jieyue.setStatus(0);
                    jieyue.setContinuenum(0);
                    jieyue.setCreatetime(new Date());
                    jieyue.setDuetime(temp);
                    jieyue.setOperatorid(operatorid);
                    service.xujie(operatorid, jieyueid, jieyue);
                    remap.put("xujie", "续借成功");
                } else {
                    remap.put("xujie", "超过续借次数");
                }
                success(remap);

            } catch (ParseException e) {
                e.printStackTrace();
            }

        } else if ("buhuan".equals(type)) {
            if (null == barcode) {
                fail(1, "请求参数不完整!");
                return;
            }
            Record penaltyRecord = Db.findFirst("select * from t_book_penalty where jieyueid = ? and type = 0 order by createtime desc", jieyueid);
            if (null == penaltyRecord) {
                remap.put("buhuanerror", "无法获取到有效信息");
                success(remap);
                return;
            }
            long diushubuhuaiqixian = authRecord.getLong("diushubuhuaiqixian");
            Timestamp penaltyCreateTime = penaltyRecord.get("createtime");
            long penaltyEndTime = penaltyCreateTime.getTime() + diushubuhuaiqixian * 1000 * 60 * 60 * 24;
            long currentTime = System.currentTimeMillis();
            if (currentTime > penaltyEndTime && 0 != diushubuhuaiqixian) { //超过最后补还日期
                remap.put("buhuanerror", "补还超期");
                success(remap);
                return;
            }
            remap.put("penaltyRecord", penaltyRecord);
            Timestamp duetime = bookInfoRecord.get("duetime");
            remap.put("buhuan", 0);
            if (currentTime > duetime.getTime()) { // 超期
                Map fakuanMap = chaoqifakuan(currentTime, duetime.getTime(), authRecord.get("chaoqifakuan"), authRecord.get("chaoqifakuanxiane"));
                if (new BigDecimal(fakuanMap.get("amount").toString()).compareTo(BigDecimal.ZERO) == 1) {
                    remap.put("day", fakuanMap.get("day"));
                    remap.put("amount", fakuanMap.get("amount"));
                    remap.put("buhuan", 1);
                }
            }
            success(remap);
        } else {
            success("获取不到信息");
        }

    }

    /**
     * 丢书
     */
    public void diushu() {
        String cardnumber = this.getPara("cardnumber");
        if (null == cardnumber) {
            fail(1, "请求参数不完整!");
            return;
        }
        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;
        }
        Map remap = service.findReaderInfoAndJieyueListByCardnumber(cardnumber, orgid, true);
        if (CommonUtils.isNullOrEmpty(remap) || CommonUtils.isNullOrEmpty(remap.get("userInfo"))) {
            success("查询不到读者信息");
            return;
        }
        int readerid = ((Record) (remap.get("userInfo"))).getInt("id");
        Record authRecord = Db.findFirst("select a.* from t_reader r left join t_reader_auth a on r.readerauthid=a.id where r.id=?",readerid);
        remap.put("diushufakuanbeishu", authRecord.get("diushufakuanbeishu"));
        success(remap);
    }

    /**
     * 根据读者证号查询读者信息以及赔书列表
     */
    public void findpeishuPageInfo() {
        String cardnumber = this.getPara("cardnumber");
        if (null == cardnumber) {
            fail(1, "请求参数不完整!");
            return;
        }
        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;
        }

        Map remap = new HashMap();
        Record readerRecord = service.findReaderInfoByCardnum(cardnumber, orgid);
        if (CommonUtils.isNullOrEmpty(readerRecord)) {
            success("查询不到读者信息");
            return;
        }
        remap = service.findReaderInfoAndJieyueListByCardnumber(cardnumber, orgid, false);
        remap.put("readerInfo", readerRecord);
//        int readerid = readerRecord.getInt("id");
//        List<Record> list = Db.find("select p.id,d.id detailid,j.id jieyueid,d.barcode,b.title,b.bookno,j.createtime,j.duetime,j.isoverdue from t_book_penalty p left join t_jieyue j on p.jieyueid=j.id inner join t_book_detail d on p.bookdetailid = d.id left join t_book b on d.bookid=b.id where p.readerid = ? and j.orgid=? and p.type = 0 and p.penaltystatus in (0,1)  and p.flag=0 " +
//                " union " +
//                " select p.id,d.id detailid,j.id jieyueid,d.barcode,pb.kanming title,pb.bookno,j.createtime,j.duetime,j.isoverdue from t_book_penalty p left join t_jieyue j on p.jieyueid=j.id inner join t_periodical_detail d on p.bookdetailid = d.id left join t_periodical_zhengding pb on d.periodicalid=pb.id where p.readerid = ? and j.orgid=? and p.type = 0 and p.penaltystatus in (0,1)  and p.flag=1",readerid,orgid,readerid,orgid);
//        remap.put("lostList",list);
        success(remap);
    }

    public void peishuinfo() {
        String readerid = this.getPara("readerid");
        String detailid = this.getPara("detailid");
        String jieyueid = this.getPara("jieyueid");
        if (null == readerid || null == detailid || null == jieyueid) {
            fail(1, "请求参数不完整!");
            return;
        }
        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;
        }
//        Record authRecord = Db.findFirst("select a.* from t_reader r left join t_reader_auth a on r.readerauthid=a.id where r.id='" + readerid + "'");
        Map remap = new HashMap();
//        Record jieyueRecord = Db.findFirst("select * from t_jieyue where readerid = ? and bookdetailid = ? and id = ?",readerid,detailid,jieyueid);
//        Timestamp duetime = jieyueRecord.get("duetime");
//        long currentTime = System.currentTimeMillis();

//        long diushubuhuaiqixian = authRecord.getLong("diushubuhuaiqixian");
//        Timestamp penaltyCreateTime = jieyueRecord.get("createtime");
//        long penaltyEndTime = penaltyCreateTime.getTime() + diushubuhuaiqixian *1000*60*60*24;
//        if(currentTime>penaltyEndTime){ //超过最后补还日期
//            remap.put("peishu","超过赔书限定日期");
//            success(remap);
//            return;
//        }

//        if(currentTime > duetime.getTime()) { // 超期
//            Map fakuanMap = chaoqifakuan(currentTime,duetime.getTime(),authRecord.get("chaoqifakuan"),authRecord.get("chaoqifakuanxiane"));
//            remap.put("day",fakuanMap.get("day"));
//            remap.put("amount",fakuanMap.get("amount"));
//            remap.put("chaoqi",1);
//        }
        Record penaltyRecord = Db.findFirst("select * from t_book_penalty where jieyueid = ? and type = 0 order by createtime desc", jieyueid);
        if (null == penaltyRecord) {
            remap.put("peishu", "获取不到丢书记录");
            success(remap);
            return;
        }
        remap.put("penaltyRecord", penaltyRecord);
        success(remap);
    }

    /**
     * 保存条码信息并且更新
     */
    public void peishuReplaceBarcode() {
        String barcode = this.getPara("barcode");
        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;
        }
//        if (CommonUtils.isNullOrEmpty(barcode)) {
//            fail(1, "请求参数不完整!");
//            return;
//        }
        if (CommonUtils.isNotNullOrNotEmpty(barcode)) {
            OrgSetting orgSetting = sysConfigService.findOrgSetting(orgid);
            barcode = CommonUtils.formatBarcode(barcode, orgSetting);
//            int count;
//            if (bookPenalty.getFlag() == 0) {
//                count = bookService.findByBarcode(orgid, barcode);
//            } else {
//                Record record = periodicalDetailService.findPeriodicalByBarcode(orgid, barcode);
//                if (CommonUtils.isNotNullOrNotEmpty(record)) {
//                    count = 1;
//                } else {
//                    count = 0;
//                }
//            }
//            if (count > 0) {
//                success("条码重复");
//                return;
//            }
        }
        int jieyueid = this.getParaToInt("jieyueid");
        Jieyue jieyue = service.findById(jieyueid);

        int detailid = 0;
        OrgSetting orgSetting = sysConfigService.findOrgSetting(orgid);
        if (jieyue.getFlag() == 0) {
            barcode = CommonUtils.formatBarcode(barcode, orgSetting);
            Record record = bookDetailService.bookBarcodeExists(orgid, barcode);
            if (CommonUtils.isNotNullOrNotEmpty(record)) {
                detailid = record.getInt("id");
            }
        }
        if (detailid != jieyue.getBookdetailid() && detailid != 0) {
            success("条码重复");
            return;
        }

        int day = getParaToInt("day");
        String amount = getPara("amount");
        int penaltystatus = getParaToInt("penaltystatus");
        if (day > 0 && !"0".equals(amount)) {
            BookPenalty bookPenaltynew = new BookPenalty();
            bookPenaltynew.setOrgid(orgid);
            bookPenaltynew.setReaderid(jieyue.getReaderid());
            bookPenaltynew.setBookdetailid(jieyue.getBookdetailid());
            bookPenaltynew.setJieyueid(jieyueid);
            bookPenaltynew.setPenaltystatus(penaltystatus);
            bookPenaltynew.setPenaltyamount(new BigDecimal(amount));
            bookPenaltynew.setFlag(jieyue.getFlag());
            bookPenaltynew.setType(2);
            bookPenaltynew.setStatus(null);
            bookPenaltynew.setRemarks("超期" + day + "天罚款");
            bookPenaltynew.setCreatetime(new Date());
            bookPenaltynew.setOperatorid(operatorid);
            service.peishu(jieyue, barcode, operatorid, bookPenaltynew);
        } else {
            service.peishu(jieyue, barcode, operatorid, null);
        }
        success();
    }

    /**
     * 通过条码 类型和机构id查询书籍信息
     */
    public void findByBarCode() {
        int orgid = this.getParaToInt("orgid", 0);
        if (orgid == 0) {
            fail(1, "请求参数不完整!");
            return;
        }
        String barcode = getPara("barcode");
        int bookType = getParaToInt("bookType");
        success(service.findByBarCode(barcode, bookType, orgid));
    }



    private Map chaoqifakuan(long currentTime, long endTime, BigDecimal chaoqifakuan, BigDecimal maxfakuan) {
        double day = Math.ceil((currentTime - endTime) / 1000 / 60 / 60 / 24);
        day++;
        Map remap = new HashMap();
        remap.put("day", day);
        BigDecimal allamount = chaoqifakuan.multiply(new BigDecimal(day));
        int a = allamount.compareTo(maxfakuan);
        if (a == 1 && maxfakuan.compareTo(BigDecimal.ZERO) != 0) {
            remap.put("amount", maxfakuan);
        } else {
            remap.put("amount", allamount);
        }
        return remap;
    }

    //借阅
    @Before(JieyueValidator.class)
    public void add() {
        Jieyue bean = getBean(Jieyue.class, "bean");
        String token = this.getPara("token");
        try {
            int operatorid = JwtUtils.validateJWTForUserId(token);
            if (operatorid == 0) {
                fail(3, "token错误");
                return;
            }
            service.add(bean, operatorid);
            success();
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }

    //还书
    public void still() {
        String token = this.getPara("token");
        int bookdetailid = this.getParaToInt("bean.bookdetailid");
        try {
            int id = this.getParaToInt("bean.id");
            int operatorid = JwtUtils.validateJWTForUserId(token);
            if (operatorid == 0) {
                fail(3, "token错误");
                return;
            }
            service.still(id, operatorid, bookdetailid);
            success();
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }

    /**
     * 图书流通记录
     */
    public void jieyueRecord() {
        int orgid = this.getParaToInt("orgid");
        Integer record = this.getParaToInt("record");
        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        String txm = this.getPara("txm");
        //Integer flag = this.getParaToInt("flag");
        Integer dept = this.getParaToInt("dept");
        Integer library = this.getParaToInt("library",0);
        Integer overdue = this.getParaToInt("overdue");
        String cardnumber = this.getPara("cardnumber");
        String title = this.getPara("title");
        String order = this.getPara("order");
        String bm = this.getPara("bm");
        success(service.jieyueRecord(this.getParaToInt("pageNumber"), this.getParaToInt("pageSize"), orgid, record, kssj, jssj, dept, overdue, cardnumber, title,order,txm,bm,library));
    }

    /**
     * 图书流通记录 -- 导出
     */
    public void exportJieyueRecord() {
        int orgid = this.getParaToInt("orgid");
        String orgname = new Org().dao().findById(orgid).getOrgname();
        Integer record = this.getParaToInt("record");
        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");

        String txm = this.getPara("txm");
        //Integer flag = this.getParaToInt("flag");
        Integer dept = this.getParaToInt("dept");
        Integer library = this.getParaToInt("library",0);
        Integer overdue = this.getParaToInt("overdue");
        String cardnumber = this.getPara("cardnumber");
        String title = this.getPara("title");
        String order = this.getPara("order");
        String bm = this.getPara("bm");
        List<Record> list = service.exportJieyueRecord(orgid, record, kssj, jssj, dept, overdue, cardnumber, title,order,txm,bm,library);

        List list1 = new ArrayList();
        for (Record record1 : list) {
            if (null != record1.get("isoverdue") && record1.getInt("isoverdue") == 1) {
                record1.set("isoverdueCn", "是");
            } else {
                record1.set("isoverdueCn", "否");
            }
            if (CommonUtils.isNotNullOrNotEmpty(record1.getStr("createtime"))) {
                record1.set("createtime", record1.getStr("createtime").split(" ")[0]);
            }
            if (CommonUtils.isNotNullOrNotEmpty(record1.getStr("duetime"))) {
                record1.set("duetime", record1.getStr("duetime").split(" ")[0]);
            }
            if (CommonUtils.isNotNullOrNotEmpty(record1.getStr("returntime"))) {
                record1.set("returntime", record1.getStr("returntime").split(" ")[0]);
            }
            list1.add(record1);
        }

        /*LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("barcode", "图书条码");
        headMap.put("isbn", "ISBN");
        headMap.put("title", "题名");
        headMap.put("bookno", "索书号");
        headMap.put("cardnumber", "读者证号");
        headMap.put("realname", "姓名");
        headMap.put("deptname", "部门");
        headMap.put("createtime", "借阅日期");
        headMap.put("duetime", "应还日期");
        headMap.put("returntime", "归还日期");
        //headMap.put("isoverdueCn", "是否超期");
*/
        String fields[] = {"barcode","isbn","title","bookno","price","cardnumber","realname","deptname","createtime","duetime","returntime"};
        ExcelExportUtil_template.exportExcel("图书流通记录.xls",this.getResponse(),orgname+"图书流通记录",list,fields,2);
        renderNull();
    }

    /**
     * 期刊流通记录
     */
    public void jieyueRecordQ() {
        int orgid = this.getParaToInt("orgid");
        Integer record = this.getParaToInt("record");
        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        String txm = this.getPara("txm");
        //Integer flag = this.getParaToInt("flag");
        Integer dept = this.getParaToInt("dept");
        Integer overdue = this.getParaToInt("overdue");
        String cardnumber = this.getPara("cardnumber");
        String title = this.getPara("title");

        success(service.jieyueRecordQ(this.getParaToInt("pageNumber"), this.getParaToInt("pageSize"), orgid, record, kssj, jssj, dept, overdue, cardnumber, title,txm));
    }

    /**
     * 期刊流通记录 --export
     */
    public void exportJieyueRecordQ() {
        int orgid = this.getParaToInt("orgid");
        Integer record = this.getParaToInt("record");
        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");

        String txm = this.getPara("txm");
        //Integer flag = this.getParaToInt("flag");
        Integer dept = this.getParaToInt("dept");
        Integer overdue = this.getParaToInt("overdue");
        String cardnumber = this.getPara("cardnumber");
        String title = this.getPara("title");

        List<Record> list = service.exportJieyueRecordQ(orgid, record, kssj, jssj, dept, overdue, cardnumber, title ,txm);

        List list1 = new ArrayList();
        for (Record record1 : list) {
            if (record1.get("isoverdue") != null && record1.getInt("isoverdue") == 1) {
                record1.set("isoverdueCn", "是");
            } else {
                record1.set("isoverdueCn", "否");
            }
            list1.add(record1);
        }

        LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("barcode", "期刊条码");
        headMap.put("issn", "ISSN");
        headMap.put("kanming", "刊名");
        headMap.put("bookno", "索刊号");
        headMap.put("cardnumber", "读者证号");
        headMap.put("realname", "姓名");
        headMap.put("deptname", "部门");
        headMap.put("createtime", "借阅日期");
        headMap.put("duetime", "应还日期");
        headMap.put("returntime", "归还日期");
        headMap.put("isoverdueCn", "是否超期");

        try {
            ExcelExportUtil.listToExcel(list1, headMap, "期刊流通记录", this.getResponse());
        } catch (Exception e) {
            e.printStackTrace();
        }
        renderNull();
    }


    /**
     * 图书丢书记录
     */
    public void loseBook() {
        int orgid = this.getParaToInt("orgid");

        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        //Integer flag = this.getParaToInt("flag");
        Integer dept = this.getParaToInt("dept");
        Integer cancel = this.getParaToInt("cancel");
        String cardnumber = this.getPara("cardnumber");
        String title = this.getPara("title");

        success(service.loseBook(this.getParaToInt("pageNumber"), this.getParaToInt("pageSize"), orgid, kssj, jssj, dept, cancel, cardnumber, title));
    }

    /**
     * 图书丢书记录 --export
     */
    public void exportLoseBook() {
        int orgid = this.getParaToInt("orgid");

        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        //Integer flag = this.getParaToInt("flag");
        Integer dept = this.getParaToInt("dept");
        Integer cancel = this.getParaToInt("cancel");
        String cardnumber = this.getPara("cardnumber");
        String title = this.getPara("title");

        List<Record> list = service.exportLoseBook(orgid, kssj, jssj, dept, cancel, cardnumber, title);


        List list1 = new ArrayList();
        for (Record record1 : list) {
            if (record1.getInt("status") == 3) {
                record1.set("isoverdueCn", "是");
            } else {
                record1.set("isoverdueCn", "否");
            }
            list1.add(record1);
        }

        LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("barcode", "图书条码");
        headMap.put("isbn", "ISBN");
        headMap.put("title", "题名");
        headMap.put("bookno", "索书号");
        headMap.put("cardnumber", "读者证号");
        headMap.put("realname", "姓名");
        headMap.put("deptname", "部门");
        headMap.put("createtime", "借阅日期");
        headMap.put("duetime", "应还日期");
        headMap.put("remarks", "丢书原因");
        headMap.put("fcreatetime", "丢书处理日期");
        headMap.put("isoverdueCn", "是否注销");

        try {
            ExcelExportUtil.listToExcel(list1, headMap, "图书-丢书清单", this.getResponse());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 图书丢书注销
     */
    public void removeLoseBook() {
        Long[] detailids = this.getParaValuesToLong("detailids");
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if (operatorid == 0) {
            fail(3, "token错误");
            return;
        }
        if (detailids != null) {
            service.removeLoseBook(detailids, operatorid);
            success();
        } else {
            success(2, "请选择需要注销的图书");
        }
    }

    /**
     * 期刊丢书注销
     */
    public void removeLoseBookQ() {
        Long[] detailids = this.getParaValuesToLong("detailids");
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if (operatorid == 0) {
            fail(3, "token错误");
            return;
        }
        if (detailids != null) {
            service.removeLoseBookQ(detailids, operatorid);
            success();
        } else {
            success(2, "请选择需要注销的期刊");
        }
    }

    /**
     * 期刊丢书记录
     */
    public void loseBookQ() {
        int orgid = this.getParaToInt("orgid");

        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        Integer dept = this.getParaToInt("dept");
        Integer cancel = this.getParaToInt("cancel");
        String cardnumber = this.getPara("cardnumber");
        String title = this.getPara("title");

        success(service.loseBookQ(this.getParaToInt("pageNumber"), this.getParaToInt("pageSize"), orgid, kssj, jssj, dept, cancel, cardnumber, title));
    }

    /**
     * 期刊丢书记录 --export
     */
    public void exportLoseBookQ() {
        int orgid = this.getParaToInt("orgid");

        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        Integer dept = this.getParaToInt("dept");
        Integer cancel = this.getParaToInt("cancel");
        String cardnumber = this.getPara("cardnumber");
        String title = this.getPara("title");

        List<Record> list = service.exportLoseBookQ(orgid, kssj, jssj, dept, cancel, cardnumber, title);


        List list1 = new ArrayList();
        for (Record record1 : list) {
            if (record1.getInt("status") == 1) {
                record1.set("isoverdueCn", "是");
            } else {
                record1.set("isoverdueCn", "否");
            }
            list1.add(record1);
        }

        LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("barcode", "期刊条码");
        headMap.put("issn", "ISSN");
        headMap.put("kanming", "刊名");
        headMap.put("bookno", "索刊号");
        headMap.put("cardnumber", "读者证号");
        headMap.put("realname", "姓名");
        headMap.put("deptname", "部门");
        headMap.put("createtime", "借阅日期");
        headMap.put("duetime", "应还日期");
        headMap.put("remarks", "丢书原因");
        headMap.put("fcreatetime", "丢书处理日期");
        headMap.put("isoverdueCn", "是否超期");

        try {
            ExcelExportUtil.listToExcel(list1, headMap, "期刊-丢书清单", this.getResponse());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 图书损书记录
     */
    public void damagedBook() {
        int orgid = this.getParaToInt("orgid");

        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        Integer dept = this.getParaToInt("dept");
        String cardnumber = this.getPara("cardnumber");
        String title = this.getPara("title");

        success(service.damagedBook(this.getParaToInt("pageNumber"), this.getParaToInt("pageSize"), orgid, kssj, jssj, dept, cardnumber, title));
    }

    /**
     * 图书损书记录 --export
     */
    public void exportDamagedBook() {
        int orgid = this.getParaToInt("orgid");

        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        Integer dept = this.getParaToInt("dept");
        String cardnumber = this.getPara("cardnumber");
        String title = this.getPara("title");

        List<Record> list = service.exportDamagedBook(orgid, kssj, jssj, dept, cardnumber, title);

        LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("numbers", "序号");
        headMap.put("barcode", "图书条码");
        headMap.put("isbn", "ISBN");
        headMap.put("title", "题名");
        headMap.put("bookno", "索书号");
        headMap.put("cardnumber", "读者证号");
        headMap.put("realname", "姓名");
        headMap.put("deptname", "部门");
        headMap.put("createtime", "借阅日期");
        headMap.put("returntime", "还书日期");
        headMap.put("remarks", "损书描述");
        headMap.put("fcreatetime", "损书处理日期");

        List list1 = new ArrayList();
        for (Record record1 : list) {
            if (CommonUtils.isNotNullOrNotEmpty(record1.get("createtime"))) {
                record1.set("createtime", record1.getStr("createtime").split(" ")[0]);
            }
            if (CommonUtils.isNotNullOrNotEmpty(record1.get("returntime"))) {
                record1.set("returntime", record1.getStr("returntime").split(" ")[0]);
            }
            if (CommonUtils.isNotNullOrNotEmpty(record1.get("fcreatetime"))) {
                record1.set("fcreatetime", record1.getStr("fcreatetime").split(" ")[0]);
            }
            list1.add(record1);
        }

        try {
            ExcelExportUtil.listToExcel(list1, headMap, "图书-损书清单", this.getResponse());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 期刊损书记录
     */
    public void damagedBookQ() {
        int orgid = this.getParaToInt("orgid");

        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        Integer dept = this.getParaToInt("dept");
        String cardnumber = this.getPara("cardnumber");
        String title = this.getPara("title");

        success(service.damagedBookQ(this.getParaToInt("pageNumber"), this.getParaToInt("pageSize"), orgid, kssj, jssj, dept, cardnumber, title));
    }

    /**
     * 期刊损书记录 --export
     */
    public void exportDamagedBookQ() {
        int orgid = this.getParaToInt("orgid");

        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        Integer dept = this.getParaToInt("dept");
        String cardnumber = this.getPara("cardnumber");
        String title = this.getPara("title");

        List<Record> list = service.exportDamagedBookQ(orgid, kssj, jssj, dept, cardnumber, title);

        LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("barcode", "期刊条码");
        headMap.put("issn", "ISSN");
        headMap.put("kanming", "刊名");
        headMap.put("bookno", "索刊号");
        headMap.put("cardnumber", "读者证号");
        headMap.put("realname", "姓名");
        headMap.put("deptname", "部门");
        headMap.put("createtime", "借阅日期");
        headMap.put("returntime", "还书日期");
        headMap.put("remarks", "损书描述");
        headMap.put("fcreatetime", "损书处理日期");

        try {
            ExcelExportUtil.listToExcel(list, headMap, "期刊-损书清单", this.getResponse());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 图书注销清单
     */
    public void removeBook() {
        int orgid = this.getParaToInt("orgid");
        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        String booktype = this.getPara("booktype");
        Integer library = this.getParaToInt("library");
        String reason = this.getPara("reason");
        String barcode = this.getPara("barcode");
        String title = this.getPara("title");
        success(service.removeBook(this.getParaToInt("pageNumber"), this.getParaToInt("pageSize"), orgid, kssj, jssj, booktype, library, reason, barcode, title));
    }

    public void removeBookPrint() {
        int orgid = this.getParaToInt("orgid");
        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        String booktype = this.getPara("booktype");
        Integer library = this.getParaToInt("library");
        String reason = this.getPara("reason");
        String barcode = this.getPara("barcode");
        String title = this.getPara("title");
        success(service.removeBookPrint(orgid, kssj, jssj, booktype, library, reason, barcode, title));

    }

    /**
     * 图书注销总价
     */
    public void removeBookTotalPrice() {
        int orgid = this.getParaToInt("orgid");
        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        String booktype = this.getPara("booktype");
        Integer library = this.getParaToInt("library");
        String reason = this.getPara("reason");
        String barcode = this.getPara("barcode");
        String title = this.getPara("title");
        success(service.removeBookTotalPrice(orgid, kssj, jssj, booktype, library, reason, barcode, title));

    }

    /**
     * 图书注销清单 --导出
     */
    public void exportRemoveBook() {
        int orgid = this.getParaToInt("orgid");
        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        String booktype = this.getPara("booktype");
        Integer library = this.getParaToInt("library");
        String reason = this.getPara("reason");
        String barcode = this.getPara("barcode");
        String title = this.getPara("title");
        List list = service.exportRemoveBook(orgid, kssj, jssj, booktype, library, reason, barcode, title);
        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", "注销日期");

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

    /**
     * 期刊注销清单
     */
    public void removeBookQ() {
        int orgid = this.getParaToInt("orgid");
        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        String booktype = this.getPara("booktype");
        Integer library = this.getParaToInt("library");
        String reason = this.getPara("reason");
        String barcode = this.getPara("barcode");
        String title = this.getPara("title");
        success(service.removeBookQ(this.getParaToInt("pageNumber", 1), this.getParaToInt("pageSize", 10), orgid, kssj, jssj, booktype, library, reason, barcode, title));
    }

    /**
     * 图书注销总价
     */
    public void removeBookQTotalPrice() {
        int orgid = this.getParaToInt("orgid");
        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        String booktype = this.getPara("booktype");
        Integer library = this.getParaToInt("library");
        String reason = this.getPara("reason");
        String barcode = this.getPara("barcode");
        String title = this.getPara("title");
        success(service.removeBookQTotalPrice(orgid, kssj, jssj, booktype, library, reason, barcode, title));

    }

    public void exportRemoveBookQ() {
        int orgid = this.getParaToInt("orgid");
        String kssj = this.getPara("kssj");
        String jssj = this.getPara("jssj");
        String booktype = this.getPara("booktype");
        Integer library = this.getParaToInt("library");
        String reason = this.getPara("reason");
        String barcode = this.getPara("barcode");
        String title = this.getPara("title");
        List list = service.exportRemoveBookQ(orgid, kssj, jssj, booktype, library, reason, barcode, title);

        LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("barcode", "期刊条码");
        headMap.put("kanming", "刊名");
        headMap.put("bianjibu", "编辑部");
        headMap.put("bookno", "索刊号");
        headMap.put("price", "定价");
        headMap.put("library", "馆藏地");
        headMap.put("reason", "注销原因");
        headMap.put("createtime", "注销日期");

        try {
            ExcelExportUtil.listToExcel(list, headMap, "期刊注销清单", this.getResponse());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 图书丢书注销恢复
     */
    public void recoveryRemoveBook() {
        Long[] zxid = this.getParaValuesToLong("zxid");
        if (zxid != null) {
            service.recoveryRemoveBook(zxid);
            success();
        } else {
            success(2, "请选择需要恢复的图书");
        }
    }

    /**
     * 图书丢书注销恢复
     */
    public void recoveryRemoveBookQ() {
        Long[] zxid = this.getParaValuesToLong("zxid");
        if (zxid != null) {
            service.recoveryRemoveBookQ(zxid);
            success();
        } else {
            success(2, "请选择需要恢复的图书");
        }
    }



    public void findChaoqiByJieyueInfo() {
        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;
        }
        int jieyueid = this.getParaToInt("jieyueid");
        Jieyue jieyue = service.findById(jieyueid);
        if (jieyue.getOrgid() != orgid) {
            fail(1, "请求参数不正确!");
            return;
        }
        Map remap = new HashMap();
        Record authRecord = Db.findFirst("select a.* from t_reader r left join t_reader_auth a on r.readerauthid=a.id where r.id=?",jieyue.getReaderid());
        Date duetime = jieyue.getDuetime();
        long currentTime = System.currentTimeMillis();
        if (currentTime > duetime.getTime()) { // 超期
            remap.put("type", "超期");
            Map fakuanMap = chaoqifakuan(currentTime, duetime.getTime(), authRecord.get("chaoqifakuan"), authRecord.get("chaoqifakuanxiane"));
            remap.put("day", fakuanMap.get("day"));
            remap.put("amount", fakuanMap.get("amount"));
            success(remap);
        } else {
            success("noinfo");
        }
    }

    public void jieyueReport() {
        Integer orgid = getParaToInt("orgid");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);
        String begindate = getPara("begindate", DateUtils.getSimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
        String enddate = getPara("enddate", DateUtils.getSimpleDateFormat("yyyy-MM-dd").format(new Date()));
        success(service.jieyueReport(orgid, begindate, enddate));
    }

    public void floatingBookreprot() {
        int libraryid = getParaToInt("library",0);
        String library = libraryid == 0? "": libraryid+"";
        String begindate = getPara("begindate");
        String enddate = getPara("enddate");

        success(service.floatingBookreprot(library, begindate, enddate,getPara("orgid")));
    }

    public void curdate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> resultList = new ArrayList<String>();
        Calendar calendar = Calendar.getInstance();
        resultList.add(sdf.format(calendar.getTime()));
        calendar.add(Calendar.MONTH, -12);
        resultList.add(sdf.format(calendar.getTime()));
        success(resultList);
    }

    public void curdate_week() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> resultList = new ArrayList<String>();
        Calendar calendar = Calendar.getInstance();
        resultList.add(sdf.format(calendar.getTime()));
        calendar.add(Calendar.WEEK_OF_MONTH, -1);
        resultList.add(sdf.format(calendar.getTime()));
        success(resultList);
    }

    public void overdue() {
        render("/view/flow-manage/overdue.html");
    }


    public void overdueList() {
        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 queryStr = getPara("queryStr");
        String orgdeptid = getPara("dept");
        String title = getPara("title");
        String startDate = getPara("kssj");
        String endDate = getPara("jssj");
        Integer libraryid = getParaToInt("libraryid",0);

        success(service.overdueList(this.getParaToInt("pageNumber"), this.getParaToInt("pageSize"), queryStr, orgdeptid, title, startDate, endDate, orgid,libraryid));
    }


    public void exportOverdueList() {
        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 orgname = new Org().dao().findById(orgid).getOrgname();
        String queryStr = getPara("queryStr");
        String orgdeptid = getPara("dept");
        String title = getPara("title");
        String startDate = getPara("kssj");
        String endDate = getPara("jssj");

        List list = service.exportOverdueList(queryStr, orgdeptid, title, startDate, endDate, orgid);

        /*LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("title", "正题名/刊名");
        headMap.put("barcode", "书刊条码");
        headMap.put("duetime", "应还日期");
        headMap.put("createtime", "借阅日期");
        headMap.put("deptname", "部门");
        headMap.put("realname", "姓名");
        headMap.put("cardnumber", "读者证号");
        headMap.put("days", "超期天数");
        headMap.put("price", "定价");*/
        String fields[] = {"title","barcode","duetime","createtime","deptname","realname","cardnumber","days","price"};
        ExcelExportUtil_template.exportExcel("图书催还清单.xls",this.getResponse(),orgname+"图书催还清单",list,fields,2);
        renderNull();
    }


    public void exportOverdueQList() {
        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 queryStr = getPara("queryStr");
        String orgdeptid = getPara("dept");
        String title = getPara("title");
        String startDate = getPara("kssj");
        String endDate = getPara("jssj");

        List list = service.exportOverdueQList(queryStr, orgdeptid, title, startDate, endDate, orgid);

        LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("title", "正题名/刊名");
        headMap.put("barcode", "书刊条码");
        headMap.put("duetime", "应还日期");
        headMap.put("createtime", "借阅日期");
        headMap.put("deptname", "部门");
        headMap.put("realname", "姓名");
        headMap.put("cardnumber", "读者证号");
        headMap.put("days", "超期天数");
        headMap.put("price", "定价");
        headMap.put("niandu", "年度");
        headMap.put("qizhiqi", "起止期");
        try {
            ExcelExportUtil.listToExcel(list, headMap, "催还清单", this.getResponse());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void findJieyueListInfoByOrgid() {
        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.findJieyueListInfoByOrgid(this.getParaToInt("pageNumber"), this.getParaToInt("pageSize"), orgid));
    }

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

            UploadFile file = getFile();
            List<Map<String, String>> jieyueList = ExcelUtil.readExcel(new FileInputStream(file.getFile()));
            List<Map<String, String>> errorDataList = new ArrayList<Map<String, String>>();

            for (Map<String, String> readermap : jieyueList) {
                try{
                    if (CommonUtils.isNullOrEmpty(readermap.get("借阅日期")) && CommonUtils.isNullOrEmpty(readermap.get("归还日期"))){
                        readermap.put("未导入原因","借阅日期与归还日期不能同时为空!");
                        errorDataList.add(readermap);
                        continue;
                    }

                    if ("".equals(readermap.get("图书条码"))){
                        readermap.put("未导入原因","图书条码为空!");
                        errorDataList.add(readermap);
                        continue;
                    }
                    if ("".equals(readermap.get("读者证号"))){
                        readermap.put("未导入原因","读者证号为空!");
                        errorDataList.add(readermap);
                        continue;
                    }
                    Jieyue jieyue = new Jieyue();
                    Record book=   Db.findFirst("select a.id,a.status from t_book_detail as a left join t_book as b on a.bookid = b.id where a.barcode=? and b.orgid= ?",readermap.get("图书条码"),orgid);
                    if (null==book){
                        readermap.put("未导入原因","找不到图书!");
                        errorDataList.add(readermap);
                        continue;
                    }

                    Record reader = Db.findFirst("SELECT * FROM t_reader WHERE cardnumber =? and orgid= ?",readermap.get("读者证号"),orgid);

                    if (null==reader){
                        readermap.put("未导入原因","读者信息为空!");
                        errorDataList.add(readermap);
                        continue;
                    }
                    Record readerAuthRecord = Db.findById("t_reader_auth",reader.getInt("readerauthid"));
                    if (null==readerAuthRecord){
                        readermap.put("未导入原因","读者权限为空!");
                        errorDataList.add(readermap);
                        continue;
                    }
                    if(CommonUtils.isNotNullOrNotEmpty(readermap.get("归还日期")) && CommonUtils.isNotNullOrNotEmpty(readermap.get("借阅日期"))){
                        jieyue.setOrgid(orgid);
                        jieyue.setReaderid(reader.get("id"));
                        jieyue.setBookdetailid(book.getInt("id"));
                        jieyue.setContinuenum(0);
                        jieyue.setFlag(0);
                        jieyue.setStatus(1);
                        jieyue.setCreatetime(DateUtils.getSimpleDateFormat("yyyy-MM-dd").parse(readermap.get("借阅日期")));

                        jieyue.setOperatorid(operatorid);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(format1.parse(readermap.get("借阅日期")));
                        calendar.add(Calendar.DAY_OF_MONTH, readerAuthRecord.getInt("jieyuetianshu"));

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String datestr = sdf.format(calendar.getTime());
                        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        jieyue.setDuetime(sdf2.parse(datestr + " 23:59:59"));
                        jieyue.setReturntime(DateUtils.getSimpleDateFormat("yyyy-MM-dd").parse(readermap.get("归还日期")));
                        jieyue.setReturnuserid(operatorid);
                        jieyue.save();
                        Db.update("update t_book_detail  set jieyuenums=jieyuenums+1,status=1 where id =?",book.getInt("id"));
                    } else if (CommonUtils.isNullOrEmpty(readermap.get("归还日期"))  && CommonUtils.isNotNullOrNotEmpty(readermap.get("借阅日期"))){
                        if (!book.getInt("status").equals(0)){
                            readermap.put("未导入原因","借书失败，该书不是在馆状态!");
                            errorDataList.add(readermap);
                            continue;
                        }else {
                            jieyue.setBookdetailid(book.getInt("id"));
                            jieyue.setOrgid(orgid);
                            jieyue.setOperatorid(operatorid);
                            jieyue.setContinuenum(0);
                            jieyue.setFlag(0);
                            jieyue.setStatus(0);
                            jieyue.setReaderid(reader.get("id"));
                            jieyue.setCreatetime(DateUtils.getSimpleDateFormat("yyyy-MM-dd").parse(readermap.get("借阅日期")));
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(format1.parse(readermap.get("借阅日期")));
                            calendar.add(Calendar.DAY_OF_MONTH, readerAuthRecord.getInt("jieyuetianshu"));

                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            String datestr = sdf.format(calendar.getTime());
                            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            jieyue.setDuetime(sdf2.parse(datestr + " 23:59:59"));
                            jieyue.setReturnuserid(operatorid);
                            jieyue.save();

                            Db.update("update t_book_detail  set jieyuenums=jieyuenums+1,status=1 where id =?",book.getInt("id"));
                        }
                    }else if (CommonUtils.isNotNullOrNotEmpty(readermap.get("归还日期"))  && CommonUtils.isNullOrEmpty(readermap.get("借阅日期"))) {
                        if (book.getInt("status").equals(1)) {  //如果当前状态是再借中 则为还书操作
                            Record jieyuer = Db.findFirst("select id ,status,createtime,readerid from t_jieyue where bookdetailid =? and orgid=? order by id desc  ", book.getInt("id"), orgid);
                            Db.update("update t_jieyue  set returntime=?,status=1,returnuserid=? where id =?", DateUtils.getSimpleDateFormat("yyyy-MM-dd").parse(readermap.get("归还日期")), operatorid, jieyuer.getInt("id"));
                            Db.update("update t_book_detail set status=? where id=?", 0, book.getInt("id"));
                        } else {
                            readermap.put("未导入原因","还书失败，书籍当前不属于在借中!");
                            errorDataList.add(readermap);
                            continue;
                        }
                    }
                }catch (Exception e){
                    if (e instanceof  ParseException){
                        readermap.put("未导入原因","日期格式不正常");
                    }else {
                        readermap.put("未导入原因",e.getMessage());
                    }
                    errorDataList.add(readermap);
                }
            }
            String filename = "";
            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 (Exception e) {
            fail();
        }
    }


    public void findJieyueList() {
        String cardnumber = this.getPara("cardnumber");
        int orgid = this.getParaToInt("orgid", 0);
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if (operatorid == 0) {
            fail(3, "token错误");
            return;
        }
        if (orgid == 0) {
            fail(1, "请求参数不完整!");
            return;
        }
        success(service.findJieyueList( cardnumber, orgid));
    }


    public void jieyuereport(){
        int orgid = this.getParaToInt("orgid", 0);
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if (operatorid == 0) {
            fail(3, "token错误");
            return;
        }
        if (orgid == 0) {
            fail(1, "请求参数不完整!");
            return;
        }
        String starttime = getPara("starttime");
        String endtime = getPara("endtime");
        success(service.jieyuereport(orgid, starttime, endtime));
    }

    public void jieyuezhongreport(){
        int orgid = this.getParaToInt("orgid", 0);
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if (operatorid == 0) {
            fail(3, "token错误");
            return;
        }
        if (orgid == 0) {
            fail(1, "请求参数不完整!");
            return;
        }
        success(service.jieyuereport(orgid));
    }

    public void findCardnumber(){
        int orgid = this.getParaToInt("orgid", 0);
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if (operatorid == 0) {
            fail(3, "token错误");
            return;
        }
        if (orgid == 0) {
            fail(1, "请求参数不完整!");
            return;
        }
        String realname = getPara("realname");
        success(service.findCardnumber(orgid, realname));
    }

}
