package com.service;


import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
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.Reader;
import com.model.User;
import com.utils.CommonUtils;
import com.utils.FaceUtil;
import org.apache.commons.lang3.StringUtils;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

public class ReaderService {


	public static final ReaderService me = new ReaderService();
	private Reader dao = new Reader().dao();
	private User userDao = new User().dao();

	public Reader findById(int id){
		return dao.findById(id);
	}
	public Page<Reader> paginate(int pageNumber,int pageSize, Reader bean, String deptname){
		String select = "SELECT a.id,a.realname,a.password as recode,a.cardnumber,a.sex,a.losedate,a.status,a.createtime,a.headimgurl,a.certificate," +
				" a.readertypeid, a.orgdeptid,a.readerauthid,a.certificatetypeid ," +
				" b.orgname,c.deptname,d.cardtype,e.name as certificatetypename,g.name as cardtypename ,f.name as authname";
		StringBuilder where = new StringBuilder(" from t_reader a " +
				"LEFT JOIN t_org b ON a.orgid = b.id " +
				"LEFT JOIN t_org_dept c ON a.orgdeptid = c.id " +
				"LEFT JOIN t_cardtype d ON a.cardtypeid = d.id " +
				"LEFT JOIN t_dict e ON a.certificatetypeid = e.id " +
				"LEFT JOIN t_dict g ON a.readertypeid = g.id " +
				"LEFT JOIN t_reader_auth f on f.id=a.readerauthid where 1=1");
		List values = new ArrayList();
		String cardnumber = bean.getCardnumber();
		String realname = bean.getRealname();

		if(StringUtils.isNotBlank(realname)){
			where.append(" and  ( a.realname like ?  or a.cardnumber like ? )");
			values.add("%"+realname+"%");
			values.add("%"+realname+"%");
		}
		if (bean.getOrgid() !=null ){
			where.append(" and  a.orgid = ?");
			values.add(bean.getOrgid());
		}
		if (bean.getOrgdeptid()!=null ){
			where.append(" and  a.orgdeptid = ?");
			values.add(bean.getOrgdeptid());
		}

		if (bean.getReadertypeid()!=null ){
			where.append(" and  a.readertypeid = ?");
			values.add(bean.getReadertypeid());
		}

		if (bean.getStatus()!=null ){
			where.append("  and  a.status = ?");
			values.add(bean.getStatus());
		}

		if (bean.getSex()!=null && !bean.getSex().equals("") ){
			where.append("  and a.sex = ?");
			values.add(bean.getSex());
		}
		if(StringUtils.isNotBlank(deptname)){
			where.append(" and c.deptname like ?");
			values.add("%"+deptname+"%");
		}

		where.append("  order by a.id desc");
		long t1 = System.currentTimeMillis();
		Page<Reader> list = dao.paginate(pageNumber, pageSize,select,where.toString(), CommonUtils.listToArray(values));
		long t2 = System.currentTimeMillis();
		System.out.println(t2-t1);
		return list;
	}


	public List<Record> export(Reader bean){
		String select = "SELECT a.*,b.orgname,c.deptname,d.cardtype,e.name as certificatetypename,g.name as cardtypename ,f.name as authname";
		StringBuilder where = new StringBuilder(" from t_reader a " +
				"inner JOIN t_org b ON a.orgid = b.id " +
				"inner JOIN t_org_dept c ON a.orgdeptid = c.id " +
				"LEFT JOIN t_cardtype d ON a.cardtypeid = d.id " +
				"LEFT JOIN t_dict e ON a.certificatetypeid = e.id " +
				"LEFT JOIN t_dict g ON a.readertypeid = g.id " +
				"LEFT JOIN t_reader_auth f on f.id=a.readerauthid where 1=1");
		List values = new ArrayList();
		String cardnumber = bean.getCardnumber();
		String realname = bean.getRealname();

		if(StringUtils.isNotBlank(realname)){
			where.append(" and  ( a.realname like ?  or a.cardnumber like ? )");
			values.add(realname+"%");
			values.add(realname+"%");
		}
		if (bean.getOrgid() !=null ){
			where.append(" and  a.orgid = ?");
			values.add(bean.getOrgid());
		}
		if (bean.getOrgdeptid()!=null ){
			where.append(" and  a.orgdeptid = ?");
			values.add(bean.getOrgdeptid());
		}

		if (bean.getReadertypeid()!=null ){
			where.append(" and  a.readertypeid = ?");
			values.add(bean.getReadertypeid());
		}

		if (bean.getStatus()!=null ){
			where.append("  and  a.status = ?");
			values.add(bean.getStatus());
		}

		if (bean.getSex()!=null && !bean.getSex().equals("") ){
			where.append("  and a.sex = ?");
			values.add(bean.getSex());
		}
		where.append("  order by a.id desc");

		return Db.find(select+where.toString(),CommonUtils.listToArray(values));
	}

