package com.controller.school;


import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Clear;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.model.*;
import com.service.*;
import com.tools.ISBNTools;
import com.utils.CommonUtils;
import com.utils.ExcelUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 该类用于平时同步单独的学校提供的各种数据到系统里面
 * 学校数据转换
 */
@ControllerInterface(path="/synschoolinfo")
public class SynchronizationSchoolInfoController extends BaseController {

    OrgDeptService orgDeptService = OrgDeptService.me;
    ReaderAuthService readerAuthService= ReaderAuthService.me;
    BookService bookService = BookService.me;
    BookPiciService bookpiciService = BookPiciService.me;
    LibraryService libraryService = LibraryService.me;
    SysConfigService sysConfigService = SysConfigService.me;

    @Clear
    public void updateFile(){
        int orgid = 121236;
        File root = new File("d://121236");
        File[] files = root.listFiles();
        for(File file:files){
            String filenamestr = file.getName();
            System.err.println(filenamestr.indexOf("."));
            String filename = filenamestr.substring(0,filenamestr.indexOf("."));
            String str[] = filename.split("_");
            if(str.length!=3){
                System.err.println("文件名称错误");
                continue;
            }
            String newfilename = str[2]+"_"+str[1]+filenamestr.substring(filenamestr.indexOf("."));
            File newfile=new File(file.getParent()+File.separator+newfilename);
            if(file.renameTo(newfile)) {
                System.out.println("重命名成功！");
            }else {
                System.out.println("重命名失败！新文件名已存在");
            }

            Record record = Db.findFirst("select * from t_org_dept where orgid = ? and deptname = ?",orgid,str[1]);
            if(CommonUtils.isNullOrEmpty(record)){
                Record newRecord = new Record();
                newRecord.set("deptname",str[1]);
                newRecord.set("orgid",orgid);
                newRecord.set("readerauthid",0); //机构暂无默认权限
                newRecord.set("createtime",new Date());
                newRecord.set("operatorid",0);
                Db.save("t_org_dept", newRecord);
                System.err.println("创建班级成功 班级名称："+str[1]);
            }
        }
        success();
    }

