package com.palmnest.dao.estateserve.impl;

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

import com.palmnest.application.bean.AppResultDto;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.dao.estateserve.AppUserDao;
import com.palmnest.dao.estateserve.VirtualArchDao;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;

/**
 * 企业管理Dao实现类
 *
 * @author longmeizhen
 */
@Repository("virtualArchDao")
public class VirtualArchDaoImpl extends GenericDaoHibernate<VirtualArchitecture, Integer> implements VirtualArchDao {

	@Autowired
	private AppUserDao appUserDao;

	public VirtualArchDaoImpl() {
		super(VirtualArchitecture.class);
	}

	/**
	 * 获取企业信息列表界面(当传过来的参数均为空时，默认查询所有的企业信息)
	 *
	 * @param floorId    楼层ID
	 * @param roomId     房间号
	 * @param isZuStatus 在租状态
	 * @param virName    企业名称
	 * @return
	 * @throws Exception
	 */

	@Transactional
	@Override
	public Page queryVirtualArchList(String orgId, String floorId, String roomId,
									 String isZuStatus, String virName, int pageNo, int pageSize)
			throws Exception {
		StringBuffer strSQL = new StringBuffer("  select va.isEnable isEnable,vir.id,ifnull(vir.`name`,'') as virName,ifnull(vir.customerNumber,'') customerNumber,vir.organizationId,org.`name` as orgName,vir.freeLenTime,vir.remainderTime ");
		strSQL.append(" ,ifnull(replace(vir.floorNames,',',';'),'') as 'floorNames',ifnull(replace(vir.roomNames,',',';'),'') as 'roomNames',vir.settleType,vir.isEmail,vir.isWechat,vir.isMessage,vir.leaseStatus,ifnull(vir.remark,'') remark ");
		strSQL.append(" ,ifnull(va.virAccount,'') as virAccount ,ifnull(t1.name,'暂未设置') as virPermName,t1.id permId,vir.virType");
		strSQL.append(" from tb_virtualarchitecture  vir ");
		strSQL.append(" left join tb_organization org on vir.organizationId=org.id  ");
		strSQL.append(" left join tb_vir_perm_config t1 on vir.virType=t1.id  ");
		strSQL.append(" left join tb_vir_account va on va.virId=vir.id where vir.isEnabled='1'  ");
		if (StringUtils.isNotBlank(orgId)) {
			String[] orgStr = orgId.split(";");
			String str = "";
			if (orgStr != null && orgStr.length > 0) {
				for (int i = 0; i < orgStr.length; i++) {
					str = str + orgStr[i] + ",";
				}
			}
			if (StringUtils.isNotEmpty(str)) {
				str = str.substring(0, str.length() - 1);
				strSQL.append(" and org.id in (" + str + ") ");
			}

		}
		if (StringUtils.isNotBlank(floorId)) {
			strSQL.append(" and (vir.floorIds like '%," + floorId + ",%' or vir.floorIds =" + floorId + " or vir.floorIds like '%," + floorId + "' or vir.floorIds like '," + floorId + "%' ) ");
		}
		if (StringUtils.isNotBlank(roomId)) {
			strSQL.append(" and (vir.roomIds like '%," + roomId + ",%' or vir.roomIds =" + roomId + " or vir.roomIds like '%," + roomId + "' or vir.roomIds like '," + roomId + "%' ) ");
		}
		if (StringUtils.isNotBlank(isZuStatus)) {

			strSQL.append(" and vir.leaseStatus=" + isZuStatus + " ");
		}
		if (StringUtils.isNotBlank(virName)) {
			strSQL.append(" and vir.name like '%" + virName + "%' ");
		}
		strSQL.append(" order by vir.createTime desc,id ");
		return pagedQueryByJdbcTemplate(strSQL.toString(), pageNo, pageSize);
	}