	public void deleteById(int id) {
		dao.deleteById(id);
	}
	public void addOrUpdate(Reader bean, int operatorid){
		Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				if(bean.getId()== null){
					if(CommonUtils.isNullOrEmpty(bean.getPassword())){
						bean.setPassword(PropKit.get("initPassword","123456"));
					}
					bean.setStatus(1).setCreatetime(new Date()).setOperatorid(operatorid).save();
					if (bean.getFaceimage() !=null && !bean.getFaceimage().equals("")){
						FaceUtil.createUser(bean.getCardnumber(),bean.getRealname(),""+bean.getOrgid(),bean.getFaceimage().substring(22));
					}
				}else{
					Reader old = dao.findById(bean.getId());
					if(CommonUtils.isNullOrEmpty(old.getPassword())&&CommonUtils.isNullOrEmpty(bean.getPassword())){
						bean.setPassword(PropKit.get("initPassword","123456"));
					}
					bean.setCreatetime(old.getCreatetime()).setOperatorid(old.getOperatorid()).setUpdatetime(new Date()).setUpdateuserid(operatorid).update();

					if (bean.getFaceimage() !=null && !bean.getFaceimage().equals("")){
						FaceUtil.updateUser(bean.getCardnumber(),bean.getRealname(),""+bean.getOrgid(),bean.getFaceimage().substring(22));
					}
				}
				return true;
			}
		});
		Map map = new HashMap();
		map.put("orgid",bean.getOrgid()+"");
		map.put("realname",bean.getRealname());
		map.put("sex",bean.getSex());
		SimpleDateFormat format3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(CommonUtils.isNotNullOrNotEmpty(bean.getBirthday())){
			map.put("birthday",format3.format(bean.getBirthday()));
		}
		map.put("beantypeid",bean.getReadertypeid()+"");
		map.put("createtime",format3.format(bean.getCreatetime()));

	}
	public Map selectType(int operatorid){

		Map map = new HashMap<String,List>();
		//获取机构ID
		User userorgid = userDao.findFirst("SELECT orgid from t_user WHERE id = ? ",operatorid);
		int orgid = userorgid.getInt("orgid");
		//查询所在机构所有部门
		List orgdept = Db.find("SELECT id,deptname from t_org_dept WHERE orgid = ? ",orgid);
		//查询证件类型
		List certificatetype = Db.find("SELECT id,`name` from t_dict WHERE type = '7' ");
		map.put("orgdept",orgdept);
		map.put("certificatetype",certificatetype);
		return map;
	}
	//生成借书证号前缀
	public static String codeAddOne (int orgid,int strLength){
		String str = String.valueOf(orgid);
		while (str.length() < strLength) {
			str+="0";
		}
		return str;
	}
	//注销或者停用
	public void status(int id,int status){
		if(status == 4) {
			String exstr = "zx_" + CommonUtils.randownStr(4)+"_";
			Db.update("update t_reader set cardnumber = concat(?,cardnumber),readcardcode = cardnumber,status =4 where id = ? ",exstr,id);
		} else {
			Db.update("update t_reader set status = ? where id = ? ",status,id);
		}
	}

	//重置密码
	public void resetStatus(int id){
		Db.update("update t_reader set password = '123456' where id = ? ",id);
	}

	public void updatelosedate(String[] ids,String lostdate){
		StringBuffer idbuf=new StringBuffer();
		for (String id :ids){
			idbuf.append(id).append(",");
		}
		idbuf.append("-1");
		Db.update("update t_reader set losedate = ?, status=1 where id in ("+idbuf.toString()+") ",lostdate);
	}

	public boolean findReaderByCardNumber(String cardNumber,Integer id,Integer orgid){
		if (id ==null){
			String sql ="select cardnumber from  t_reader where cardnumber =? and orgid=?  limit 1";
			return Db.find(sql,cardNumber,orgid).size()>0;
		}else {
			String sql ="select cardnumber from  t_reader where cardnumber =? and id !=? and orgid=?";
			return Db.find(sql,cardNumber,id,orgid).size()>0;
		}
	}

	public List findReaderByCardNumber(Set<String> cardNumberSet,Integer orgid){
		StringBuffer sb =new StringBuffer();
		for (String cardNumber : cardNumberSet){
			sb.append("'").append(cardNumber).append("',");
		}
		sb.append("'----0000000000'");
		String sql ="select cardnumber from  t_reader where cardnumber in (" + sb.toString()+") and orgid=? ";
		List<Record> list=Db.find(sql,orgid);
		return list;
	}


	public List<Record> findBioKey(Integer orgid){
		String sql = "SELECT id,biokey FROM t_reader WHERE orgid=?";
		return  Db.find(sql,orgid);
	}
}
