package com.palmnest.dao.estateserve.impl;

import com.palmnest.application.bean.Page;
import com.palmnest.dao.estateserve.EnterprisePermissionDao;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.model.enterprise.VirPermConfig;
import com.palmnest.model.property.VirtualArchitecture;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author HIAPAD
 * @Description TODO
 * @Date 2019/2/25 9:40
 **/
@Repository("enterprisePermissionDao")
public class EnterprisePermissionDaoImpl extends GenericDaoHibernate<VirPermConfig, Long> implements EnterprisePermissionDao {

	private static final Logger log = LoggerFactory.getLogger(EnterprisePermissionDaoImpl.class);

	public EnterprisePermissionDaoImpl() {
		super(VirPermConfig.class);
	}


	@Override
	public void saveOtherObj(Object object) {
		getSession().save(object);
	}


	/**
	 * VirServiceRelation(tr_vir_service) 这个是企业权限(tb_vir_perm_config) X 服务项目关联表(tb_serviceprojectallocation) 的关联
	 *
	 * @param id
	 */
	@Override
	public void delVirPermServiceRelation(Long id) {

		String sql = "DELETE FROM VirServiceRelation WHERE virPermId=?";

		getSession().createQuery(sql).setLong(0, id).executeUpdate();
	}

	@Override
	public void delVirPermService(Long id) {
		String sql = "DELETE FROM VirServiceChild WHERE virPermId=?";
		getSession().createQuery(sql).setLong(0, id).executeUpdate();
	}

	/**
	 * TODO 标注 这方法 还存在 调用方 组装 hql 传进来?
	 *
	 * @param pageNo
	 * @param pageSize
	 * @param s
	 * @return
	 */
	@Override
	public Page queryVirPermListPage(int pageNo, int pageSize, String s) {

		StringBuffer strSbf = new StringBuffer();

		strSbf.append(" SELECT t1.id,t1.`name` 'permName',t2.`name` 'orgName',t4.name 'virName',t3.userName,t1.createTime FROM tb_vir_perm_config t1 LEFT JOIN tb_organization t2 ON t1.orgId=t2.ID LEFT JOIN tb_app_user t3 ON t1.creator=t3.ID ");
		strSbf.append(" LEFT JOIN tb_virtualarchitecture t4 ON t1.virId=t4.id");
		strSbf.append(s);
		strSbf.append(" order by t1.createTime desc");

		return pagedQueryByJdbcTemplate(strSbf.toString(), pageNo, pageSize);
	}

	@Override
	public String getVirPermServiceRelationStr(long id) {

		String sql = " select group_concat(t2.`name`) result from " +
				" (SELECT serviceName 'name' FROM tb_servicetypeinfo WHERE id in(SELECT t2.serviceTypeId FROM tr_vir_service t1 LEFT JOIN tb_serviceprojectallocation t2 ON t1.serviceId = t2.id WHERE t1.virPermId=" + id + ") ORDER BY id) t2";

		Object o = getSession().createSQLQuery(sql).uniqueResult();
		if (Objects.isNull(o)) {
			return null;
		} else {
			return o.toString();
		}
//        return getSession().createSQLQuery(sql).uniqueResult().toString();
	}

	@Override
	public List<Map<String, Object>> getVirPermService(long id) {

		String sql = " SELECT t2.id, t3.id AS serviceId, t3.serviceName 'name' FROM tr_vir_service t1 LEFT JOIN tb_serviceprojectallocation t2 ON t1.serviceId = t2.id LEFT JOIN tb_servicetypeinfo t3 ON t2.serviceTypeId = t3.id WHERE t1.virPermId = " + id;
//        String sql = " select t2.id 'serviceId', t2.`name` from " +
//                " (SELECT id, serviceName 'name' FROM tb_servicetypeinfo WHERE id in(SELECT t2.serviceTypeId FROM tr_vir_service t1 LEFT JOIN tb_serviceprojectallocation t2 ON t1.serviceId = t2.id WHERE t1.virPermId="+id+") ORDER BY id) t2";

		return getJdbcTemplate().queryForList(sql);
	}

