package com.sys.bus.setting.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.jfree.util.Log;
import com.alibaba.druid.util.StringUtils;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.sys.bus.sys.model.DtBean;
import com.sys.core.utils.Tool;

public class ApproverSettingService {
	private static final DtBean comDao = new DtBean().dao();

	public List<DtBean> department(){
		String sql = "select orgtab.fid id,fparentid pId,fname_l2 name,fdisplayname_l2 t,fdisplayname_l2 fullname  from t_org_admin orgtab";

		//"select orgtab.fid id,fparentid pId,fname_l2 name,fdisplayname_l2 t,fdisplayname_l2 fullname,rownum as rownnumber from t_org_admin orgtab  start with  fparentid is null connect by prior fid = fparentid ";
		return comDao.find(sql);
	}
	public Page<DtBean> listApproveUser(int pageNumber ,int pageSize,String orgid) {
		String sql = " FROM ct_jx_app a \r\n" + 
				"left join t_bd_person p on  a.app_personid = p.fid\r\n" + 
				"where a.app_deptid = ? order by a.app_orderno asc";

		return  comDao.paginate(pageNumber, pageSize, "SELECT a.App_Id id,a.app_deptid ,a.app_nodename,a.app_orderno,a.app_personid,p.fnumber,p.fname_l2", sql, orgid);
	}
	public List<DtBean> listApproveUser(String orgid) {
		String sql = "SELECT a.App_Id id,a.app_deptid ,a.app_nodename,a.app_orderno,a.app_personid,p.fnumber,p.fname_l2 \r\n"
				+" FROM ct_jx_app a \r\n" + 
				"left join t_bd_person p on  a.app_personid = p.fid\r\n" + 
				"where a.app_deptid = ? order by a.app_orderno asc";

		return  comDao.find(sql, orgid);
	}
	public List<DtBean> listLeftApproveUser() {
		String sql = "SELECT p.fid id,p.fname_l2 name,a.Fid deptid,a.FNAME_L2 deptname ,et.FNAME_L2"
				+" FROM  ct_jx_app ap "
		 +" left join t_bd_person p on  ap.app_personid = p.fid"
		 +" LEFT JOIN t_org_admin a ON a.FID = ap.app_deptid "
		+" left join  T_HR_BDEmployeeType et on  et.fid = p.femployeetypeid " 
		 +" WHERE  et.femployeefenleiid <>'00000000-0000-0000-0000-0000000000015C14FC3A' "
		+"  order by p.FID";

		return  comDao.find(sql);
	}
	public Page<DtBean> searchUser(int pageNumber ,int pageSize,String orgid,String qName){

		String sqlCount = "";
		String sqlPara  = "";
		//调节查询
		if(!StringUtils.isEmpty(qName)) {
			String[] names = null;
//			if(qName.indexOf("，")>0||qName.indexOf(",")>0){
//				qName =qName.replace(" ", "");//清除空格
//				 if(qName.indexOf("，")>0)qName =qName.replace("，", ",");
//				 if(qName.indexOf(",")>0){
//					 names = qName.split(",");
//				 }
//			}else if(qName.indexOf(" ")>0){
//				names = qName.split(" ");
//			}
			qName = qName.replaceAll("\\s{1,}", " ");//把多个连续空格替换成单空格
			names = qName.split("[ ,：，；;]");//任意分隔符分割
			String namesql = "";
			if(names!=null&&names.length>1){
				for (String n:names) {
					namesql+="'"+n+"',";
				}
				namesql=namesql.substring(0, namesql.length()-1);
			}
			
			sqlCount = "select count(1) from \r\n" + 
					"(\r\n" + 
					"SELECT person.fid ,person.fnumber ,person.fname_l2 uname,position.fname_l2 poname,position.fid poid,org.fdisplayname_l2 fullname\r\n" + 
					"  FROM t_bd_person person\r\n" + 
					"  left join T_ORG_PositionMember opmap\r\n" + 
					"    on person.fid = opmap.fpersonid\r\n" + 
					"  left join t_org_position position\r\n" + 
					"    on position.fid = opmap.fpositionid\r\n" + 
					"  left join t_org_admin org\r\n" + 
					"    on org.fid = position.fadminorgunitid\r\n" + 
					"  left join T_HR_BDEmployeeType t\r\n" + 
					"    on t.fid = person.femployeetypeid\r\n" + 
					" where t.fname_l2 in ('正式员工','试用员工') and (person.fnumber = '"+qName;
			      if(org.apache.commons.lang3.StringUtils.isNotBlank(namesql)){
			    	  sqlCount += "' or person.fname_l2 in( "+namesql+"))) temp";
			      }else{
			    	  sqlCount += "' or person.fname_l2 = '"+qName+"')) temp";
			      }
					
			sqlPara = "SELECT person.fid id,person.fnumber ,person.fname_l2 uname,position.fname_l2 poname,position.fid poid,org.fdisplayname_l2 fullname\r\n" + 
					"  FROM t_bd_person person\r\n" + 
					"  left join T_ORG_PositionMember opmap\r\n" + 
					"    on person.fid = opmap.fpersonid\r\n" + 
					"  left join t_org_position position\r\n" + 
					"    on position.fid = opmap.fpositionid\r\n" + 
					"  left join t_org_admin org\r\n" + 
					"    on org.fid = position.fadminorgunitid\r\n" + 
					"  left join T_HR_BDEmployeeType t\r\n" + 
					"    on t.fid = person.femployeetypeid\r\n" + 
					" where t.fname_l2 in ('正式员工','试用员工') and (person.fnumber = '"+qName;
				 if(org.apache.commons.lang3.StringUtils.isNotBlank(namesql)){
					 sqlPara += "' or person.fname_l2 in( "+namesql+"))";
			      }else{
			    	  sqlPara += "' or person.fname_l2 = '"+qName+"')";
			      }
			     

			Log.info(sqlPara);

		}else {//按部门查询

			sqlCount = "select count(1) from \r\n" + 
					"(\r\n" + 
					"SELECT person.fid ,person.fnumber ,person.fname_l2,org.fdisplayname_l2\r\n" + 
					"  FROM t_bd_person person\r\n" + 
					"  left join T_ORG_PositionMember opmap\r\n" + 
					"    on person.fid = opmap.fpersonid\r\n" + 
					"  left join t_org_position position\r\n" + 
					"    on position.fid = opmap.fpositionid\r\n" + 
					"  left join t_org_admin org\r\n" + 
					"    on org.fid = position.fadminorgunitid\r\n" + 
					"  left join T_HR_BDEmployeeType t\r\n" + 
					"    on t.fid = person.femployeetypeid\r\n" + 
					" where t.fname_l2 in ('正式员工','试用员工') and org.fid = '"+orgid+"'\r\n" + 
					") temp \r\n" +
					"";
			sqlPara ="SELECT person.fid id,person.fnumber ,person.fname_l2 uname,position.fname_l2 poname,position.fid poid,org.fdisplayname_l2 fullname\r\n" + 
					"  FROM t_bd_person person\r\n" + 
					"  left join T_ORG_PositionMember opmap\r\n" + 
					"    on person.fid = opmap.fpersonid\r\n" + 
					"  left join t_org_position position\r\n" + 
					"    on position.fid = opmap.fpositionid\r\n" + 
					"  left join t_org_admin org\r\n" + 
					"    on org.fid = position.fadminorgunitid\r\n" + 
					"  left join T_HR_BDEmployeeType t\r\n" + 
					"    on t.fid = person.femployeetypeid\r\n" + 
					" where t.fname_l2 in ('正式员工','试用员工') and org.fid = '"+orgid+"'";
		}

		return comDao.paginateByFullSql(pageNumber, pageSize, sqlCount, sqlPara);
	}
	public String getPara(String value) {
		if(!StringUtils.isEmpty(value)) {
			return "and person.fname_l2 like '%"+value+"%'";
		}
		return "";
	}
	public Page<DtBean> page(int pageNumber, int pageSize) {
		return comDao.paginate(pageNumber, pageSize, "select *", "from ZX_TEST_USER order by id asc");
		//comDao.paginateByFullSql(pageNumber, pageSize, totalRowSql, findSql, paras);
	}