    /**
     * 湖南省株洲县第五中学数据同步 读者信息同步
     */
    @Clear
    public void zhuzhoudiwu_readerinfo(){
        Integer orgid = getParaToInt("orgid",0);
        if(orgid == 0){
            fail(0,"orgid不能为空");
            return;
        }
        String filename = getPara("filename");
        if(CommonUtils.isNullOrEmpty(filename)){
            fail(0,"filename不能为空");
            return;
        }
//        List<OrgDept> orgDeptList=orgDeptService.findOrgDept(orgid);
        Map<String,Integer> readerAuthMap=readerAuthService.findReaderAuthByName(orgid);

        try {
            logger.info("开始同步 湖南省株洲县第五中学 读者信息 ");
            // 读取文件的输入流
            InputStream fis = new FileInputStream(getRequest().getServletContext().getRealPath("upload")+"/"+filename);
//            InputStream fis = new FileInputStream("d://" + filename);
            List<Map<String,String>> list = ExcelUtil.readExcel(fis);

            for(Map<String,String> map : list){
                try{
                    long starttime = Calendar.getInstance().getTimeInMillis();
                    Reader reader = new Reader();
                    reader.setOrgid(orgid);
                    Record deptRecord = Db.findFirst("select id from t_org_dept where orgid = ? and deptname = ?",orgid,map.get("班级").trim());
                    if (CommonUtils.isNullOrEmpty(deptRecord)){
                        OrgDept orgDept = new OrgDept();
                        orgDept.setDeptname(map.get("班级").trim()).setOrgid(orgid).save();
                        reader.setOrgdeptid(orgDept.getId());
                    } else {
                        reader.setOrgdeptid(deptRecord.getInt("id"));
                    }
                    String cardnumber = map.get("编码").trim().replace("*","");
                    reader.setCardnumber(cardnumber);
                    reader.setRealname(map.get("姓名").trim());
                    reader.setPassword("123456");
                    reader.setReadcardcode(cardnumber);
                    reader.setSex(map.get("性别").trim());
                    reader.setReaderauthid(readerAuthMap.get(map.get("读者类型").trim()));
                    if(reader.getReaderauthid() ==null){
                        logger.info(orgid+" 权限名称："+map.get("读者类型").trim()+" 未导入原因:借阅权限不正确!");
                        continue;
                    }
                    reader.setOverdue(0);
                    reader.setMemo(cardnumber);
                    if(map.get("读者类型").trim().equals("教师")){
                        reader.setReaderauthid(625);
                    } else {
                        reader.setReaderauthid(626);
                    }
                    reader.setReadertypeid(62);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(simpleDateFormat.parse(map.get("办证日期")));
                    reader.setCreatetime(calendar.getTime());
                    calendar.add(Calendar.YEAR,3);
                    reader.setLosedate(calendar.getTime());
                    if(map.get("读者类型").trim().equals("教师")){
                        calendar.add(Calendar.YEAR,30);
                        reader.setLosedate(calendar.getTime());
                    }
                    if(map.get("状态").trim().equals("正常")){
                        reader.setStatus(1);
                    } else {
                        reader.setStatus(2);
                    }
                    reader.setMemo(map.toString());
                    reader.save();

                    long endtime = Calendar.getInstance().getTimeInMillis();
                    long times = endtime- starttime;
                    logger.info("同步读者数据中 该条数据总耗时："+times);
                }catch (Exception e){
                    logger.info("读者转化异常 orgid:"+ orgid +" 读者证号："+map.get("编码"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        success();
    }

    /**
     * 湖南省株洲县第五中学数据同步 书籍信息同步
     */
    @Clear
    public void zhuzhoudiwu_bookinfo(){
        logger.info("开始同步 湖南省株洲县第五中学 书籍信息 ");
        Integer orgid = getParaToInt("orgid",0);
        if(orgid == 0){
            fail(0,"orgid不能为空");
            return;
        }
        Record orgRecord = Db.findById("t_org",orgid);
        if(CommonUtils.isNullOrEmpty(orgRecord)){
            fail(0,"查询不到机构信息");
            return;
        }
        String filename = getPara("filename");
        if(CommonUtils.isNullOrEmpty(filename)){
            fail(0,"filename不能为空");
            return;
        }

        OrgSetting orgSetting = sysConfigService.findOrgSetting(orgid);
        if(null == orgSetting) {
            fail(1,"数据异常!");
            return;
        }
        Record userRecord = Db.findFirst("select * from t_user where isadmin = 1 and orgid = ?",orgid);
        int operatorid = userRecord.getInt("id");
        try {
            InputStream fis = new FileInputStream(getRequest().getServletContext().getRealPath("upload")+"/"+filename);
            long starttime = Calendar.getInstance().getTimeInMillis();
            List<Map<String,String>> bookList= ExcelUtil.readExcel(fis);
            long endtime = Calendar.getInstance().getTimeInMillis();
            long times = endtime- starttime;
            logger.info("读取文件总耗时："+times);
            logger.info("书籍总数量："+bookList.size());

            Thread.sleep(5000);
            for (Map<String,String> bookMap : bookList) {
                try{
                    StringBuffer bookno = new StringBuffer();
                    Book book=new Book();
                    book.setOrgid(orgid);
                    String typecode= bookMap.get("分类号");
                    if(CommonUtils.isNullOrEmpty(typecode)){
                        typecode = "0";
                    }
                    book.setBooknum(0);
                    book.setOperatorid(operatorid);
                    book.setTypecode(typecode);
                    bookno.append(typecode);
                    book.setTypeid(typecode);//22大类ID
                    //book.setTypecommonid()  //通俗分类id
                    book.setShucihao(1);
                    bookno.append("/").append(CommonUtils.isNotNullOrNotEmpty(bookMap.get("书次号"))?bookMap.get("书次号"):"0");
                    if(CommonUtils.isNotNullOrNotEmpty(bookMap.get("原始条形码"))){
                        book.setIsbn(ISBNTools.fmtisbn(bookMap.get("原始条形码")));
                    }
                    book.setTitle(bookMap.get("书籍名称"));
                    book.setPublisher(bookMap.get("出版社名"));
                    book.setEdition(bookMap.get("书籍版次"));
                    book.setAuthor(bookMap.get("作者信息"));
                    book.setPublishdate(bookMap.get("出版日期"));
                    book.setPublishaddress(bookMap.get("出版地点"));
                    book.setMemo(bookMap.get("内容简介"));
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                    if(CommonUtils.isNotNullOrNotEmpty(bookMap.get("入库时间"))){
                        book.setCreatetime(simpleDateFormat.parse(bookMap.get("入库时间")));
                    } else {
                        book.setCreatetime(new Date());
                    }
                    book.setOperatorid(operatorid);

                    if(CommonUtils.isNullOrEmpty(bookMap.get("书籍价格"))){
                        try{
                            book.setPrice(new BigDecimal(bookMap.get("书籍价格")));
                        }catch (Exception e) {
                            logger.info("书籍价格异常"+bookMap.get("书籍价格"));
                        }
                    }
//                    book.setOperatorid(operatorid);
                    BookPlus bookPlus = new BookPlus();
                    if(CommonUtils.isNotNullOrNotEmpty(bookMap.get("书籍页码"))) {
                        try{
                            bookPlus.setTotalpages(Integer.parseInt(bookMap.get("书籍页码")));
                        }catch (Exception e) {
                            logger.info("页数格式异常");
                        }
                    }
                    int bindingid = 0;
                    if(CommonUtils.isNotNullOrNotEmpty(bookMap.get("装订形式"))){
                        if(bookMap.get("装订形式").equals("平装")){
                            bindingid = 45;
                        } else if(bookMap.get("装订形式").equals("精装")){
                            bindingid = 46;
                        } else if(bookMap.get("装订形式").equals("套装")){
                            bindingid = 47;
                        }
                    }
                    if (bindingid != 0){
                        bookPlus.setBindingid(bindingid);
                    }

                    book.setBookno(bookno.toString().toUpperCase());
                    BookDetail bookDetail = new BookDetail();

                    bookDetail.setLibraryid(1702);
                    bookDetail.setPiciid(258);

                    if(CommonUtils.isNotNullOrNotEmpty(bookMap.get("入库时间"))){
                        bookDetail.setShangjiatime(simpleDateFormat.parse(bookMap.get("入库时间")));
                    }

                    String barcode = bookMap.get("书籍条形码");
                    int count = bookService.findByBarcode(orgid,barcode);
                    if (count > 0) {
                        barcode = "CF_"+barcode;
                    }
                    int check = 0;
                    Book checkBook = bookService.findBookByBooknoTitle(book.getOrgid(),book.getBookno(),book.getTitle(),book.getIsbn(),book.getPublisher(),book.getAuthor());
                    if(CommonUtils.isNotNullOrNotEmpty(checkBook)){
                        book = checkBook;
                        check = 1;
                    }
                    bookDetail.setBarcode(barcode);
                    bookDetail.setBookstatus(1);
                    if(CommonUtils.isNotNullOrNotEmpty(bookMap.get("在馆状态")) && "在馆".equals(bookMap.get("在馆状态"))){
                        bookDetail.setStatus(0);
                    } else {
                        bookDetail.setStatus(1);
                    }
                    bookDetail.setCreatetime(new Date());
                    bookDetail.setOperatorid(operatorid);
                    if(0 == check) {
                        book.save();
                        bookPlus.setBookid(book.getId());
                        bookPlus.save();
                    } else {
                        book.update();
                    }
                    bookDetail.setBookid(book.getId());
                    bookDetail.save();
                    Db.update("update t_book set booknum = booknum +1 where id = ?",book.getId());
                }catch (Exception e){
                    e.printStackTrace();
                    logger.info("导入失败");
                }
            }
            success();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Clear
    public void updateprice_zhuzhoudiwu(){
        logger.info("开始同步 湖南省株洲县第五中学 书籍信息 ");
        String filename = getPara("filename");
        if(CommonUtils.isNullOrEmpty(filename)){
            fail(0,"filename不能为空");
            return;
        }

        try {
            System.err.println(getRequest().getServletContext().getRealPath("upload"));
            InputStream fis = new FileInputStream(getRequest().getServletContext().getRealPath("upload")+"/"+filename);
            long starttime = Calendar.getInstance().getTimeInMillis();
            List<Map<String,String>> bookList= ExcelUtil.readExcel(fis);
            long endtime = Calendar.getInstance().getTimeInMillis();
            long times = endtime- starttime;
            logger.info("读取文件总耗时："+times);
            logger.info("书籍总数量："+bookList.size());

            for (Map<String,String> bookMap : bookList) {
                try{
                    logger.info(bookMap.toString());
                    StringBuffer bookno = new StringBuffer();
                    Book book=new Book();
                    String typecode= bookMap.get("分类号");
                    if(CommonUtils.isNullOrEmpty(typecode)){
                        typecode = "0";
                    }
                    book.setBooknum(0);
                    book.setTypecode(typecode);
                    bookno.append(typecode);
                    book.setTypeid(typecode);//22大类ID
                    book.setShucihao(1);
                    bookno.append("/").append(CommonUtils.isNotNullOrNotEmpty(bookMap.get("书次号"))?bookMap.get("书次号"):"0");
                    if(CommonUtils.isNotNullOrNotEmpty(bookMap.get("原始条形码"))){
                        book.setIsbn(ISBNTools.fmtisbn(bookMap.get("原始条形码")));
                    }
                    book.setTitle(bookMap.get("书籍名称"));
                    book.setPublisher(bookMap.get("出版社名"));
                    book.setEdition(bookMap.get("书籍版次"));
                    book.setAuthor(bookMap.get("作者信息"));
                    book.setPublishdate(bookMap.get("出版日期"));
                    book.setPublishaddress(bookMap.get("出版地点"));
                    book.setMemo(bookMap.get("内容简介"));
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                    if(CommonUtils.isNotNullOrNotEmpty(bookMap.get("入库时间"))){
                        book.setCreatetime(simpleDateFormat.parse(bookMap.get("入库时间")));
                    } else {
                        book.setCreatetime(new Date());
                    }

                    if(CommonUtils.isNotNullOrNotEmpty(bookMap.get("书籍价格"))){
                        try{
                            book.setPrice(new BigDecimal(bookMap.get("书籍价格")));
                        }catch (Exception e) {
                            logger.info("书籍价格异常"+bookMap.get("书籍价格"));
                        }
                    }
                    Record record = Db.findFirst("select * from t_book where orgid = 121258 and price is null and isbn = ? and publisher = ? and author = ? and publishdate = ?",CommonUtils.isNotNullOrNotEmpty(book.getIsbn())?book.getIsbn():null,CommonUtils.isNotNullOrNotEmpty(book.getPublisher())?book.getPublisher():"",CommonUtils.isNotNullOrNotEmpty(book.getAuthor())?book.getAuthor():"",CommonUtils.isNotNullOrNotEmpty(book.getPublishdate())?book.getPublishdate():"");
                    if(CommonUtils.isNullOrEmpty(record)) {
                        record = Db.findFirst("select * from t_book where orgid = 121258 and price is null and (title = ? or title = ?) and publisher = ? and author = ? and publishdate = ?",CommonUtils.isNotNullOrNotEmpty(book.getTitle())?book.getTitle():null,"",CommonUtils.isNotNullOrNotEmpty(book.getPublisher())?book.getPublisher():"",CommonUtils.isNotNullOrNotEmpty(book.getAuthor())?book.getAuthor():"",CommonUtils.isNotNullOrNotEmpty(book.getPublishdate())?book.getPublishdate():"");
                    }
                    if(CommonUtils.isNotNullOrNotEmpty(record)){
                        Db.update("update t_book set price = ? where orgid = 121258 and id = ?",book.getPrice(),record.getInt("id"));
                        logger.info("修改成功"+record.getInt("id"));
                    } else {
                        logger.info("查询不到数据 break");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    logger.info("导入失败");
                }
            }
            success();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 湖南省株洲县第五中学数据同步 流通记录同步
     */
    @Clear
    public void zhuzhoudiwu_liutonginfo() {
        Integer orgid = getParaToInt("orgid", 0);
        if (orgid == 0) {
            fail(0, "orgid不能为空");
            return;
        }
        Record orgRecord = Db.findById("t_org", orgid);
        if (CommonUtils.isNullOrEmpty(orgRecord)) {
            fail(0, "查询不到机构信息");
            return;
        }
        String filename = getPara("filename");
        if (CommonUtils.isNullOrEmpty(filename)) {
            fail(0, "filename不能为空");
            return;
        }
        Record userRecord = Db.findFirst("select * from t_user where isadmin = 1 and orgid = ?", orgid);
        int operatorid = userRecord.getInt("id");
        InputStream fis = null;
        try {
//            fis = new FileInputStream("d://" + filename);
            fis = new FileInputStream(getRequest().getServletContext().getRealPath("upload")+"/"+filename);
            logger.info("开始同步 湖南省株洲县第五中学 书籍信息 ");

            long starttime = Calendar.getInstance().getTimeInMillis();
            List<Map<String,String>> list= ExcelUtil.readExcel(fis);
            long endtime = Calendar.getInstance().getTimeInMillis();
            long times = endtime- starttime;
            logger.info("读取文件总耗时："+times);
            logger.info("书籍总数量："+list.size());
            Thread.sleep(5000);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (Map<String, String> map : list) {
                try{
                    String cardnumber = map.get("读者编码").trim().replace("*","");
                    String realname = map.get("读者姓名").trim().replace("*","");
                    Record readerRecord = Db.findFirst("select id from t_reader where orgid = ? and realname = ? and cardnumber = ?",orgid,realname,cardnumber);
                    int readerid = 1011;
                    if(CommonUtils.isNotNullOrNotEmpty(readerRecord)){
                        readerid = readerRecord.getInt("id");
                    }

                    String barcode = map.get("图书编码").trim();
                    String bookname = map.get("图书名称").trim();
                    String price = map.get("图书价格").trim();
                    Record bookDetailRecord = Db.findFirst("select d.id from t_book_detail d left join t_book b on d.bookid = b.id where b.orgid = ? and d.barcode = ? and b.title = ?",orgid,barcode,bookname);
                    int bookdetailid = 1011;
                    if(CommonUtils.isNotNullOrNotEmpty(bookDetailRecord)){
                        bookdetailid = bookDetailRecord.getInt("id");
                    }
//                    Record bookRecord = Db.findFirst("select id from t_book b where b.orgid = ? b.bookname = ? and price = ?",orgid,bookname,price);
//                    int bookid = 1011;
//                    if(CommonUtils.isNotNullOrNotEmpty(bookRecord)){
//                        bookid = bookRecord.getInt("id");
//                    }
//                    Calendar calendar = Calendar.getInstance();
                    Jieyue jieyue = new Jieyue();
                    jieyue.setReaderid(readerid);
                    jieyue.setOrgid(orgid);
                    jieyue.setBookdetailid(bookdetailid);
                    jieyue.setFlag(0);
                    String sql = "update t_book_detail set jieyuenums = ifnull(jieyuenums,0)+1";
                    if(CommonUtils.isNullOrEmpty(map.get("归还时间").trim())){
                        jieyue.setStatus(0); //状态：0：借阅中，1：已归还 2:已丢失
                        sql = sql + ",status = 1";
                    } else {
                        jieyue.setStatus(1); //状态：0：借阅中，1：已归还 2:已丢失
                        jieyue.setReturntime(simpleDateFormat.parse(map.get("归还时间").trim()));
                    }
                    sql = sql + "  where id = ?";
                    jieyue.setContinuenum(0);
                    Date jieyueDate = simpleDateFormat.parse(map.get("借阅时间").trim());
                    jieyue.setCreatetime(jieyueDate);
                    Date duetime = simpleDateFormat.parse(map.get("应归还时间").trim());
                    try {
                        jieyue.setDuetime(sdf2.parse(sdf.format(duetime) + " 23:59:59"));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    jieyue.setOperatorid(operatorid);
                    Db.update(sql,bookdetailid);
                    jieyue.save();
                }catch (Exception e){
                    e.printStackTrace();
                    logger.info("导入失败");
                }

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