package com.controller.api;


import com.config.BaseController;
import com.config.ControllerInterface;
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.Record;
import com.jfinal.upload.UploadFile;
import com.model.*;
import com.utils.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.security.PublicKey;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Clear
@ControllerInterface(path="/api/inventory")
public class InventoryController extends BaseController {

//    public void signin(){
//        Integer orgid = getParaToInt("orgid");
//        String secret = getHeader("secret");
//
//        try {
//            String key = AESUtil.Encrypt("121007", PropKit.get(orgid.toString()));
//            System.err.println(key);
//            String rsakey = RSAUtil.encrypt(key,PropKit.get("publickey"));
//            System.err.println(rsakey);
//
//            String dersakey = RSAUtil.decrypt(rsakey,PropKit.get("privatekey"));
//            System.err.println(dersakey);
//            String dekey = AESUtil.Decrypt(dersakey,PropKit.get(orgid.toString()));
//            System.err.println(dekey);
//            success();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public void getRFIDInfo(){
        Integer type = getParaToInt("type");
        if(CommonUtils.isNullOrEmpty(type)){
            fail(1,"类型不能为空,1:图书 2：层架标签");
            return;
        }
        String rfid = getPara("rfid");
        if(CommonUtils.isNullOrEmpty(rfid)){
            fail(1,"rfid不能为空");
            return;
        }
        Integer orgid = getParaToInt("orgid");
        if(type == 1){
            success(Db.findFirst("select b.title,b.bookno,b.publisher,d.barcode,d.rfid,d.bookshelfinfoStr from t_book_detail d left join t_book b on d.bookid = b.id where b.orgid = ? and d.rfid=?",orgid,rfid));
        } else if(type == 2) {
            success(Db.findFirst("select * from t_bookshelfinfo where orgid = ? and rfid = ?",orgid,rfid));
        } else {
            success();
        }
    }

    public void bindRFID(){
        Integer orgid = getParaToInt("orgid");
        Integer type = getParaToInt("type");
        if(CommonUtils.isNullOrEmpty(type)){
            fail(1,"类型不能为空1：绑定 2：取消绑定");
            return;
        }
        String bookshelfId = getPara("bookshelfId");
        if(CommonUtils.isNullOrEmpty(bookshelfId)){
            fail(1,"bookshelfId不能为空");
            return;
        }
        Record record = Db.findFirst("select * from t_bookshelfinfo where rfid=? and orgid=?",bookshelfId,orgid);
        if(CommonUtils.isNullOrEmpty(record)){
            fail(1,"查询不到层架标签信息");
            return;
        }
        String bookshelfinfoStr = record.getStr("location");
        String rfidstr = getPara("rfidstr");
        if(CommonUtils.isNullOrEmpty(rfidstr)){
            fail(1,"rfidstr不能为空");
            return;
        }
        String rfids[] = rfidstr.split(",");
        List errorList = new ArrayList();
        for(String rfid_book : rfids) {
            if("".equals(rfid_book)){
                continue;
            }
            Record bookRecord = Db.findFirst("select d.id,d.bookshelfinfoid,b.title,b.bookno from t_book_detail d left join t_book b on d.bookid = b.id where b.orgid=? and d.rfid=?",orgid,rfid_book);
            if(type == 1){
                Db.update("update t_book_detail set bookshelfinfoid=?,bookshelfinfoStr=? where id=?",record.getInt("id"),bookshelfinfoStr,bookRecord.getInt("id"));
            } else if(type == 2) {
                Db.update("update t_book_detail set bookshelfinfoid=null,bookshelfinfoStr=null where id=?",bookRecord.getInt("id"));
            }
        }
        success();
    }

    public void findBookListByBookshelfId(){
        Integer orgid = getParaToInt("orgid");
        String bookshelfId = getPara("bookshelfId");
        if(CommonUtils.isNullOrEmpty(bookshelfId)){
            fail(1,"bookshelfId不能为空");
            return;
        }
        Record record = Db.findFirst("select * from t_bookshelfinfo where rfid=? and orgid=?",bookshelfId,orgid);
        if(CommonUtils.isNullOrEmpty(record)){
            fail(1,"查询不到层架标签信息");
            return;
        }
        List list = Db.find("select b.title,b.bookno,b.publisher,d.barcode,d.rfid,d.bookshelfinfoStr from t_book_detail d left join t_book b on d.bookid = b.id where b.orgid = ? and d.bookshelfinfoid=?",orgid,record.getInt("id"));
        success(list);
    }

    public void updateBookshelf(){
        Integer orgid = getParaToInt("orgid");
        String oldBookshelfId = getPara("oldBookshelfId");
        if(CommonUtils.isNullOrEmpty(oldBookshelfId)){
            fail(1,"oldBookshelfId不能为空");
            return;
        }
        Record oldrecord = Db.findFirst("select * from t_bookshelfinfo where rfid=? and orgid=?",oldBookshelfId,orgid);
        if(CommonUtils.isNullOrEmpty(oldrecord)){
            fail(1,"查询不到层架标签信息");
            return;
        }

        String bookshelfId = getPara("bookshelfId");
        if(CommonUtils.isNullOrEmpty(bookshelfId)){
            fail(1,"bookshelfId不能为空");
            return;
        }
        Record record = Db.findFirst("select * from t_bookshelfinfo where rfid=? and orgid=?",bookshelfId,orgid);
        if(CommonUtils.isNullOrEmpty(record)){
            fail(1,"查询不到层架标签信息");
            return;
        }

        Db.update("update t_book_detail set bookshelfinfoid = ?,bookshelfinfoStr=? where id in (select * from (select id from t_book_detail where bookshelfinfoid = ?) t)",record.getInt("id"),record.getStr("location"),oldrecord.getInt("id"));
        success();
    }

    public void getLowerShelfPlanList(){
        Integer orgid = getParaToInt("orgid");
        List list = Db.find("select * from t_shelfplan where orgid = ? and status = 0",orgid);
        success(list);
    }

    public void getPlanToBookInfoList(){
        Integer orgid = getParaToInt("orgid");
        Integer planid = getParaToInt("planid");
        if(CommonUtils.isNullOrEmpty(planid)){
            fail(1,"下架计划id不能为空");
            return;
        }
        Record record = Db.findFirst("select * from t_shelfplan where id=? and orgid=?",planid,orgid);
        if(CommonUtils.isNullOrEmpty(record)){
            fail(1,"查询不到下架计划信息");
            return;
        }

        List list = Db.find("select b.title,b.bookno,b.publisher,d.barcode,d.rfid,d.bookshelfinfoStr from t_book_detail d left join t_book b on d.bookid = b.id left join t_book_shelfplan s on d.id = s.bookdetailid where b.orgid = ? and s.shelfplanid = ? ",orgid,planid);
        success(list);
    }

    public void bookLowerShelf(){
        Integer orgid = getParaToInt("orgid");
        String rfidstr = getPara("rfidstr");
        String planid = getPara("planid");
        if(CommonUtils.isNullOrEmpty(planid)){
            fail(1,"下架计划id不能为空");
            return;
        }
        if(CommonUtils.isNullOrEmpty(rfidstr)){
            fail(1,"rfidstr不能为空");
            return;
        }
        String rfids[] = rfidstr.split(",");
        for(String rfid : rfids) {
            if("".equals(rfid)){
                continue;
            }
            Record bookdetailRecord = Db.findFirst("select d.id from t_book_detail d left join t_book b on d.bookid = b.id where rfid = ? and orgid = ?",rfid,orgid);
            Db.update("update t_book_detail set bookstatus = 0 where id =?",bookdetailRecord.getInt("id"));
            Db.update("update t_book_shelfplan set status =1 where shelfplanid = ? and bookdetailid=?",planid,bookdetailRecord.getInt("id"));
            List list = Db.find("select * from t_book_shelfplan where status != 1 and shelfplanid = ?",planid);
            if(list.size() == 0){
                Db.update("update t_shelfplan set status = 1 where id=? and orgid = ?",planid,orgid);
            }
        }
        success();
    }

    @Clear
    public void uploadBookInfo(){
        Integer orgid = getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(0,"orgid不能为空");
            return;
        }
        String filename = getPara("filename");
        if(CommonUtils.isNullOrEmpty(filename)){
            fail(0,"文件名称不能为空");
            return;
        }
        List<Map<String,String>> errorList = new ArrayList();
        Map checkMap = null;
        Calendar calendar = Calendar.getInstance();
        Record defaultLibraryRecord = Db.findFirst("select id from t_library where orgid = ? order by defaultlibrary desc ",orgid);
        if(CommonUtils.isNullOrEmpty(defaultLibraryRecord)){
            Library library = new Library();
            library.setOrgid(orgid);
            library.setLibrary("书库");
            library.setDefaultlibrary(1);
            library.setCreatetime(calendar.getTime());
            library.setIsopen(1);
            library.setArea(BigDecimal.TEN);
            library.save();
            defaultLibraryRecord = library.toRecord();
        }
        Record piciRecord = Db.findFirst("select id from t_bookpici where orgid = ? order by id desc",orgid);
        if(CommonUtils.isNullOrEmpty(piciRecord)){
            Bookpici bookpici = new Bookpici();
            bookpici.setOrgid(orgid);
            bookpici.setDictid(52);
            bookpici.setBatchname("默认批次");
            bookpici.setCreatetime(calendar.getTime());
            bookpici.setOperatorid(1);
            bookpici.save();
            piciRecord = bookpici.toRecord();
        }
        String path =getRequest().getRealPath("upload")+"/"+filename;
        List<Map<String,String>> bookList= null;
        try {
            bookList = ExcelUtil.readExcel(new FileInputStream(new File(path)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if(bookList.size() == 0){
            fail(0,"文件路径错误或读取不到数据");
            return;
        }
        for(Map<String,String> map : bookList) {
            try {
                checkMap = map;
                Book book = new Book();
                book.setOrgid(orgid);
                String typecode = map.get("book_vcfl");
                book.setTypeid(typecode.substring(0,1));
                book.setTypecode(typecode);

                int shucihao = 0;
                Record shucihaoRecord = Db.findFirst("select shucihao from t_book where orgid = ? and typecode = ? order by shucihao desc",orgid,typecode);
                if(CommonUtils.isNotNullOrNotEmpty(shucihaoRecord)){
                    shucihao = shucihaoRecord.getInt("shucihao");
                }
                book.setShucihao(shucihao);
                String bookno = typecode+"/"+shucihao;
//                int booknum = Integer.parseInt(map.get("册数"));
                book.setBooknum(1);
                book.setIsbn(map.get("book_vcisbn"));
                book.setTitle(map.get("book_vcmc"));
                book.setPublisher(map.get("book_vccbs"));
                book.setAuthor(map.get("book_vczz"));
                book.setPublishdate(map.get("book_dcbrq"));
                book.setBookno(bookno);
//                book.setPublishaddress(map.get("出版地"));
                if(CommonUtils.isNullOrEmpty(map.get("book_fdj"))){
                    book.setPrice(new BigDecimal(map.get("book_fdj")));
                }
                book.setCreatetime(calendar.getTime());
                book.setOperatorid(1);
                Record checkBookRecord = Db.findFirst("select id from t_book where orgid = ? and isbn=? and title = ? and publisher = ? and author = ? and bookno = ?", book.getOrgid(), book.getIsbn(), book.getTitle(), book.getPublisher(), book.getAuthor(), book.getBookno());
                if (CommonUtils.isNullOrEmpty(checkBookRecord)) {
//                    book.setBooknum(booknum);
                    book.save();
                    BookPlus bookPlus = new BookPlus();
                    bookPlus.setBookid(book.getId());
//                    bookPlus.setSubtitle(map.get("副题名"));
//                    try{
//                        bookPlus.setTotalpages(Integer.parseInt(map.get("页数").replace("页", "").replace("*", "")));
//                    }catch (Exception e) {
//
//                    }
//                    bookPlus.setCongshuming(map.get("丛编名"));
                    bookPlus.save();

                    String barcode = map.get("book_vcid");
                    String zerostr = "0000000000000000000000000000";
                    barcode = zerostr.substring(0,6-barcode.length())+barcode;
                    BookDetail bookDetail = new BookDetail();
                    bookDetail.setBookid(book.getId());
                    bookDetail.setLibraryid(defaultLibraryRecord.getInt("id"));
                    bookDetail.setPiciid(piciRecord.getInt("id"));
                    bookDetail.setBarcode(barcode);
                    bookDetail.setStatus(0);
                    bookDetail.setBookstatus(1);
                    bookDetail.setShangjiatime(calendar.getTime());
                    bookDetail.setPutindate(calendar.getTime());
                    bookDetail.setCreatetime(calendar.getTime());
                    bookDetail.setOperatorid(1);
                    bookDetail.save();
                } else {
                    Db.update("update t_book set booknum = booknum + 1 where id = ?",checkBookRecord.getInt("id"));
                    String barcode = map.get("book_vcid");
                    String zerostr = "0000000000000000000000000000";
                    barcode = zerostr.substring(0,6-barcode.length())+barcode;
                    BookDetail bookDetail = new BookDetail();
                    bookDetail.setBookid(book.getId());
                    bookDetail.setLibraryid(defaultLibraryRecord.getInt("id"));
                    bookDetail.setPiciid(piciRecord.getInt("id"));
                    bookDetail.setBarcode(barcode);
                    bookDetail.setStatus(0);
                    bookDetail.setBookstatus(1);
                    bookDetail.setShangjiatime(calendar.getTime());
                    bookDetail.setPutindate(calendar.getTime());
                    bookDetail.setCreatetime(calendar.getTime());
                    bookDetail.setOperatorid(1);
                    bookDetail.save();
                }
                Thread.sleep(50);
//                System.err.println("导入完成数据：" + map.toString());
//                logger.info("导入完成数据：" + map.toString());
            }catch (Exception e) {
                errorList.add(checkMap);
                e.printStackTrace();
            }
        }
        logger.info("图书未导入数量："+ errorList.size());
//        String exfilename="";
//        if (errorList.size()>0){
//            exfilename="/图书未导入列表"+ DateUtils.getNowTimeNo()+".xls";
//            File targetFile =new File(getRequest().getRealPath("upload")+exfilename);
//            ExcelUtil.writeExcel(targetFile,errorList,"图书未导入列表");
//        }
        success(errorList);
    }

    public void dateformat(){
        Integer orgid = getParaToInt("orgid",0);
        if(orgid == 0) {
            fail(0,"orgid不能为空");
            return;
        }
        Calendar calendar = Calendar.getInstance();
        Record defaultLibraryRecord = Db.findFirst("select id from t_library where orgid = ? order by defaultlibrary desc ",orgid);
        if(CommonUtils.isNullOrEmpty(defaultLibraryRecord)){
            Library library = new Library();
            library.setOrgid(orgid);
            library.setLibrary("图书馆");
            library.setDefaultlibrary(1);
            library.setCreatetime(calendar.getTime());
            library.setIsopen(1);
            library.setArea(BigDecimal.TEN);
            library.save();
            defaultLibraryRecord = library.toRecord();
        }
        Record piciRecord = Db.findFirst("select id from t_bookpici where orgid = ? order by id desc",orgid);
        if(CommonUtils.isNullOrEmpty(piciRecord)){
            Bookpici bookpici = new Bookpici();
            bookpici.setOrgid(orgid);
            bookpici.setDictid(52);
            bookpici.setBatchname("默认批次");
            bookpici.setCreatetime(calendar.getTime());
            bookpici.setOperatorid(1);
            bookpici.save();
            piciRecord = bookpici.toRecord();
        }
        List<Record> cengjiabiaoqianList = CommonUtils.getDbPro("sqlserver4").find("select top 100 * from sm");
        for (Record record : cengjiabiaoqianList) {
            Book book = new Book();
            book.setOrgid(orgid);
            book.setShucihao(1);
            book.setTypeid(record.getStr("flh"));
            book.setTypecode(record.getStr(""));
            List<Record> bookdetailList = Db.find("select * from scxx where kzh=?",record.getInt("kzh"));
            book.setBooknum(bookdetailList.size());
            book.setIsbn(record.getStr("isbn"));
            book.setTitle(record.getStr("sm"));
            book.setPublisher(record.getStr("cbs"));
            book.setKeyword(record.getStr("ztc"));
            book.setEdition(record.getStr("bc"));
            book.setAuthor(record.getStr("zzmc"));
            book.setPublishdate(record.getStr("cbn"));
//            book.setBookno(map.get("索书号"));
            book.setPublishaddress(record.getStr("cbd"));
            book.setPrice(record.getBigDecimal("jg"));
            book.setCreatetime(record.getDate("bmrq"));
            book.setOperatorid(1);
            book.save();
            BookPlus bookPlus = new BookPlus();
            bookPlus.setBookid(book.getId());
            bookPlus.setFuzhu(record.getStr("fz"));
            bookPlus.setTotalpages(record.getInt("ym"));
            bookPlus.setCongshuming(record.getStr("csm"));
            bookPlus.setCongshuauthor(record.getStr("cszz"));
            bookPlus.save();
            for (Record detailRecord : bookdetailList){
                BookDetail bookDetail = new BookDetail();
                bookDetail.setBookid(book.getId());
                bookDetail.setLibraryid(defaultLibraryRecord.getInt("id"));
                bookDetail.setPiciid(piciRecord.getInt("id"));
                bookDetail.setBarcode(detailRecord.getStr("tmh"));
                bookDetail.setStatus(0);
                bookDetail.setBookstatus(1);
                bookDetail.setShangjiatime(detailRecord.getDate("rkrq"));
                bookDetail.setPutindate(record.getDate("bmrq"));
                bookDetail.setCreatetime(record.getDate("bmrq"));
                bookDetail.setOperatorid(1);
                bookDetail.save();
            }
        }
        success();
    }
}