	@Override
	public List<Map<String, Object>> getVirPermServiceChild(long id) {

		String sql = " SELECT t2.id, t2.service_id, t2.child_name `name`, t2.`code` " +
				"FROM ( " +
				"	SELECT * " +
				"	FROM tb_servicetypeinfo_child " +
				"	WHERE " +
				"		id IN ( " +
				"			SELECT t2.id " +
				"			FROM tr_vir_service_child t1 " +
				"				LEFT JOIN tb_servicetypeinfo_child t2 ON t1.serviceChildId = t2.id " +
				"			WHERE t1.virPermId = " + id +
				" 			) " +
				"ORDER BY id ) t2";

		return getJdbcTemplate().queryForList(sql);
	}



	@Override
	public List<Map<String, Object>> getProcessName(Long orgId, String types) {

		String sql = " SELECT DISTINCT  t1.processName FROM tb_goods_config t1 " +
				" WHERE t1.type IN ("+types+") AND t1.orgId = "+orgId+" ORDER BY t1.id " ;


		return getJdbcTemplate().queryForList(sql);
	}



	@Override
	public List<Integer> getVirPermServiceIds(Long virPermId) {

		String sql = "select serviceId from VirServiceRelation where virPermId=?";
		return getSession().createQuery(sql).setLong(0, virPermId).list();
	}

	@Override
	public List<Integer> getVirPermServiceChildIds(Long virPermId) {

		String sql = "select serviceChildId from VirServiceChild where virPermId=?";
		return getSession().createQuery(sql).setLong(0, virPermId).list();
	}

	@Override
	public List<VirPermConfig> getOrgRelationVirPermList(Integer orgId) {

		String hql = "from VirPermConfig where orgId=? and permType=? and enable=1 order by id";
		return getSession().createQuery(hql).setInteger(0, orgId).setInteger(1, 0).list();
	}

	@Override
	public List<Map<String, Object>> getVirPermServiceRelation(Long id) {

		String sql = " SELECT t4.serviceName,t3.id,t4.code " +
				"	FROM tr_vir_service t2 " +
				" 		LEFT JOIN tb_serviceprojectallocation t3 ON t2.serviceId = t3.id " +
				" 		LEFT JOIN tb_servicetypeinfo t4 ON t3.serviceTypeId = t4.id " +
				" WHERE t2.virPermId =" + id + " ORDER BY t2.id";

		return getJdbcTemplate().queryForList(sql);
	}

	@Override
	public List<VirtualArchitecture> getVirListByPermId(Long id) {
		String sql = " from VirtualArchitecture where isEnabled=? and virType=? order by id";
		return getSession().createQuery(sql).setInteger(0, 1).setLong(1, id).list();
	}

	@Override
	public void clearVirPermRelation(long permId) {
		String sql = " update VirtualArchitecture set virType=null where virType=?";
		getSession().createQuery(sql).setLong(0, permId).executeUpdate();
	}

//    @Override
//    public List<VirPermConfig> getVirRelationVirPermList(Integer orgId, Integer virId) {
//        String hql = "from VirPermConfig where orgId=? and virId=? and permType=? and enable=1 order by id";
//        return getSession().createQuery(hql).setInteger(0,orgId).setInteger(1,virId).setInteger(2,1).list();
//    }
//
//    @Override
//    public List<Map<String, Object>> getOrgOpenedPermList(Integer organizationId) {
//
//        String sql = " SELECT t2.serviceName,t2.`code` serviceCode,t2.id serviceId " +
//                " FROM tb_serviceprojectallocation t1 " +
//                " LEFT JOIN tb_servicetypeinfo t2 ON t1.serviceTypeId = t2.id " +
//                " WHERE t1.projectId = "+organizationId+" AND permission = 1 ";
//        return getJdbcTemplate().queryForList(sql);
//    }

	@Override
	public List<String> getNoPermServiceCodeList(Integer organizationId, Long virPermId) {
		String sql = " SELECT t2.`code` serviceCode " +
				"FROM tb_serviceprojectallocation t1 " +
				"	LEFT JOIN tb_servicetypeinfo t2 ON t1.serviceTypeId = t2.id " +
				"WHERE " +
				"	t1.projectId = " + organizationId +
				" 	AND permission = 1 " +
				"	AND t1.id not in(SELECT t1.serviceId FROM tr_vir_service t1 WHERE t1.virPermId=" + virPermId + ") ";
		return getSession().createSQLQuery(sql).list();
	}