	public void doAction(int type,String rowid) {
		String sql ="";
		DtBean  bean = comDao.findFirst("select * from ct_jx_app where app_id = ?", rowid);
		int cOrder = bean.getBigDecimal("app_orderno").intValue();
		if(type==1) {
			int minOrder = getOrderNo("min",bean.getStr("app_deptid"));
			int order =minOrder -1;
			sql = "update ct_jx_app set app_orderno = "+order+" where App_Id = '"+rowid+"'";
			Db.update(sql);
		}
		if(type==2) {//up
			
			sql = "update ct_jx_app set app_orderno = (app_orderno+1) where App_Id = '"+rowid+"' and app_orderno <" +cOrder;
			Db.update(sql);
			sql = "update ct_jx_app set app_orderno = (app_orderno-1) where App_Id = '"+rowid+"'";
			Db.update(sql);
		}
		if(type==3) {//down
			
			/*
			Db.tx(new IAtom(){
				@Override
				public boolean run() throw SQLException{
					sql = "update ct_jx_app set app_orderno = (app_orderno+1) where App_Id = '"+rowid+"' and app_orderno >" +cOrder;
					Db.update(sql);
					return true;
				}
			});
			*/
			
			
			sql = "update ct_jx_app set app_orderno = (app_orderno+1) where App_Id = '"+rowid+"'";
			Db.update(sql);
			
		}
		if(type==4) {
			sql = "delete from ct_jx_app  where App_Id = '"+rowid+"'";
			Db.update(sql);
		}

	}
	public void addApproveUser(String orgId,String nodeName,String personId) {
		String sql = "insert into ct_jx_app(app_id,app_deptid,app_nodename,app_personid,app_orderno)"
				+ " values('"+Tool.uuid()+"','"+orgId+"','"+nodeName+"','"+personId+"',"+(getOrderNo("max",orgId)+1)+")";
		Db.update(sql);
	}
	
