package com.service;


import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.model.ReaderAuth;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReaderAuthService {
	

	public static final ReaderAuthService me = new ReaderAuthService();

	private ReaderAuth dao = new ReaderAuth().dao();

	public ReaderAuth findById(int id){
		return dao.findById(id);
	}
	public List<ReaderAuth> list(int orgid){
		String select = "select * from t_reader_auth where orgid=?";
		return dao.find(select,orgid);
	}

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

	public void addOrUpdate(ReaderAuth bean, int operatorid) throws Exception {
		if(bean.getId()== null){
			List<ReaderAuth> readerAuthList= dao.find("SELECT id, name FROM t_reader_auth where   orgid=? and name=?",bean.getOrgid(),bean.getName());
			if (!readerAuthList.isEmpty()){
				throw  new Exception("借阅权限名称已经存在，请更换其他名称");
			}
		}

		Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				if(bean.getId()== null){
					bean.setCreatetime(new Date()).setOperatorid(operatorid).save();
				}else{
					bean.setUpdatetime(new Date()).setUpdateuserid(operatorid).update();
				}
				return true;
			}
		});
	}


	public Map<String,Integer> findReaderAuthByName(int orgid){
		Map<String,Integer> map =new HashMap<String,Integer>();
		List<ReaderAuth> readerAuthList= dao.find("SELECT id, name FROM t_reader_auth where   orgid=?",orgid);
		for (ReaderAuth readerAuth: readerAuthList) {
			map.put(readerAuth.getName(),readerAuth.getId());
		}
		return map;
	}


	public List<Record> findBooktypeAuth(int orgid){
	    String sql ="select * from t_booktype_auth where orgid=?";
        return Db.find(sql,orgid);
    }

	public List<Record> findBooktypeAuthByIds(String ids){
		String sql ="select * from t_booktype_auth where id in ("+ ids+")";
		return Db.find(sql);
	}
}
