package com.service;


import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.model.Cardtype;
import com.model.User;

import java.sql.SQLException;
import java.util.Date;

/**
 * 读者卡类型
 * 2018-10-22
 * zj
 */
public class CardTypeService {
	

	public static final CardTypeService me = new CardTypeService();
	private Cardtype dao = new Cardtype().dao();
	private User userDao = new User().dao();

	public Cardtype findById(int id){
		return dao.findById(id);
	}
	public Page<Cardtype> paginate(int pageNumber,int pagesize, Cardtype bean){
		String select = "SELECT a.*,b.orgname ";
		StringBuilder where = new StringBuilder(" from t_cardtype a LEFT JOIN t_org b ON a.orgid = b.id");
		return dao.paginate(pageNumber, pagesize,select,where.toString());
	}

	public void deleteById(int id) {
		dao.deleteById(id);
	}

	public void addOrUpdate(Cardtype bean, int operatorid){
		Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				if(bean.getId()== null){
					User userorgid = userDao.findFirst("SELECT orgid from t_user WHERE id = ? ",operatorid);
					int orgid = userorgid.getInt("orgid");
					bean.setOrgid(orgid).setCreatetime(new Date()).setOperatorid(operatorid).save();
				}else{
					Cardtype old = dao.findById(bean.getId());
					bean.setCreatetime(old.getCreatetime()).setOperatorid(old.getOperatorid()).setUpdatetime(new Date()).setUpdateuserid(operatorid).update();
				}
				return true;
			}
		});
	}

	public void still(int id,int operatorid,int bookdetailid){
		Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				Db.update("UPDATE t_jieyue set `status` = 1,returntime = ?,returnuserid = ? WHERE id = ? ",new Date(),operatorid,id);
				//更改馆藏明细书本状态
				Db.update("UPDATE t_book_detail SET `status`=0,updatetime=?,updateuserid=? WHERE id =? ",new Date(),operatorid,bookdetailid);
				return true;
			}
		});
	}

}