	@Override
	public void delGoodsConfig(Long id, String types) {
		String sql = "DELETE FROM GoodsConfig WHERE orgId=? and type IN (" + types + ") ";
		getSession().createQuery(sql).setLong(0, id).executeUpdate();
	}

	/**
	 *
	 * @param orgId
	 * @param types 查数据库得知 1.企业审核;2.物业审核 TODO 3,4 又是什么
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getGoodsConfig(Long orgId, /*1.企业审核;2.物业审核*/String types,String processName) {

		String sql = " SELECT * FROM tb_goods_config WHERE orgId = " + orgId;

		if (StringUtils.isNotEmpty(types)) {

			sql = " SELECT t1.roleId,t1.roleName, t2.`name`,t1.type,t1.sort, t1.processType,t1.processName " +
					"FROM tb_goods_config t1 " +
					"	LEFT JOIN tb_vir_perm_config t2 ON t1.roleId = t2.id " +
					"WHERE " +
					"	t1.type IN (" + types + ") " ;


			if(StringUtils.isNotEmpty(processName)){
				sql = sql+ " and t1.processName = '"+processName+"' " ;
			}

			sql = sql +  " and t1.orgId = " + orgId + " ORDER BY t1.type ";
		}



		System.out.println("===>getGoodsConfig Sql :"+sql);
		return getJdbcTemplate().queryForList(sql);
	}
	
	@Override
	public List<Map<String, Object>> getGoodsConfigByTypes(Long orgId, /*1.企业审核;2.物业审核*/String types) {

		String sql = " SELECT * FROM tb_goods_config WHERE orgId = " + orgId;

		if (StringUtils.isNotEmpty(types)) {

			sql = " SELECT ifnull( "
					+ "( SELECT GROUP_CONCAT(DISTINCT t1.roleId) " +
					" FROM tb_goods_config t1 " +
					"	LEFT JOIN tb_vir_perm_config t2 ON t1.roleId = t2.id " +
					" WHERE " +
					"	t1.type IN (" + types + ") " +
					"	and t1.orgId = " + orgId + " ORDER BY t1.type )	,0 "
					+ " ) roleId ";
			
			
			
			
			
			/*if (type.equals(1)) {
				sql = " SELECT t1.roleId, t2.`name` FROM tb_goods_config t1 LEFT JOIN tb_vir_perm_config t2 ON t1.roleId = t2.id WHERE t1.type = "+type+" and t1.orgId = " + orgId;
			}*/ /*else {
				sql = " SELECT t1.roleId, t2.`name` FROM tb_goods_config t1 LEFT JOIN tb_app_role t2 ON t1.roleId = t2.ID WHERE t1.type = 2 and t1.orgId = " + orgId;
			}*/
		}

		//return getSession().createSQLQuery(sql).list();
		//return getSession().createQuery(sql).list();
		return getJdbcTemplate().queryForList(sql);
	}

	/**
	 * tb_vir_perm_config 是个企业 权限 配置表
	 *
	 * @param orgId
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getPermByCheckRole(Long orgId) {

		// 增加isGeneral = 1 的 全局公共身份
		String sql = " SELECT id, `name` " +
				"FROM tb_vir_perm_config " +
				"WHERE " +
				"	(orgId IN (" + orgId + ") or isGeneral=1) " +
				"	AND checkRole = 1";

		return getJdbcTemplate().queryForList(sql);
	}

	/**
	 * 查询 某企业 前端用户 有没 某企业权限
	 * TODO 是不关心是谁,
	 * @param virtualArchId
	 * @return
	 */
	@Override
	public Integer check(Integer virtualArchId) {

		String sql = " SELECT COUNT(1) " +
				"FROM tb_user t1 " +
				"	LEFT JOIN tb_vir_perm_config t2 ON t1.virPermId = t2.id " +
				"WHERE " +
				"	t2.checkRole = 1 " +
				"	AND t1.virtualArchId = " + virtualArchId;

		return getJdbcTemplate().queryForInt(sql);
	}

}
