package com.palmnest.dao.hibernate;

import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.dao.ElementGroupDao;
import com.palmnest.model.Element;
import com.palmnest.model.ElementGroup;
import com.palmnest.model.OrgElement;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This class interacts with Hibernate session to save/delete and
 * retrieve ScNearby objects.
 *
 * @author ldb
 */
@Repository("elementGroupDao")
public class ElementGroupDaoHibernate extends GenericDaoHibernate<ElementGroup, Long> implements ElementGroupDao {

	public ElementGroupDaoHibernate() {
		super(ElementGroup.class);
		// TODO Auto-generated constructor stub
	}

	/**
	 * 删除ElementGroup
	 * 级联删除子表 Element 关联数据
	 * 级联删除子表 OrgElement 关联数据
	 */
	public void removeElementGroups(Long... ids) {

		if (ArrayUtils.isEmpty(ids))
			throw new NullPointerException();
		super.getSession().createQuery("delete from Element where elementGroup.id in (:ids)")
				.setParameterList("ids", ids).executeUpdate();
		super.getSession().createQuery("delete from OrgElement where elementGroup.id in (:ids)")
				.setParameterList("ids", ids).executeUpdate();
		super.getSession().createQuery("delete from ElementGroup where id in (:ids)")
				.setParameterList("ids", ids).executeUpdate();
	}

	@Override
	public ElementGroup getElementGroupId(Long id) {

		return (ElementGroup) getSession().get(ElementGroup.class, id);
	}



	@Override
	public void removeElement(Long... ids) {

		if (ArrayUtils.isEmpty(ids))
			throw new NullPointerException();
		super.getSession().createQuery("delete from Element where id in (:ids)")
				.setParameterList("ids", ids).executeUpdate();

		// 同时删除group表中相关的数据
		super.getSession().createQuery("update ElementGroup set itemId=null  where itemId in (:ids)")
				.setParameterList("ids", ids).executeUpdate();
	}

	public String getElementName(Long id) {
		List<Element> list = getSession().createCriteria(Element.class).add(Restrictions.eq("elementGroup.id", id)).list();
		String        str  = "";
		if (list != null && list.size() > 0) {
			for (Element element : list) {
				str += element.getItemname() + "{" + element.getItemcode() + "},";
			}
		}
		return str;
	}

	@Override
	public Map<Long, String> getElementIds(Collection<Long> ids) {

		if (ids == null)
			throw new NullPointerException();
		Map<Long, String> map = new HashMap<Long, String>();
		for (Long id : ids) {
			map.put(id, getElementName(id));
		}
		return map;
	}

	@Override
	public Element saveElement(Element element) {

		return (Element) getSession().merge(element);
	}

	@Override
	public Element getElementId(Long id) {

		return (Element) getSession().get(Element.class, id);
	}

	@Override
	public long getTabMaxOptVersion(String tableName) {

		return super.getTabMaxOptVersion(tableName);
	}

	@Override
	public List<ElementGroup> getSyncDataList(long minVersion, long maxVersion) {
		String hql = "from ElementGroup where opratetype!='" + ElementConstant.OPRATETYPE_DEL + "' and oprateversion>" + minVersion + " and oprateversion<=" + maxVersion;
		return super.getSession().createQuery(hql).list();
	}

	@Override
	public List getSyncElementDataList(long minVersion, long maxVersion) {
		String sql = "select * from tb_dictionary_item where opratetype!='" + ElementConstant.OPRATETYPE_DEL + "' and oprateversion>" + minVersion + " and oprateversion<=" + maxVersion;
		return this.getJdbcTemplate().queryForList(sql);
	}

	@Override
	public List<ElementGroup> getAllDataList() {
		String hql = "from ElementGroup where opratetype!='" + ElementConstant.OPRATETYPE_DEL + "'";
		return super.getSession().createQuery(hql).list();
	}