	@Transactional
	@Override
	public List<VirtualArchitecture> getVirByParamt(String floorId, String roomId, String isZuStatus, String virName, int pageNo, int pageSize) throws Exception {
		StringBuffer strSQL = new StringBuffer("  select vir.id,ifnull(vir.`name`,'') as virName,ifnull(vir.customerNumber,'') customerNumber,vir.organizationId,org.`name` as orgName ");
		strSQL.append(" ,ifnull(replace(vir.floorNames,',',';'),'') as 'floorNames',ifnull(replace(vir.roomNames,',',';'),'') as 'roomNames',vir.isEmail,vir.isWechat,vir.isMessage,vir.leaseStatus,ifnull(vir.remark,'') remark ");
		strSQL.append(" from tb_virtualarchitecture  vir ");
		strSQL.append(" left join tb_organization org on vir.organizationId=org.id where 1=1 ");
		if (StringUtils.isNotBlank(floorId)) {
			strSQL.append(" and (vir.floorIds like '%," + floorId + ",%' or vir.floorIds =" + floorId + " or vir.floorIds like '%," + floorId + "' or vir.floorIds like '," + floorId + "%' ) ");
		}
		if (StringUtils.isNotBlank(roomId)) {
			strSQL.append(" and (vir.roomIds like '%," + roomId + ",%' or vir.roomIds =" + roomId + " or vir.roomIds like '%," + roomId + "' or vir.roomIds like '," + roomId + "%' ) ");
		}
		if (StringUtils.isNotBlank(isZuStatus)) {
			strSQL.append(" and vir.leaseStatus=" + isZuStatus + " ");
		}
		if (StringUtils.isNotBlank(virName)) {
			strSQL.append(" and vir.name like '%" + virName + "%' ");
		}
		List<VirtualArchitecture> virList = getSession().createQuery(strSQL.toString()).list();
		return virList;
	}

	/**
	 * 根据企业获取有效的负责人信息
	 */
	@Transactional
	@Override
	public List<AppUser> getAppUserByVirAndIsRes(int virId) throws Exception {
		String userHql = "from AppUser where  virtualArchId=? and isEnabled='1' and isResponsible=1 ";
		List<AppUser> userList = getSession().createQuery(userHql).setInteger(0, virId).list();
		return userList;
	}

	@Override
	public List<VirtualArchitecture> getVirByCode(String code) throws Exception {
		//String userHql="from VirtualArchitecture where customerNumber=? and isEnabled='1' ";//貌似customerNumber 被删除了 一保存就不见了 by qzy
		String userHql = "from VirtualArchitecture where codeNumber=? and isEnabled='1' ";
		List<VirtualArchitecture> userList = getSession().createQuery(userHql).setString(0, code).list();
		return userList;
	}

	@Override
	public List<VirtualArchitecture> getVirByCode(String code, String orgId)
			throws Exception {
		String userHql = "from VirtualArchitecture where customerNumber=? and  organizationId=? and isEnabled='1' ";
		List<VirtualArchitecture> userList = getSession().createQuery(userHql).setString(0, code).setString(1, orgId).list();
		return userList;
	}

	@Override
	public List<VirtualArchitecture> getVirByOrgIdAndVirName(Integer virtualId, Integer level, int orgId, String virName) {
		String sql = " select * from tb_virtualarchitecture where organizationId=" + orgId + " and isEnabled='1' AND TYPE='1'";
		if (StringUtil.isNotEmpty(virName)) {
			sql = sql + "  and name like '%" + virName + "%'  ";
		}
		if (level != null) {
			sql = sql + " and `level` = " + level;
		}
		if (virtualId != null) {
			sql = sql + " and  id <> " + virtualId;
		}
		List<VirtualArchitecture> userList = getSession().createSQLQuery(sql).addEntity(VirtualArchitecture.class).list();
		return userList;
	}

