package com.controller.api;


import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Clear;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.model.BookDetail;
import com.model.Jieyue;
import com.model.Reader;
import com.utils.CommonUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;

@Clear
@ControllerInterface(path="/api/jswplg")
public class JswPlgApiController extends BaseController {
    BookDetail bookDetailDao = new BookDetail().dao();
    Reader readerDao = new Reader().dao();
    public void queryBookInfo(){
        try{
            Record resultRecord = new Record();
            String orgid = getPara("orgid");
            String bookId = getPara("rfid");
            Record record = Db.findFirst("select d.`status`,d.barcode,d.rfid,b.title,b.author,b.isbn,b.price,b.bookno,b.keyword," +
                    "(select library from t_library where id = d.libraryid) library,b.publisher " +
                    "from t_book b inner join t_book_detail d on b.id = d.bookid where b.orgid = ? and d.rfid =?",orgid,bookId);
            if(CommonUtils.isNullOrEmpty(record)) {
                fail(0,"查询不到书籍信息，请联系图书管理员");
                return ;
            }
            int status = record.getInt("status");

            resultRecord.set("status",status);
            resultRecord.set("rfid",(CommonUtils.isNotNullOrNotEmpty(record.get("rfid"))?record.get("rfid"):""));
            resultRecord.set("title",(CommonUtils.isNotNullOrNotEmpty(record.get("title"))?record.get("title"):""));
            resultRecord.set("author",(CommonUtils.isNotNullOrNotEmpty(record.get("author"))?record.get("author"):""));
            resultRecord.set("isbn",(CommonUtils.isNotNullOrNotEmpty(record.get("isbn"))?record.get("isbn"):""));
            resultRecord.set("price",(CommonUtils.isNotNullOrNotEmpty(record.get("price"))?record.get("price"):""));
            resultRecord.set("bookno",(CommonUtils.isNotNullOrNotEmpty(record.get("bookno"))?record.get("bookno"):""));
            resultRecord.set("library",(CommonUtils.isNotNullOrNotEmpty(record.get("library"))?record.get("library"):""));
            resultRecord.set("publisher",(CommonUtils.isNotNullOrNotEmpty(record.get("publisher"))?record.get("publisher"):""));
            resultRecord.set("keyword",(CommonUtils.isNotNullOrNotEmpty(record.get("keyword"))?record.get("keyword"):""));
            resultRecord.set("barcode",(CommonUtils.isNotNullOrNotEmpty(record.get("barcode"))?record.get("barcode"):""));
            Record jieyueTimeRecord = Db.findFirst("select j.createtime,j.duetime from t_jieyue j left join t_book_detail d on j.bookdetailid = d.id " +
                    "where d.rfid = ? and j.orgid = ? order by j.id desc",bookId,orgid);
            if(CommonUtils.isNotNullOrNotEmpty(jieyueTimeRecord)) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                resultRecord.set("duetime",simpleDateFormat.format(jieyueTimeRecord.getDate("duetime")));
                resultRecord.set("createtime",simpleDateFormat.format(jieyueTimeRecord.getDate("createtime")));
            }
            /*if(status == 1){
                success(0,"该书已借出，不能借阅",resultRecord);
                return;
            }else if(status == 2){
                success(1,"该书已被预约，不能借阅",resultRecord);
                return;
            }else if(status == 3){
                success(1,"该书已被注销，不能借阅",resultRecord);
                return;
            }else if(status > 0){
                success(1,"该书状态异常，不能借阅",resultRecord);
                return;
            }*/
            //int status = CommonUtils.isNotNullOrNotEmpty(record.get("status"))?record.getInt("status"):9;



            success(resultRecord);
        }catch(Exception e){
            fail(1,"数据异常");
            return;
        }
    }
    /**
     * 漂流贵图书上架
     */
    public void shangjia(){
        int orgid = getParaToInt("orgid", 0);
        int libraryid = getParaToInt("libraryid", 0);
        String rfid = getPara("rfid");
        String sql = "select d.id, barcode,title,author,publisher from t_book_detail d inner join t_book b on d.bookid=b.id where rfid=? and b.orgid=? ";
        Record res = Db.findFirst(sql,rfid,orgid);
        bookDetailDao.findById(res.getInt("id")).setShangjiatime(new Date()).setLibraryid(libraryid).update();
        res.set("msg","上架成功");
        success(res);
    }

    /**
     * 漂流贵图书下架
     */
    public void xiajia(){
        int orgid = getParaToInt("orgid", 0);
        String rfid = getPara("rfid");
        Record library = Db.findFirst("select id from t_library where orgid=?", orgid);
        String sql = "select d.id,barcode,title,author,publisher from t_book_detail d inner join t_book b on d.bookid=b.id where rfid=? and b.orgid=? ";
        Record res = Db.findFirst(sql,rfid,orgid);
        bookDetailDao.findById(res.getInt("id")).setLibraryid(library.getInt("id")).update();
        res.set("msg","下架成功");
        success(res);

    }
    public void findCuihuanList(){
        try {
            int orgid = getParaToInt("orgid",0);
            StringBuffer where = new StringBuffer("select * from (select b.title,d.barcode,DATE_FORMAT(j.duetime,'%Y-%m-%d') duetime,DATE_FORMAT(j.createtime,'%Y-%m-%d') createtime,od.deptname,r.realname,r.cardnumber,(to_days(now()) - to_days(duetime)) days,b.price from t_jieyue j ");
            where.append(" inner join t_book_detail d on j.bookdetailid = d.id ");
            where.append(" inner join t_book b on d.bookid = b.id ");
            where.append(" inner join t_org o on j.orgid = o.id ");
            where.append(" inner join t_reader r on j.readerid = r.id ");
            where.append(" inner join t_org_dept od on r.orgdeptid = od.id");
            where.append(" where j.isoverdue = 1 and j.flag = 0 and j.status = 0 and j.orgid = ? ");
            where.append(" ) t order by days limit 0,200");
            success(Db.find(where.toString(), orgid));
        }catch(Exception e){
            fail();
        }
    }
    public void xinshutongbao(){
        try{
            int orgid = getParaToInt("orgid",0);
            success(Db.find("select title,author,bookno from t_book where orgid=? order by createtime desc limit 0,100",orgid));
        }catch(Exception e){
            fail();
        }

    }
    public void rementushu(){
        try{
            int orgid = getParaToInt("orgid");
            String sql = "select * from (" +
                    "select b.title,b.author,b.bookno,count(j.id) num from t_jieyue j inner join t_book_detail bd on bd.id=j.bookdetailid " +
                    "inner join t_book b on b.id=bd.bookid" +
                    " where j.orgid=? group by b.title) table1 order by num desc limit 0,100";
            List<Record> list = Db.find(sql,orgid);
            success(list);
        }catch(Exception e){
            fail();
        }


    }
    public void downReaderHeader(){
        int readerid = getParaToInt("readerid",0);
        if(readerid == 0){
            fail();
            return;
        }
        Reader reader = readerDao.findById(readerid);
        if(reader == null){
            fail();
            return;
        }
        Map map = new HashMap();
        if(StringUtils.isNotBlank(reader.getReadcardcode())){
            map.put("cardnumber", reader.getReadcardcode());
        }else {
            map.put("cardnumber", reader.getCardnumber());
        }
        String flag = "jpg";
        String base64 = reader.getHeadimgurl();
        if(StringUtils.isNotBlank(base64)) {
            base64 = base64.replace("data:image/", "");
            flag = base64.substring(0, base64.indexOf(";"));
            map.put("flag", flag);
            base64 = reader.getHeadimgurl().replace("data:image/" + flag + ";base64,", "");
            map.put("base64", base64);
        }
        success(map);

    }

    public void uploadTongbuTxt(){
        try{
            UploadFile file =getFile();
            String orgid = getPara("orgid");
            if(StringUtils.isBlank(orgid)){
                fail();
                return;
            }
            System.out.println("orgid:"+orgid);
            File image = file.getFile();
            System.out.println("txt："+image.getPath());
            String sb = FileUtils.readFileToString(file.getFile(), "UTF-8");
            System.out.println(sb);
            Map result = new HashMap();
            result.put("code",200);
            result.put("msg","调用成功");
            if(StringUtils.isNotBlank(sb)){
                List<Reader> readerList = readerDao.find("select id, cardnumber, readcardcode from t_reader where orgid=? and (headimgurl is null or headimgurl='') and " +
                        "(cardnumber in ("+sb.substring(1)+") or readcardcode in ("+sb.substring(1)+")) ",orgid);
                StringBuilder resStr = new StringBuilder();
                Map<String, String> map = new HashMap<>();
                for(Reader r : readerList){
                    if(r.getCardnumber() != null && map.get(r.getCardnumber()) == null){
                        resStr.append(","+r.getCardnumber());
                        map.put(r.getCardnumber(),"");
                    }
                    if(r.getReadcardcode() != null && map.get(r.getReadcardcode()) == null){
                        resStr.append(","+r.getReadcardcode());
                        map.put(r.getReadcardcode(),"");
                    }
                }
                if(StringUtils.isNotBlank(resStr)){
                    result.put("data1",resStr.substring(1));
                }
                List<Reader> readerList2 = readerDao.find("select id from t_reader where orgid=? and (headimgurl is not null or headimgurl='') and " +
                        "(cardnumber not in ("+sb.substring(1)+") and readcardcode not in ("+sb.substring(1)+")) ",orgid);
                StringBuilder resStr2 = new StringBuilder();
                for(Reader r : readerList2){
                    resStr2.append(","+r.getId());
                }
                if(StringUtils.isNotBlank(resStr2)){
                    result.put("data2",resStr2.substring(1));
                }
            }else{
                List<Reader> readerList2 = readerDao.find("select id from t_reader where orgid=? and headimgurl is not null",orgid);
                StringBuilder resStr2 = new StringBuilder();
                for(Reader r : readerList2){
                    resStr2.append(","+r.getId());
                }
                if(StringUtils.isNotBlank(resStr2)){
                    result.put("data2",resStr2.substring(1));
                }
            }





            this.renderJson(result);

        }catch(Exception e){
            e.printStackTrace();fail();
        }
    }
    public void uploadHeaderImg(){
        try{
            UploadFile file =getFile();
            String orgid = getPara("orgid");
            String cardnumber = getPara("cardnumber");
            if(StringUtils.isBlank(orgid) || StringUtils.isBlank(cardnumber)){
                fail();
                return;
            }

            File image = file.getFile();
            System.out.println("图片地址："+image.getPath());
            String flag = image.getName().substring(image.getName().lastIndexOf(".")+1);
            Reader reader = readerDao.findFirst("select * from t_reader where  orgid=? and (cardnumber=? or readcardcode=?)", orgid, cardnumber,cardnumber);
            if(reader == null){
                System.out.println("读者不存在");
                fail();
                return;
            }
            String base64 = convertFileToBase64(image.getPath());
            reader.setHeadimgurl("data:image/"+flag+";base64,"+base64).update();
            success();
        }catch(Exception e){
            e.printStackTrace();fail();
        }
    }
    public void myjieyue(){
        try{
            String orgid = getPara("orgid");
            String readerCardId = getPara("cardnumber");
            String sql = "select r.id, r.cardnumber,r.realname,status,losedate from t_reader r where orgid=? and (r.readcardcode = ? or r.cardnumber = ?)";
            Record record = Db.findFirst(sql,orgid,readerCardId,readerCardId);
            if(CommonUtils.isNotNullOrNotEmpty(record)){
                Timestamp losedate = record.get("losedate");
                long currentTime = System.currentTimeMillis();
                if(currentTime>losedate.getTime()) { //如果当前时间大于有效期 则说明已过期
                    fail(0,"读者证已过期");
                    return ;
                }
                int readerStatus = record.get("status");
                if(readerStatus != 1) {
                    fail(0,"读者证状态异常");
                    return ;
                }
                List<Record> list = Db.find("select j.createtime,j.duetime,j.isoverdue,b.title,b.author,d.barcode from t_jieyue j inner join t_book_detail d on d.id=j.bookdetailid " +
                        "inner join t_book b on b.id=d.bookid  where j.readerid=? and j.status=0 ", record.getInt("id"));
                if(list !=null && list.size()>0){
                    for(Record r : list){
                        if(r.get("createtime") != null){
                            r.set("createtime", format1.format(r.getDate("createtime")));
                        }
                        if(r.get("duetime") != null){
                            r.set("duetime", format1.format(r.getDate("duetime")));
                        }
                    }
                }
                success(list);
            } else {
                fail(0,"读者信息为空");
                return;
            }
        }catch(Exception e){
            fail(1,"数据异常");
            return;
        }

    }
    public void queryReaderInfo(){
        try{
            Record resultRecord = new Record();
            String orgid = getPara("orgid");
            String readerCardId = getPara("cardnumber");
            String sql = "select r.*,a.jieyueshuliang,a.name typename," +
                    "(select count(*) from t_jieyue where status = 0 and readerid = r.id) yijienumber," +
                    "(select count(*) from t_jieyue where status = 0 and isoverdue = 1 and readerid = r.id) overduenumber " +
                    "from t_reader r inner join t_reader_auth a on r.readerauthid = a.id where r.orgid=? and (r.readcardcode = ? or r.cardnumber = ?)";
            Record record = Db.findFirst(sql,orgid,readerCardId,readerCardId);
            if(CommonUtils.isNotNullOrNotEmpty(record)){
                Timestamp losedate = record.get("losedate");
                long currentTime = System.currentTimeMillis();
                if(currentTime>losedate.getTime()) { //如果当前时间大于有效期 则说明已过期
                    fail(0,"读者证已过期");
                    return ;
                }
                int readerStatus = record.get("status");
                if(readerStatus != 1) {
                    fail(0,"读者证状态异常");
                    return ;
                }

                Record authRecord = Db.findFirst("select a.* from t_reader r inner join t_reader_auth a on r.readerauthid=a.id where (r.readcardcode='" + readerCardId + "' or r.cardnumber ='" + readerCardId + "') and r.orgid=?",orgid);
                if(CommonUtils.isNullOrEmpty(authRecord)) {
                    fail(0,"权限异常");
                    return ;
                }
                int shifounengchaoqijieshu = authRecord.get("shifounengchaoqijieshu");
                int shifounengqiankuanjieshu = authRecord.get("shifounengqiankuanjieshu");
                int jieyueshuliang = authRecord.get("jieyueshuliang");
                if(1 == shifounengchaoqijieshu) {
                    if(null != record.get("overdue")) {
                        int overdue = record.get("overdue");
                        if (1 == overdue) {
                            fail(0,"超期不允许借书");
                            return ;
                        }
                    }
                }
                if(1 == shifounengqiankuanjieshu) {
                    Record qiankuanRecord = Db.findFirst("select count(1) qiankuannum from t_book_penalty p inner join t_reader r on p.readerid = r.id where penaltystatus = 0 and penaltyamount > 0 and (r.readcardcode = ? or r.cardnumber = ?)",readerCardId,readerCardId);
                    int qiankuannum = qiankuanRecord.getInt("qiankuannum");
                    if (qiankuannum > 0) {
                        fail(0,"欠款不允许借书");
                        return ;
                    }
                }
                int overduenumber = record.getInt("overduenumber");
                int yijienumber = record.getInt("yijienumber");

                if (yijienumber > jieyueshuliang) {
                    fail(0,"已超过可借数量");
                    return ;
                }
                resultRecord.set("yijienumber",yijienumber); //当前借书数量
                resultRecord.set("overduenumber",overduenumber); //超期图书数量
                resultRecord.set("readerCardId",readerCardId); //读者证号，不可以为空
                resultRecord.set("realname",record.getStr("realname")); //读者名字
                resultRecord.set("jieyueshuliang",jieyueshuliang);
                /*if(jieyueshuliang - yijienumber > 0) {
                    resultRecord.set("jieyueshuliang",jieyueshuliang); //允许最大借书数
                } else {
                    resultRecord.set("jieyueshuliang",0); //允许最大借书数
                }*/
                resultRecord.set("typename",record.getStr("typename"));
                resultRecord.set("losedate",record.getStr("losedate").substring(0,10));

                List<Record> jieyueBarcodeList = Db.find("select d.rfid from t_jieyue j left join t_book_detail d on " +
                        " j.bookdetailid = d.id left join t_reader r on j.readerid = r.id where j.status = 0 and " +
                        " (r.readcardcode = ? or r.cardnumber = ?) and j.orgid = ?",readerCardId,readerCardId,orgid);

                resultRecord.set("jieyueBarcodeList",jieyueBarcodeList);
                if(jieyueshuliang - yijienumber < 0) {
                    fail(0,"已超过可借数量");
                    return ;
                    //resultRecord.set("reinfo","已超过可借数量");
                } else {
                    resultRecord.set("reinfo","查询成功");
                }
            } else {
                fail(0,"读者信息为空");
                return;
            }
            success(resultRecord);
        }catch(Exception e){
            fail(1,"数据异常");
        }

    }
    public void queryReaderInfo_jieyuelist(){
        try{
            Record resultRecord = new Record();
            String orgid = getPara("orgid");
            String readerCardId = getPara("cardnumber");
            String sql = "select r.cardnumber,r.realname,status,losedate from t_reader r where orgid=? and (r.readcardcode = ? or r.cardnumber = ?)";
            Record record = Db.findFirst(sql,orgid,readerCardId,readerCardId);
            if(CommonUtils.isNotNullOrNotEmpty(record)){
                Timestamp losedate = record.get("losedate");
                long currentTime = System.currentTimeMillis();
                if(currentTime>losedate.getTime()) { //如果当前时间大于有效期 则说明已过期
                    fail(0,"读者证已过期");
                    return ;
                }
                int readerStatus = record.get("status");
                if(readerStatus != 1) {
                    fail(0,"读者证状态异常");
                    return ;
                }
                success(record);
            } else {
                fail(0,"读者信息为空");
                return;
            }
        }catch(Exception e){
            fail(1,"数据异常");
            return;
        }

    }
    public void jiansuo(){
        try{
            String text = getPara("text");
            String orgid = getPara("orgid");
            int libraryid = getParaToInt("libraryid",0);
            try{
                if(StringUtils.isBlank(text)){
                    success(new Page());
                }

                List values = new ArrayList();
                values.add(orgid);
                values.add("%"+text+"%");
                String where = "";

                where = "from t_book b inner join t_book_detail e on e.bookid=b.id where orgid=? and title like ?";
                if(libraryid>0){
                    where+=" and libraryid=?";
                    values.add(libraryid);
                }


                Page<Record> page = Db.paginate(getParaToInt("pageNumber", 1),getParaToInt("pageSize", 10),
                        "select b.id,title,author,publisher,bookno,(select count(id) from t_book_detail d where d.bookid = b.id and d.status=0) as zaiguan," +
                                "(select count(id) from t_book_detail d where d.bookid = b.id ) as totalnum ",
                        where, listToArray(values));
                success(page);
            }catch(Exception e){
                e.printStackTrace();
                success(new Page());
            }
        }catch(Exception e){
            fail(1,"数据异常");
            return;
        }

    }
    public void bindReader(){
        String cardnumber = getPara("cardnumber");
        String code = getPara("code");
        int orgid = getParaToInt("orgid", 0);
        if(StringUtils.isBlank(cardnumber) || StringUtils.isBlank(code) || orgid == 0){
            fail(1,"参数不完整");
            return;
        }
        Reader reader = readerDao.findFirst("select id from t_reader where cardnumber=? and password=? and orgid=?",cardnumber,code,orgid);
        if(reader == null){
            fail(1,"读者证号或确认码错误");
            return ;
        }
        success();
    }
    public void borrowBooks(){
        try{
            Record resultRecord = new Record();

            String orgid = getPara("orgid");
            String libraryid = getPara("libraryid");
            String readerCardId = getPara("cardnumber");
            String bookrfid = getPara("rfid");
            String equipmentid = getPara("equipmentid");
            Record readerRecord = Db.findFirst("select id,cardnumber from t_reader where (readcardcode = ? or cardnumber = ?) and orgid=?",readerCardId,readerCardId,orgid);
            Record bookRecord = Db.findFirst("select b.title,b.price,d.id,d.barcode,b.author ,d.status,d.rfid from t_book b inner join t_book_detail d on b.id = d.bookid where (d.rfid =? or d.barcode=?) and b.orgid=?",bookrfid,bookrfid,orgid);
            resultRecord.set("barcode", "");
            resultRecord.set("author", "");
            resultRecord.set("title", "");
            if(CommonUtils.isNullOrEmpty(bookRecord)) {

                resultRecord.set("reinfo","查询不到书籍信息");
                success(2,"查询不到书籍信息",resultRecord);
                return ;
            }
            resultRecord.set("title",bookRecord.getStr("title"));
            resultRecord.set("author", bookRecord.get("author"));
            resultRecord.set("barcode", bookRecord.get("barcode"));
            if(CommonUtils.isNullOrEmpty(readerRecord)) {
                resultRecord.set("reinfo","查询不到读者信息");
                success(2,"查询不到读者信息",resultRecord);
                return ;
            }

            int status = bookRecord.getInt("status");
            if(status == 1){
                resultRecord.set("reinfo","该书已借出");
                success(2,"该书已借出",resultRecord);
                return;
            }else if(status == 2){
                resultRecord.set("reinfo","该书已被预约");
                success(2,"该书已被预约",resultRecord);
                return;
            }else if(status == 3){
                resultRecord.set("reinfo","该书已被注销");
                success(2,"该书已被注销",resultRecord);
                return;
            }else if(status > 0){
                resultRecord.set("reinfo","该书状态异常，不能借阅");
                success(2,"该书状态异常，不能借阅",resultRecord);
                return;
            }
            try {
                Record authRecord = Db.findFirst("select a.* from t_reader r left join t_reader_auth a on r.readerauthid=a.id where r.readcardcode='" + readerCardId + "' or r.cardnumber ='" + readerCardId + "' and r.orgid=?",orgid);
                int jieyuetianshu = authRecord.getInt("jieyuetianshu");

                int jieyueshuliang = authRecord.getInt("jieyueshuliang");
                Record jieyueCountRecord = Db.findFirst("select count(*) count from t_jieyue where status = 0 and readerid =?",readerRecord.getInt("id"));
                if(jieyueCountRecord.getInt("count") > jieyueshuliang) {
                    String currentDate = format1.format(new Date());
                    System.err.println(currentDate);
                    Db.update("update t_jieyue set exceed = ? where status = 0 and readerid =?",currentDate,readerRecord.getInt("id"));
                    Db.update("update t_reader set status = 3 where id = ? and status = 1",readerRecord.getInt("id"));
                    //resultRecord.set("reinfo","达到借书量上限，借书失败");
                    //fail(0,"达到借书量上限，借书失败");
                    // return;
                }



                Calendar calendar = Calendar.getInstance();
                Jieyue jieyue = new Jieyue();
                jieyue.setReaderid(readerRecord.get("id"));
                jieyue.setOrgid(Integer.valueOf(orgid));
                jieyue.setBookdetailid(bookRecord.get("id"));
                jieyue.setFlag(0);
                jieyue.setStatus(0);
                jieyue.setJieyuetype(2);
                jieyue.setLibraryid(Integer.parseInt(libraryid));
                if(CommonUtils.isNotNullOrNotEmpty(equipmentid)){
                    jieyue.setEquipmentid(Integer.parseInt(equipmentid));
                }
                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");
                jieyue.setDuetime(sdf2.parse(datestr + " 23:59:59"));
                jieyue.setOperatorid(999999);
                jieyue.save();
                Db.update("update t_book_detail set status = 1,jieyuenums = ifnull(jieyuenums,0)+1 where id = ?", bookRecord.getInt("id"));


                resultRecord.set("rfid",bookRecord.getStr("rfid"));

                resultRecord.set("price",bookRecord.getStr("price"));
                resultRecord.set("readerCardId",readerCardId);
                resultRecord.set("returntime",sdf2.parse(datestr + " 23:59:59"));
                resultRecord.set("reinfo","借书成功");
            } catch (ParseException e) {
                fail(0,"借书异常");
                e.printStackTrace();
                return;
            }
            success(resultRecord);
        }catch(Exception e){
            fail(1,"数据异常");
            return;
        }

    }

    public void returnBooks(){
        try {
            Record resultRecord = new Record();
            String orgid = getPara("orgid");
            String libraryid = getPara("libraryid");
            String bookrfid = getPara("rfid");
            Record bookRecord = Db.findFirst("select b.bookno,b.title,b.author,b.price,d.id,d.barcode,d.rfid from t_book b inner join t_book_detail d on b.id = d.bookid where d.rfid =? and b.orgid=?", bookrfid, orgid);
            resultRecord.set("barcode", "");
            resultRecord.set("author", "");
            resultRecord.set("title", "");
            if (CommonUtils.isNullOrEmpty(bookRecord)) {
                resultRecord.set("reinfo","查询不到书籍信息");
                success(resultRecord);
                return;
            }
            resultRecord.set("barcode", bookRecord.get("barcode"));
            resultRecord.set("author", bookRecord.get("author"));
            resultRecord.set("title", bookRecord.get("title"));
            Record jieyueRecord = Db.findFirst("select * from t_jieyue where bookdetailid = ? and status=0 ORDER BY createtime desc", bookRecord.getInt("id"));
            if (CommonUtils.isNullOrEmpty(jieyueRecord)) {
                resultRecord.set("reinfo","查询不到借阅信息");
                success(2,"查询不到借阅信息",resultRecord);
                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='" + jieyueRecord.getInt("readerid") + "'");
            if (CommonUtils.isNullOrEmpty(authRecord)) {
                resultRecord.set("reinfo","查询不到读者权限信息");
                success(2,"查询不到读者权限信息",resultRecord);
                return;
            }

            Record library = Db.findFirst("select library from t_library where id = ? ", libraryid);
            if (CommonUtils.isNullOrEmpty(library)) {
                resultRecord.set("reinfo","查询不到馆藏地信息");
                success(2,"查询不到馆藏地信息",resultRecord);
                return;
            }
            Integer isoverdue = jieyueRecord.getInt("isoverdue");
            BigDecimal amount = new BigDecimal(0);
            //已超期
            if (CommonUtils.isNotNullOrNotEmpty(isoverdue) && 1 == isoverdue) {
                Timestamp duetime = jieyueRecord.get("duetime");
                LocalDateTime dueDate = duetime.toLocalDateTime();
                BigDecimal chaoqifakuan = authRecord.getBigDecimal("chaoqifakuan");
                BigDecimal chaoqifakuanxiane = authRecord.getBigDecimal("chaoqifakuanxiane");
                Duration duration = Duration.between(LocalDateTime.now(), dueDate);
                long days = duration.toDays(); //超期的天数
                amount = chaoqifakuan.multiply(new BigDecimal(days));
                //判断是否大于超期限额
                if (amount.compareTo(chaoqifakuanxiane) > 0 && chaoqifakuanxiane.compareTo(BigDecimal.ZERO) != 0) {
                    amount = chaoqifakuanxiane;
                }
                //标记为超期
                jieyueRecord.set("isoverdue", 1);
                //保存罚款记录
                Record penalty = new Record();
                penalty.set("orgid", orgid);
                penalty.set("readerid", jieyueRecord.get("readerid"));
                penalty.set("bookdetailid", bookRecord.get("id"));
                penalty.set("jieyueid", jieyueRecord.get("id"));
                penalty.set("penaltystatus", 0);
                penalty.set("penaltyamount", amount);
                penalty.set("flag", 0);
                penalty.set("type", 2);
                Db.save("t_book_penalty", penalty);
            } else {
                jieyueRecord.set("isoverdue", 2);
            }
            jieyueRecord.set("status", 1);
            jieyueRecord.set("returntime", new Date());
            jieyueRecord.set("returnuserid", jieyueRecord.get("readerid"));
            //更新借阅记录
            Db.update("t_jieyue", jieyueRecord);
            //修改续借状态
            Db.update("update t_jieyue set continuenum=0 where readerid = ? and bookdetailid=?", jieyueRecord.get("readerid"), bookRecord.getStr("id"));

            //更新图书详情
            Db.update("update t_book_detail set status = 0 where status=1 and id = ?", bookRecord.getStr("id"));
            resultRecord.set("rfid", bookRecord.get("rfid"));

            resultRecord.set("bookno", bookRecord.get("bookno"));

            resultRecord.set("library", library.get("library"));
            resultRecord.set("readerid", jieyueRecord.get("readerid"));
            resultRecord.set("amount", amount);
            resultRecord.set("reinfo", "还书成功");
            success(resultRecord);
        }catch(Exception e){
            fail(1,"数据异常");
            return;
        }
    }

}