	public int getOrderNo(String type,String orgId) {
		DtBean bean =  comDao.findFirst("select "+type+"(app_orderno) order_ from  ct_jx_app  where  app_deptid = ?", orgId);
		if(bean==null) return 0;
		else {
			return bean.get("order_")==null?0:((BigDecimal)bean.get("order_")).intValue();
					
		}
			
	}
	public  List<DtBean>  getNodeNames() {
		String sql = "SELECT * FROM ct_jx_syscode where syscode_type = 'param' and syscode_name='nodename' and syscode_status = 1";
		String nodename = comDao.findFirst(sql).getStr("syscode_value").replaceAll("，", ",").trim();
		List<DtBean> list = new ArrayList<DtBean>();
		for(String str:nodename.split(",")){
			DtBean b = new DtBean();
			b.put("syscode_name",str);
			list.add(b);
		}
		return list;
	}

	/**
	 * Id查询员工对象
	 * @param personId
	 * @return
	 */
	public DtBean getPersonById(String personId) {
		return comDao.findFirst("select * from t_bd_person where fid=?", personId);
	}
	/**
	 * 获取员工 所有审批的部门ID集合
	 * @return
	 */
	public List<String> getDeptByPid(String pid){
		String sql=" SELECT app_deptid FROM ct_jx_app a "
		+ " left join t_bd_person p on  a.app_personid = p.fid "
		 +" where a.app_personid =? ";
		SqlPara sp = new SqlPara();	
		sp.setSql(sql);
		sp.addPara(pid);
		List<String> dlist = new ArrayList<String>();
		List<DtBean> list = comDao.find(sp);
		for(DtBean b:list){
			dlist.add(b.getStr("app_deptid"));
		}
		return dlist;
	}

}