	@Override
	public List<VirtualArchitecture> getVirByOrgIdAndNoAgant(Integer id, int orgId, String virName) {
		String sql = " select * from tb_virtualarchitecture t1 LEFT JOIN tb_virtualarchitecture_agent t2 ON t1.id = t2.id where organizationId= " + orgId + " and t1.isEnabled='1' AND t1.TYPE='1' and t1.`level` = 1 AND (t2.agent_id is null";

		if (id != null) {
			sql += " or t2.agent_id = " + id;
		}

		sql += ")";
		if (StringUtil.isNotEmpty(virName)) {
			sql = sql + "  and t1.name like '%" + virName + "%'  ";
		}
		List<VirtualArchitecture> userList = getSession().createSQLQuery(sql).addEntity(VirtualArchitecture.class).list();
		return userList;
	}

	@Override
	public List<VirtualArchitecture> getVirByName(String name) throws Exception {
		String userHql = "from VirtualArchitecture where name=? and isEnabled='1' ";
		List<VirtualArchitecture> userList = getSession().createQuery(userHql).setString(0, name).list();
		return userList;
	}

	@Override
	public List<VirtualArchitecture> getVirByName(String name, String orgId) throws Exception {
		String userHql = "from VirtualArchitecture where name=? and organizationId=?  and isEnabled='1' ";
		List<VirtualArchitecture> userList = getSession().createQuery(userHql).setString(0, name).setInteger(1, Integer.parseInt(orgId)).list();
		return userList;
	}

	@Override
	public List<TbOrganization> getBuild() throws Exception {
		String userHql = "from TbOrganization where code='SZ-HKDS' and isEnabled='1' ";
		List<TbOrganization> userList = getSession().createQuery(userHql).list();
		return userList;
	}

	@Override
	public Page getVirByIds(int pageNo, int pageSize, String virIds) throws Exception {
		StringBuffer strSQL = new StringBuffer("  select vir.id,ifnull(vir.`name`,'') as virName,ifnull(vir.customerNumber,'') customerNumber,vir.organizationId,org.`name` as orgName ");
		strSQL.append(" ,ifnull(replace(vir.floorNames,',',';'),'') as 'floorNames',ifnull(replace(vir.roomNames,',',';'),'') as 'roomNames',vir.isEmail,vir.isWechat,vir.isMessage,vir.leaseStatus,ifnull(vir.remark,'') remark ");
		strSQL.append(" from tb_virtualarchitecture  vir ");
		strSQL.append(" left join tb_organization org on vir.organizationId=org.id where vir.isEnabled='1' ");
		if (StringUtils.isNotBlank(virIds)) {
			strSQL.append(" and vir.id in (" + virIds + ") ");
		}
		strSQL.append(" order by vir.createTime desc ");
		return pagedQueryByJdbcTemplate(strSQL.toString(), pageNo, pageSize);
	}

	@Override
	public List<VirtualArchitecture> getVirByEnLess() throws Exception {
		String userHql = "from VirtualArchitecture where leaseStatus='1' and isEnabled='1' ";
		List<VirtualArchitecture> userList = getSession().createQuery(userHql).list();
		return userList;
	}

	@Override
	public List<VirtualArchitecture> getVirByRoomId(String roomIds) throws Exception {
		StringBuilder userHql = new StringBuilder("from VirtualArchitecture where leaseStatus='1' and isEnabled='1' ");
		if (StringUtils.isNotEmpty(roomIds)) {
			userHql.append(" and roomIds='" + roomIds + "'  ");
		}
		return getSession().createQuery(userHql.toString()).list();
	}

	@Override
	public List<VirtualArchitecture> getVirListByBuildId(String buildId, String virName) {
		String sql = "from VirtualArchitecture where leaseStatus='1' and isEnabled='1'";
		if (StringUtils.isNotBlank(buildId)) {
			sql += " and buildId=" + buildId;
		}
		if (StringUtils.isNotBlank(virName)) {
			sql += " and name like '%" + virName + "%' ";
		}
		return getSession().createQuery(sql.toString()).list();
	}

