package com.service;


import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.model.BookPenalty;
import com.model.Jieyue;
import com.model.Reader;
import com.model.ReaderWxmsg;
import com.utils.CommonUtils;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 图书丢失
 * 2018-10-23
 * wush
 */
public class BookPenaltyService {

	public static final BookPenaltyService me = new BookPenaltyService();
	private BookPenalty dao = new BookPenalty().dao();
	private Jieyue jieyueDao = new Jieyue().dao();
	private Reader readerDao = new Reader().dao();

	public void saveBookPenalty(BookPenalty bookPenalty) {
		Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
//保存罚款记录
				bookPenalty.save();
				int detailStatus = 100;
				int jieyueStatus = 100;
				if (bookPenalty.getType() == 0) { //如果是丢书则需要修改其余状态
					detailStatus = 4;
					jieyueStatus = 2;
				} else if (bookPenalty.getType() == 1 || bookPenalty.getType() == 2) {
					detailStatus = 0;
					jieyueStatus = 1;
				}
				if (detailStatus != 100) {
					//修改详情表状态
					if(bookPenalty.getFlag() == 0) {
						Db.update("update t_book_detail set status = ? where id = ?", detailStatus, bookPenalty.getBookdetailid());
					} else {
						Db.update("update t_periodical_detail set status = ? where id = ?", detailStatus, bookPenalty.getBookdetailid());
					}
				}

				if (jieyueStatus != 100) {
					//修改借阅状态
					long currentTime = System.currentTimeMillis();
					Jieyue jieyue = jieyueDao.findById(bookPenalty.getJieyueid());
					jieyue.setContinuenum(0);
					jieyue.setReturnuserid(bookPenalty.getOperatorid());
					if(currentTime > jieyue.getDuetime().getTime()|| bookPenalty.getType() == 2) { //超期
						jieyue.setIsoverdue(1);
						Reader reader = readerDao.findById(bookPenalty.getReaderid());
						reader.setOverdue(1);
						reader.setOverduetime(new Date());
						reader.update();
					} else {
						jieyue.setIsoverdue(2);
					}
					jieyue.setReturntime(new Date());
					jieyue.setStatus(jieyueStatus);
					jieyue.update();
				}
				return true;
			}
		});

	}

	public List weijiaofakuan(int readerid) {
		return Db.find("select * from t_book_penalty where readerid = ? and penaltystatus = 0",readerid);
	}

	public BookPenalty findByid(int id) {
		return dao.findById(id);
	}

	public void saveBuhuan(BookPenalty bookPenalty, int chaoqistatus, int penaltystatus, BigDecimal penaltyamount){
		if(bookPenalty.getFlag() == 0) {
			Db.update("update t_book_detail set status = 0 where id = ?", bookPenalty.getBookdetailid());
		} else {
			Db.update("update t_periodical_detail set status = 0 where id = ?", bookPenalty.getBookdetailid());
		}

		if(bookPenalty.getPenaltystatus() == 0) { //查询出丢失记录 将丢失记录 支付状态修改为退还 如果是记账则为 记账退还
			bookPenalty.setPenaltystatus(3);
		} else if (bookPenalty.getPenaltystatus() == 1) {
			bookPenalty.setPenaltystatus(2);
		}
		bookPenalty.setStatus(2); //修改状态为找回
		bookPenalty.setRetrievetime(new Date());
		bookPenalty.update();

		if(chaoqistatus == 1) { //如果已超期
			bookPenalty.setId(null);
			bookPenalty.setPenaltystatus(penaltystatus); //支付方式 记账或者已交
			bookPenalty.setPenaltyamount(penaltyamount); //金额
			bookPenalty.setType(2);//超期
			bookPenalty.setStatus(null);
			bookPenalty.setRemarks("补交图书的超期罚款");
			bookPenalty.setRetrievetime(null);
			bookPenalty.save();
			if(penaltyamount.compareTo(BigDecimal.ZERO) > 0 && penaltystatus == 1) {
				ReaderWxmsg readerWxmsg = new ReaderWxmsg();
				readerWxmsg.setContent("您已补交图书的超期罚款"+penaltyamount.toString()+"元");
				readerWxmsg.setReaderid(bookPenalty.getReaderid());
				readerWxmsg.setRelevanceid(bookPenalty.getId());
				readerWxmsg.setMessagetype(3);
				readerWxmsg.setCreatetime(new Date());
				readerWxmsg.save();
			}

			Db.update("update t_jieyue set status=1,isoverdue=1,returntime=? where id = ?",new Date(), bookPenalty.getJieyueid());
			Reader reader = readerDao.findById(bookPenalty.getReaderid());
			reader.setOverdue(1);
			reader.setOverduetime(new Date());
			reader.update();
		} else {
			Db.update("update t_jieyue set status=1,isoverdue=2,returntime=? where id = ?",new Date(), bookPenalty.getJieyueid());
		}
	}

	public Page<Record> bookPenaltyList(int pageNumber,int pagesize, Integer orgid,String queryStr,String startTime,String endTime,String type,String penaltystatus){
		List list = new ArrayList();
		String select = " select * ";
		StringBuffer where = new StringBuffer(" from(select p.orgid,p.type,r.cardnumber,r.realname,od.deptname,d.barcode,b.title,b.price,DATE_FORMAT(j.createtime,'%Y-%m-%d') jieyuetime,p.createtime,p.penaltyamount,p.penaltystatus from t_book_penalty p ");
		where.append(" inner join t_reader r on p.readerid = r.id ");
		where.append(" LEFT join t_org_dept od on r.orgdeptid = od.id ");
		where.append(" LEFT join t_book_detail d on p.bookdetailid = d.id ");
		where.append(" LEFT join t_book b on d.bookid = b.id ");
		where.append(" LEFT join t_jieyue j on p.jieyueid = j.id ");
		where.append(" where p.flag=0 ");
		where.append(" union ");
		where.append(" select p.orgid,p.type,r.cardnumber,r.realname,od.deptname,d.barcode,b.kanming title,d.price,DATE_FORMAT(j.createtime,'%Y-%m-%d') jieyuetime,p.createtime,p.penaltyamount,p.penaltystatus from t_book_penalty p ");
		where.append(" inner join t_reader r on p.readerid = r.id ");
		where.append(" LEFT join t_org_dept od on r.orgdeptid = od.id ");
		where.append(" LEFT join t_periodical_detail d on p.bookdetailid = d.id ");
		where.append(" LEFT join t_periodical_zhengding b on d.periodicalid = b.id ");
		where.append(" LEFT join t_jieyue j on p.jieyueid = j.id ");
		where.append(" where p.flag=1 )t");
		where.append(" where orgid=? ");
		list.add(orgid);
		if(CommonUtils.isNotNullOrNotEmpty(queryStr) && !"".equals(queryStr)) {
			where.append(" and (realname like ? or cardnumber like ?) ");
			list.add("%"+queryStr+"%");
			list.add("%"+queryStr+"%");
		}
		if(CommonUtils.isNotNullOrNotEmpty(startTime) && !"".equals(startTime)) {
			where.append(" and DATE_FORMAT(createtime,'%Y-%m-%d') >= ? ");
			list.add(startTime);
		}
		if(CommonUtils.isNotNullOrNotEmpty(endTime) && !"".equals(endTime)) {
			where.append(" and DATE_FORMAT(createtime,'%Y-%m-%d') <= ? ");
			list.add(endTime);
		}
		if(CommonUtils.isNotNullOrNotEmpty(type) && !"".equals(type)) {
			where.append(" and type  = ? ");
			list.add(type);
		}
		if(CommonUtils.isNotNullOrNotEmpty(penaltystatus) && !"".equals(penaltystatus)) {
			where.append(" and penaltystatus  = ? ");
			list.add(penaltystatus);
		}
		where.append(" order by createtime desc ");
		return Db.paginate(pageNumber, pagesize,select,where.toString(), CommonUtils.listToArray(list));
	}

	public Record bookPenaltySumPrice(Integer orgid,String queryStr,String startTime,String endTime,String type,String penaltystatus){
		List list = new ArrayList();
		String select = " select SUM(penaltyamount) as sumpeice ";
		StringBuffer where = new StringBuffer(" from(select p.orgid,p.type,r.cardnumber,r.realname,od.deptname,d.barcode,b.title,b.price,DATE_FORMAT(j.createtime,'%Y-%m-%d') jieyuetime,p.createtime,p.penaltyamount,p.penaltystatus from t_book_penalty p ");
		where.append(" inner join t_reader r on p.readerid = r.id ");
		where.append(" LEFT join t_org_dept od on r.orgdeptid = od.id ");
		where.append(" LEFT join t_book_detail d on p.bookdetailid = d.id ");
		where.append(" LEFT join t_book b on d.bookid = b.id ");
		where.append(" LEFT join t_jieyue j on p.jieyueid = j.id ");
		where.append(" where p.flag=0 AND p.penaltystatus = 0");
		where.append(" union ");
		where.append(" select p.orgid,p.type,r.cardnumber,r.realname,od.deptname,d.barcode,b.kanming title,d.price,DATE_FORMAT(j.createtime,'%Y-%m-%d') jieyuetime,p.createtime,p.penaltyamount,p.penaltystatus from t_book_penalty p ");
		where.append(" inner join t_reader r on p.readerid = r.id ");
		where.append(" LEFT join t_org_dept od on r.orgdeptid = od.id ");
		where.append(" LEFT join t_periodical_detail d on p.bookdetailid = d.id ");
		where.append(" LEFT join t_periodical_zhengding b on d.periodicalid = b.id ");
		where.append(" LEFT join t_jieyue j on p.jieyueid = j.id ");
		where.append(" where p.flag=1 AND p.penaltystatus = 0)t");
		where.append(" where orgid=? ");
		list.add(orgid);
		if(CommonUtils.isNotNullOrNotEmpty(queryStr) && !"".equals(queryStr)) {
			where.append(" and (realname like ? or cardnumber like ?) ");
			list.add("%"+queryStr+"%");
			list.add("%"+queryStr+"%");
		}
		if(CommonUtils.isNotNullOrNotEmpty(startTime) && !"".equals(startTime)) {
			where.append(" and DATE_FORMAT(createtime,'%Y-%m-%d') >= ? ");
			list.add(startTime);
		}
		if(CommonUtils.isNotNullOrNotEmpty(endTime) && !"".equals(endTime)) {
			where.append(" and DATE_FORMAT(createtime,'%Y-%m-%d') <= ? ");
			list.add(endTime);
		}
		if(CommonUtils.isNotNullOrNotEmpty(type) && !"".equals(type)) {
			where.append(" and type  = ? ");
			list.add(type);
		}
		if(CommonUtils.isNotNullOrNotEmpty(penaltystatus) && !"".equals(penaltystatus)) {
			where.append(" and penaltystatus  = ? ");
			list.add(penaltystatus);
		}

		return Db.findFirst(select+where.toString(), CommonUtils.listToArray(list));
	}

	public List<Record> exportBookPenaltyList(Integer orgid,String queryStr,String startTime,String endTime,String type,String penaltystatus){
		List list = new ArrayList();
		String select = " select * ";
		StringBuffer where = new StringBuffer(" from(select p.orgid,p.type,r.cardnumber,r.realname,od.deptname,d.barcode,b.title,b.price,DATE_FORMAT(j.createtime,'%Y-%m-%d') jieyuetime,p.createtime,p.penaltyamount,p.penaltystatus from t_book_penalty p ");
		where.append(" inner join t_reader r on p.readerid = r.id ");
		where.append(" LEFT join t_org_dept od on r.orgdeptid = od.id ");
		where.append(" LEFT join t_book_detail d on p.bookdetailid = d.id ");
		where.append(" LEFT join t_book b on d.bookid = b.id ");
		where.append(" LEFT join t_jieyue j on p.jieyueid = j.id ");
		where.append(" where p.flag=0 ");
		where.append(" union ");
		where.append(" select p.orgid,p.type,r.cardnumber,r.realname,od.deptname,d.barcode,b.kanming title,d.price,DATE_FORMAT(j.createtime,'%Y-%m-%d') jieyuetime,p.createtime,p.penaltyamount,p.penaltystatus from t_book_penalty p ");
		where.append(" inner join t_reader r on p.readerid = r.id ");
		where.append(" LEFT join t_org_dept od on r.orgdeptid = od.id ");
		where.append(" LEFT join t_periodical_detail d on p.bookdetailid = d.id ");
		where.append(" LEFT join t_periodical_zhengding b on d.periodicalid = b.id ");
		where.append(" LEFT join t_jieyue j on p.jieyueid = j.id ");
		where.append(" where p.flag=1 )t");
		where.append(" where orgid=? ");
		list.add(orgid);
		if(CommonUtils.isNotNullOrNotEmpty(queryStr) && !"".equals(queryStr)) {
			where.append(" and (realname like ? or cardnumber like ?) ");
			list.add("%"+queryStr+"%");
			list.add("%"+queryStr+"%");
		}
		if(CommonUtils.isNotNullOrNotEmpty(startTime) && !"".equals(startTime)) {
			where.append(" and DATE_FORMAT(createtime,'%Y-%m-%d') >= ? ");
			list.add(startTime);
		}
		if(CommonUtils.isNotNullOrNotEmpty(endTime) && !"".equals(endTime)) {
			where.append(" and DATE_FORMAT(createtime,'%Y-%m-%d') <= ? ");
			list.add(endTime);
		}
		if(CommonUtils.isNotNullOrNotEmpty(type) && !"".equals(type)) {
			where.append(" and type  = ? ");
			list.add(type);
		}
		if(CommonUtils.isNotNullOrNotEmpty(penaltystatus) && !"".equals(penaltystatus)) {
			where.append(" and penaltystatus  = ? ");
			list.add(penaltystatus);
		}
		where.append(" order by createtime desc ");
		return Db.find(select+where.toString(), CommonUtils.listToArray(list));
	}

}