	@Override
	public ElementGroup getElementGroupByCode(String code) {
		String hql = "from ElementGroup where groupcode=?";
		List<ElementGroup> list = super.getSession().createQuery(hql).setString(0, code).list();
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public Map<String, Object> getOrderAreaInfo(String areaCode) {
		String                    sql  = "select t1.itemname from tb_dictionary_item t1,tb_dictionary_group t2 where t2.groupcode='projectAreaGroup' and t1.groupid=t2.id and t1.itemcode='" + areaCode + "'";
		List<Map<String, Object>> list = this.getJdbcTemplate().queryForList(sql);
		if (!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public Element getByItemCode(String itemcode) {
		String        hql  = "from Element where itemcode=?";
		List<Element> list = super.getSession().createQuery(hql).setString(0, itemcode).list();
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public Element getByItemCode(String groupcode, String itemcode) {
		String        hql  = "SELECT t1.* FROM tb_dictionary_item t1 LEFT JOIN tb_dictionary_group t2 ON t1.groupid = t2.id WHERE t2.isenabled='1' AND t1.isenabled='1' AND t2.groupcode='" + groupcode + "' AND t1.itemcode='" + itemcode+ "' ";
		List<Element> list = super.getSession().createSQLQuery(hql).addEntity(Element.class).list();
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public Element getByItemname(String groupcode, String itemname) {
		String        hql  = "SELECT t1.* FROM tb_dictionary_item t1 LEFT JOIN tb_dictionary_group t2 ON t1.groupid = t2.id WHERE t2.isenabled='1' AND t1.isenabled='1' AND t2.groupcode='" + groupcode + "' AND t1.itemname='" + itemname + "' ";
		List<Element> list = super.getSession().createSQLQuery(hql).addEntity(Element.class).list();
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public Page orgSettingList(int pageNo, int pageSize, HashMap<String, String> map) {
		String sql = "SELECT" +
				" t1.id groupId," +
				" t1.groupname," +
				" t2.itemname funcName" +
				" FROM" +
				" tb_dictionary_group t1" +
				" LEFT JOIN tb_dictionary_item t2 ON t1.itemid = t2.id" +
				" WHERE" +
				" t1.isenabled = '1'" +
				" AND t1.isorgcustom = 1";

		if (StringUtils.isNotBlank(map.get("groupName"))) {
			sql += " AND t1.groupname LIKE '%" + map.get("groupName") + "%'";
		}
		if (StringUtils.isNotBlank(map.get("funcId"))) {
			sql += " AND t1.itemid=" + map.get("funcId");
		}
		return pagedQueryByJdbcTemplate(sql, pageNo, pageSize);
	}
	@Override
	public List<OrgElement> getElementListByOrgAndGroup(Long groupId, Integer orgId) {
		String sql = "SELECT * FROM tb_dictionary_org_item WHERE orgid =" + orgId + " AND groupid=" + groupId + " ORDER BY orderno";
		return getSession().createSQLQuery(sql).addEntity(OrgElement.class).list();
	}

	@Override
	public List<OrgElement> getElementListByOrgAndGroup(String groupCode,
														String orgIds) {
		StringBuilder sql = new StringBuilder("  SELECT doi.* FROM tb_dictionary_org_item doi  ");
		sql.append("  left join tb_dictionary_group dg on dg.id=doi.groupid   ");
		sql.append("  WHERE doi.orgid in (" + orgIds + ") AND dg.groupcode='" + groupCode + "'  AND doi.isenabled = 1 AND dg.isenabled = 1  ");
		sql.append("  ORDER BY doi.orderno  ");
		return getSession().createSQLQuery(sql.toString()).addEntity(OrgElement.class).list();
	}


	@Override
	public List<OrgElement> getElementListByOrgAndGroup(String groupCode,
														Integer orgId) {
		StringBuilder sql = new StringBuilder("  SELECT doi.* FROM tb_dictionary_org_item doi  ");
		sql.append("  left join tb_dictionary_group dg on dg.id=doi.groupid   ");
		sql.append("  WHERE doi.orgid=" + orgId + " AND dg.groupcode='" + groupCode + "'   ");
		sql.append("  ORDER BY doi.orderno  ");
		return getSession().createSQLQuery(sql.toString()).addEntity(OrgElement.class).list();
	}

	@Override
	public OrgElement getByItemCode(String orgId, String groupcode,
									String itemCode) {
		StringBuilder sql = new StringBuilder("  SELECT doi.* FROM tb_dictionary_org_item doi  ");
		sql.append("  left join ");
		sql.append("  tb_dictionary_group dg ");
		sql.append("  on dg.id=doi.groupid  ");
		sql.append("  WHERE doi.orgid=" + orgId + " and  doi.code='" + itemCode + "' and dg.`groupcode` ='" + groupcode + "'");
		sql.append("  ORDER BY doi.orderno  ");
		List<OrgElement> list = getSession().createSQLQuery(sql.toString()).addEntity(OrgElement.class).list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public OrgElement getByItemname(String orgId, String groupcode, String itemname) {
		StringBuilder sql = new StringBuilder("  SELECT doi.* FROM tb_dictionary_org_item doi  ");
		sql.append("  left join tb_dictionary_group dg on dg.id=doi.groupid   ");
		sql.append("  WHERE doi.orgid=" + orgId + " AND dg.groupcode='" + groupcode + "' and   doi.itemname='" + itemname + "' ");
		sql.append("  ORDER BY doi.orderno  ");
		List<OrgElement> list = getSession().createSQLQuery(sql.toString()).addEntity(OrgElement.class).list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<Element> getElementListByGroup(Long groupId) {
		String sql = "SELECT * FROM tb_dictionary_item WHERE isenabled='1' AND groupid=" + groupId;
		return getSession().createSQLQuery(sql).addEntity(Element.class).list();
	}

	@Override
	public List<Element> getItemCode(String groupcode, String itemcode) {
		String        hql  = "SELECT t1.* FROM tb_dictionary_item t1 LEFT JOIN tb_dictionary_group t2 ON t1.groupid = t2.id WHERE t2.isenabled='1' AND t1.isenabled='1' AND t2.groupcode='" + groupcode + "' AND t1.itemcode=" + itemcode;
		List<Element> list = super.getSession().createSQLQuery(hql).addEntity(Element.class).list();
		return list;
	}

	@Override
	public OrgElement getOrgElementId(Long id) {

		return (OrgElement) getSession().get(OrgElement.class, id);
	}

	@Override
	public void delOrgSettingByOrgAndGroup(String notDelIds, Integer orgId, Long groupId) {
		String sql = " DELETE FROM tb_dictionary_org_item WHERE orgid=" + orgId + " AND groupid=" + groupId;
		if (StringUtils.isNotBlank(notDelIds)) {
			sql += " AND id NOT in(" + notDelIds + ")";
		}
		getSession().createSQLQuery(sql).executeUpdate();
	}

	@Override
	public List<OrgElement> getElementListByAllOrgAndGroup(String groupCode) {
		StringBuilder sql = new StringBuilder("  SELECT doi.* FROM tb_dictionary_org_item doi  ");
		sql.append("  left join tb_dictionary_group dg on dg.id=doi.groupid   ");
		sql.append("  WHERE  1=1 and dg.isenabled='1' and dg.groupcode='" + groupCode + "'   ");
		sql.append("  ORDER BY doi.orderno  ");
		return getSession().createSQLQuery(sql.toString()).addEntity(OrgElement.class).list();
	}


	@Override
	public List<OrgElement> getElementListByAllOrgAndGroupAsPage(int pageNo, int pageSize,Map<String, String> map) {
		StringBuilder sql = new StringBuilder("  SELECT doi.* FROM tb_dictionary_org_item doi  ");
		sql.append("  left join tb_dictionary_group dg on dg.id=doi.groupid   ");
		sql.append("WHERE 1=1 and dg.isenabled='1' ");
		if(StringUtils.isNotEmpty(map.get("groupCode"))){
			sql.append("  AND  dg.groupcode='" + map.get("groupCode") + "'   ");
		}
		if(StringUtils.isNotEmpty(map.get("groupCode1"))){
			sql.append("  AND  doi.code like '%" + map.get("groupCode1") + "%'   ");
		}
		if(StringUtils.isNotEmpty(map.get("groupName"))){
			sql.append("  AND  doi.itemname like '%" + map.get("groupName") + "%'   ");
		}
		if(StringUtils.isNotEmpty(map.get("orgId"))){
			sql.append("  AND  doi.orgid=" + Integer.parseInt(map.get("orgId")) + "   ");
		}
		sql.append("  ORDER BY doi.orderno  ");

		return getSession().createSQLQuery(sql.toString()).addEntity(OrgElement.class).list();
	}

	@Override
	public OrgElement getOrgElementByCode(String code,Integer orgId) {
		StringBuilder sql = new StringBuilder("  SELECT doi.* FROM tb_dictionary_org_item doi  ");
		sql.append("WHERE 1=1 and doi.isenabled='1' ");
		if (null != orgId) {
			sql.append("  AND  doi.orgid=" + orgId + "   ");
		}
		if (StringUtil.isNotEmpty(code)) {
			sql.append("  AND  doi.code='" + code + "'  ");
		}
		sql.append("limit 1");
		List<OrgElement> list = super.getSession().createSQLQuery(sql.toString()).addEntity(OrgElement.class).list();
		if (!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

}