	@Override
	public List<Map<String, Object>> getVirByStartTime(String startTime,
													   String endTime) throws Exception {
		StringBuilder sql = new StringBuilder("");
		sql.append(" select vir.id CompanyId,vir.name CompanyName,org.id orgId,org.name orgName ");
		sql.append(" ,org.mettingClient Client,vir.settleType SettleType  ");
		sql.append(" from tb_virtualarchitecture vir  ");
		sql.append(" left join tb_organization org on vir.organizationId=org.id ");
		sql.append(" where DATE_FORMAT(vir.modifyTime,'%Y-%m-%d %T')>='" + startTime + "'  ");
		sql.append(" and DATE_FORMAT(vir.modifyTime,'%Y-%m-%d %T')<='" + endTime + "'  ");
		sql.append(" and org.mettingClient is not null  and org.mettingClient <> '' and vir.settleType<>0 ");
		List<Map<String, Object>> mapList = getJdbcTemplate().queryForList(sql.toString());
		return mapList;
	}

	/**
	 * 获取该项目下所有有效的企业
	 *
	 * @param orgId
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getVirInfoDtoByOrgId(String orgId, String virtName) {
		StringBuilder sql = new StringBuilder("");
		sql.append(" select vir.id virId,vir.name virName,vir.codeNumber virNumber,vir.address ");
		sql.append(" from tb_virtualarchitecture vir  ");
		sql.append(" where vir.organizationId=" + orgId + " and isEnabled='1' ");
		if (StringUtils.isNotEmpty(virtName)) {
			sql.append(" and vir.name like '%" + virtName + "%'");
		}
		List<Map<String, Object>> mapList = getJdbcTemplate().queryForList(sql.toString());
		return mapList;
	}

	@Override
	public List<Map<String, Object>> getVirtualDataByInfo(String orgId,
														  int dateType, String date, String endDate) {
		StringBuilder sql = new StringBuilder("");
		sql.append(" select org.id orgId,org.name orgName,ifnull(count(vir.id),0) sumVirCount ");
		sql.append(" ,ifnull(f.count,0) virCount,ifnull(d.count,0) emigCount ");
		sql.append(" ,ifnull(e.count,0) contExpireVirCount,ifnull(k.count,0) contDueVirCount ");
		sql.append(" ,ifnull(count(DISTINCT vir.id, IF(vir.`level` = 1, true, null)), 0) sumVirCountLevel1 ");
		sql.append(" ,ifnull(count(DISTINCT vir.id, IF(vir.`level` = 2, true, null)), 0) sumVirCountLevel2 ");
		sql.append(" ,ifnull(count(DISTINCT vir.id, IF((SELECT count(1) FROM tb_virtualarchitecture_agent WHERE id = vir.id ) > 0, true, null)), 0) sumVirCountRelation ");
		sql.append(" from tb_virtualarchitecture vir ");
		sql.append(" inner join tb_build bu on bu.id=vir.buildId and bu.isEnabled=1 ");
		sql.append(" inner join tb_organization org on org.id=vir.organizationId  and org.isEnabled=1 ");
		sql.append(" left join ( select v.organizationId id,ifnull(count(v.id),0) count from tb_virtualarchitecture v ");
		sql.append(" left join tb_organization o on o.id=v.organizationId ");
		sql.append("  where 1=1 ");
		if (dateType == 1) {//年度
			sql.append("  and year(v.createTime)='" + date + "'   ");
		} else if (dateType == 2) {//季度
			sql.append("  and year(v.createTime)='" + date + "'  and QUARTER(v.createTime)='" + endDate + "'  ");
		} else if (dateType == 3) {//月
			sql.append("  and year(v.createTime)='" + date + "'  and month(v.createTime)='" + endDate + "'   ");
		} else if (dateType == 4) {//周、日
			sql.append("  and date_format(v.createTime,'%Y-%m-%d')>='" + date + "'  and date_format(v.createTime,'%Y-%m-%d')<='" + endDate + "'   ");
		}
		sql.append(" group by v.organizationId ) f on f.id=org.id ");
		sql.append(" left join (select b.organizationId,ifnull(count(ent.virId),0) count from tb_enterprise ent ");
		sql.append(" left join tb_virtualarchitecture v on v.id=ent.virId ");
		sql.append(" left join tb_build b on b.id=ent.orgId ");
		sql.append(" where ent.state=2 and ent.`status`=2 and v.leaseStatus=0 ");
		if (dateType == 1) {//年度
			sql.append("  and year(ent.createTime)='" + date + "'   ");
		} else if (dateType == 2) {//季度
			sql.append("  and year(ent.createTime)='" + date + "'  and QUARTER(ent.createTime)='" + endDate + "'  ");
		} else if (dateType == 3) {//月
			sql.append("  and year(ent.createTime)='" + date + "'  and month(ent.createTime)='" + endDate + "'   ");
		} else if (dateType == 4) {//周、日
			sql.append("  and date_format(ent.createTime,'%Y-%m-%d')>='" + date + "'  and date_format(ent.createTime,'%Y-%m-%d')<='" + endDate + "'   ");
		}
		sql.append(" group by b.organizationId) d on d.organizationId=org.id ");

		sql.append(" left join (select v.organizationId,ifnull(COUNT(v.id),0) count from tb_virtualarchitecture v ");
		sql.append(" where DATE_FORMAT(v.contExpireTime,'%Y-%m-%d')>DATE_FORMAT(SYSDATE(),'%Y-%m-%d')  ");
		sql.append(" and DATEDIFF(DATE_FORMAT(v.contExpireTime,'%Y-%m-%d'),DATE_FORMAT(SYSDATE(),'%Y-%m-%d'))<=30 ");
		sql.append(" group by v.organizationId) e on e.organizationId=org.id ");

		sql.append("   left join (select v.organizationId,ifnull(COUNT(v.id),0) count from tb_virtualarchitecture v ");
		sql.append(" where DATE_FORMAT(v.contExpireTime,'%Y-%m-%d')<=DATE_FORMAT(SYSDATE(),'%Y-%m-%d') ");
		sql.append(" group by v.organizationId) k on k.organizationId=org.id ");

		sql.append(" where 1=1 and vir.type='1' and vir.isEnabled='1' and org.isEnabled='1' ");
		if (StringUtil.isNotEmpty(orgId)) {
			sql.append(" and vir.organizationId= '" + orgId + "' ");
		}
		sql.append(" group by vir.organizationId ");
		sql.append(" order by vir.organizationId desc ");
		List<Map<String, Object>> mapList = getJdbcTemplate().queryForList(sql.toString());
		return mapList;
	}

	@Override
	public List<Map<String, Object>> getVirtualByRoomId(String roomId) {
		String sql = "select id,name from tb_virtualarchitecture where find_in_set('" + roomId + "',REPLACE (roomIds,';',',')) and leaseStatus=1 and isEnabled=1 ";
		List<Map<String, Object>> mapList = getJdbcTemplate().queryForList(sql.toString());
		return mapList;
	}

	@Override
	public List<Map<String, Object>> getVirtualArchAgent() {
		String sql = " SELECT t1.`name` , ( SELECT SUM(b.area) FROM tb_virtualarchitecture_range a INNER JOIN tb_roomno b ON a.room_id = b.id WHERE a.id = t1.id ) AS room_area , ( SELECT GROUP_CONCAT(concat(d.`name`, '-', c.`name`, '楼', b.`name`)) FROM tb_virtualarchitecture_range a INNER JOIN tb_roomno b ON a.room_id = b.id INNER JOIN tb_floor c ON b.floorId = c.id INNER JOIN tb_build d ON c.buildId = d.id WHERE a.id = t1.id ) AS range_name , ( SELECT COUNT(1) FROM tb_virtualarchitecture_agent a INNER JOIN tb_virtualarchitecture b ON a.id = b.id WHERE a.agent_id = t1.id ) AS relation_count , ( SELECT GROUP_CONCAT(b.`name`) FROM tb_virtualarchitecture_agent a INNER JOIN tb_virtualarchitecture b ON a.id = b.id WHERE a.agent_id = t1.id ) AS relation_name FROM tb_virtualarchitecture t1 WHERE `level` = 2";
		List<Map<String, Object>> mapList = getJdbcTemplate().queryForList(sql.toString());
		return mapList;
	}
}
