package com.palmnest.dao.estateserve.impl;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.dao.estateserve.EnterpriseDao;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.model.EnterpriseInfo;
import com.palmnest.model.User;
import com.palmnest.model.repair.RepairBill;

@Repository("enterpriseDao")
public class EnterpriseDaoImpl extends GenericDaoHibernate<EnterpriseInfo, Integer> implements EnterpriseDao {
	public EnterpriseDaoImpl() {
		super(EnterpriseInfo.class);
	}

	@Override
	public Page getEnterpriseListByStatus(int status, int pageSize, int pageNo) throws Exception {
		StringBuilder sql = new StringBuilder("select * from tb_enterprise where status='0' and isEnabled='1' and state='1' ");
		return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
	}

	@Override
	public Page getEnterListByStatus(String floorId, String roomId, String virName, int pageSize, int pageNo) throws Exception {
		StringBuilder sql = new StringBuilder("select *  from tb_enterprise where (status='1' or status='2') and isEnabled='1'  and state='1'  ");
		if (StringUtils.isNotEmpty(floorId)) {

		}
		if (StringUtils.isNotEmpty(roomId)) {

		}
		if (StringUtils.isNotEmpty(virName)) {

		}
		sql.append(" order by createTime desc ");
		return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
	}

	@Override
	public List<RepairBill> getRepaiBillByCodes(String codes) throws Exception {
		String strHql = "from RepairBill where CODE in (" + codes + ")";
		List<RepairBill> list = getSession().createQuery(strHql).list();
		return list;
	}

	/**
	 * 获取企业 入驻/迁出 列表
	 *
	 * @param virName   企业名称
	 * @param type      1企业入驻2企业迁出
	 * @param pageSize
	 * @param pageNo
	 * @param isHisList 1-待处理列表;2-历史列表;
	 * @param orgId     项目id
	 * @return
	 * @throws Exception
	 */
	@Override
	public Page getEnterList(String virName, String type, int pageSize, int pageNo, int isHisList, String orgId) throws Exception {
		StringBuilder sql = new StringBuilder(" select ent.status status,ent.id,DATE_FORMAT(ent.createTime,'%Y-%m-%d %T') createTime,ent.virName,ent.orgId,org.`name` orgName,ent.floorIds,ent.floorNames,ent.roomIds  ");
		sql.append(" ,ent.roomNames,ent.creator,ifnull(ent.applyName,'') applyName,ifnull(ent.applyTel,'') applyTel,ent.enterNumber from tb_enterprise ent  ");
		sql.append(" left join tb_build build on build.id=ent.orgId  ");
		sql.append(" left join tb_organization org on org.id=build.organizationId  ");
		sql.append(" where ent.isEnabled='1' and ent.state='" + type + "' and org.id in (" + orgId + ") ");
		if (StringUtils.isNotEmpty(virName)) {
			sql.append(" and ent.virName like '%" + virName + "%' ");
		}
		if (isHisList == 1) {//待处理列表
			sql.append(" and ent.status='1' ");
		} else if (isHisList == 2) {//历史
			sql.append(" and ent.status in ('3','2') ");
		}
		sql.append(" order by ent.createTime desc ");
		return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
	}

	@Override
	public Page getEnterList(Map<String, Object> map, int pageNo, int pageSize) throws Exception {
		StringBuilder sql = new StringBuilder(" select ent.address,ent.email,ent.contExpireTime,ent.signingTime,ent.status status,ent.id,DATE_FORMAT(ent.createTime,'%Y-%m-%d %T') createTime,ent.virName,ent.orgId,build.`name` orgName,ent.floorIds,ent.floorNames,ent.roomIds  ");
		sql.append(" ,ent.roomNames,ent.creator,ifnull(ent.applyName,'') applyName,ifnull(ent.applyTel,'') applyTel,ent.enterNumber from tb_enterprise ent  ");
		sql.append(" left join tb_build build on build.id=ent.orgId  ");
		sql.append(" left join tb_organization org on org.id=build.organizationId  ");
		sql.append(" left join tb_audit_enterprise audit on audit.sourseId=ent.id ");
		sql.append(" where ent.isEnabled='1' ");
		//迁入或迁出
		if (map.get("type") != null) {
			sql.append(" and ent.state=" + map.get("type"));
		}
		//所属项目
		if (map.get("orgId") != null && StringUtils.isNotEmpty(map.get("orgId").toString())) {
			sql.append(" and org.id in (" + map.get("orgId") + ") ");
		}
		//企业名称
		if (map.get("virName") != null) {
			sql.append(" and ent.virName like '%" + map.get("virName") + "%' ");
		}

		if (map.get("isHisList") != null) {
			String isHisList = (String) map.get("isHisList");
			if ("1".equals(isHisList)) {//待处理列表
				sql.append(" and ent.status='1' ");
			} else if ("2".equals(isHisList)) {//历史
				sql.append(" and ent.status in ('3','2') ");
				if (map.get("userId") != null) {
					sql.append(" and audit.creator =" + map.get("userId"));
				}
			}
		}

		//申请时间
		if (map.get("applyTime") != null) {
			sql.append(" and date_format(ent.createTime,'%Y-%m-%d')='" + map.get("applyTime") + "'");
		}

		//申请人名称
		if (map.get("applyName") != null) {
			sql.append(" and ent.applyName like '%" + map.get("applyName") + "%' ");
		}

		//审核状态
		if (map.get("status") != null) {
			sql.append(" and ent.status= " + map.get("status"));
		}
		sql.append(" GROUP BY ent.id order by ent.createTime desc ");
		return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
	}

	@Override
	public EnterpriseInfo getEnterpriseDetail(Integer id) {
		String sql = "SELECT t1.*,t2.`name` AS buildName,t3.FULL_NAME AS optionName FROM tb_enterprise t1 INNER JOIN tb_build t2 ON t1.orgId=t2.id LEFT JOIN tb_app_user t3 ON t3.id=t1.modifier WHERE t1.isEnabled='1' AND t1.id=" + id;
		List<EnterpriseInfo> list = getSession().createSQLQuery(sql).addEntity(EnterpriseInfo.class).list();
		if (list != null) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * 待处理列表-----app端
	 * userId是tb_app_user中的主键
	 * status是系统中的状态，代表单据走到谁那里了
	 */
	@Override
	public Page getEnterListByUser(String virName, int userId, String floorIds, int pageSize, int pageNo, int state, int isHisList, int havePower)
			throws Exception {
		StringBuilder sql = new StringBuilder(" select ent.status status,ent.id,DATE_FORMAT(ent.createTime,'%Y-%m-%d %T') createTime,ent.virName,ent.orgId,org.`name` orgName,ent.floorIds,ent.floorNames,ent.roomIds  ");
		sql.append(" ,ent.roomNames,ent.creator,ifnull(ent.applyName,'') applyName,ifnull(ent.applyTel,'') applyTel,ent.enterNumber from tb_enterprise ent  ");
		sql.append(" left join tb_organization org on org.id=ent.orgId  ");
		sql.append(" left join tb_wxuser wu on wu.id=ent.creator  ");
		sql.append(" where ent.isEnabled='1'  and ent.state='" + state + "'  ");
		if (StringUtils.isNotEmpty(virName)) {
			sql.append(" and ent.virName like '%" + virName + "%' ");
		}
		if (isHisList == 1) {//待处理列表
			sql.append(" and ent.status not in ('3','4') ");
			//判断登录的人员的权限
			//havePower:1代表三种权限都包含;2代表有客服主管和客服权限；3代表客服主管和工程人员；4代表客服和工程人员；5客服主管；6客服；7工程人员
			if (havePower == 1) {//如果所有的权限都有，那登录进去后既要展示状态为0的单据，也要展示客服和跟进工程为他的数据
				sql.append(" and (ent.status='0' or ent.customerService='" + userId + "' or ent.engPerson='" + userId + "' ) ");
			} else if (havePower == 2) {//如果有客服主管和客服权限
				sql.append(" and (ent.status='0' or ent.customerService='" + userId + "' ) ");
			} else if (havePower == 3) {
				sql.append(" and (ent.status='0'  or ent.engPerson='" + userId + "' ) ");
			} else if (havePower == 4) {
				sql.append(" and (ent.customerService='" + userId + "' or ent.engPerson='" + userId + "' ) ");

			} else if (havePower == 5) {
				sql.append(" and ent.status='0' ");
			} else if (havePower == 6) {
				sql.append(" and  ent.customerService='" + userId + "' ");
			} else if (havePower == 7) {
				sql.append(" and  ent.engPerson='" + userId + "'  ");
			}
		} else if (isHisList == 2) {
			sql.append(" and ent.status in ('3','4') ");
			//历史列表展示的是操作过的人所能看到的历史数据
			//当为客服主管时，无需任何判断，展示所有该楼层下的申请即可
			//当为客服时，展示他操作过的即可
			if (havePower == 2) {//如果有客服主管和客服权限
				sql.append(" and (ent.customerService='" + userId + "' or ent.status='4') ");
			} else if (havePower == 3) {
				sql.append(" and (ent.engPerson='" + userId + "'  or ent.status='4' )");
			} else if (havePower == 4) {
				sql.append(" and (ent.customerService='" + userId + "' or ent.engPerson='" + userId + "' ) ");
			} else if (havePower == 6) {
				sql.append(" and  ent.customerService='" + userId + "' ");
			} else if (havePower == 7) {
				sql.append(" and  ent.engPerson='" + userId + "'  ");
			}
		}
		if (StringUtils.isNotEmpty(floorIds)) {
			floorIds = floorIds.substring(0, floorIds.length() - 1);
			String[] floor = floorIds.split(";");
			sql.append(" and ( ent.floorIds like '%" + floor[0] + ";%' ");
			for (int i = 1; i < floor.length; i++) {
				sql.append(" or  ent.floorIds like '%" + floor[i] + ";%' ");
			}
			sql.append(" ) ");
		}
		sql.append(" order by ent.createTime desc ");
		if (havePower == 8) {
			return pagedQueryByJdbcTemplate("select * from tb_enterprise where 1<>1 ", pageNo, pageSize);
		}
		return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
	}

	/**
	 * 待处理列表-----app端
	 * userId是tb_app_user中的主键
	 * status不是系统中的status，是用于区分用户的类型
	 */
	@Override
	public Page getEnterHisListByUser(String virName, int status, int userId, String floorIds, int pageSize, int pageNo, int state) throws Exception {
		StringBuilder sql = new StringBuilder(" select ent.status status,ent.id,DATE_FORMAT(ent.createTime,'%Y-%m-%d %T') createTime,ent.virName,ent.orgId,org.`name` orgName,ent.floorIds,ent.floorNames,ent.roomIds  ");
		sql.append(" ,ent.roomNames,ent.creator,ifnull(ent.applyName,'') applyName,ifnull(ent.applyTel,'') applyTel,ent.enterNumber from tb_enterprise ent  ");
		sql.append(" left join tb_organization org on org.id=ent.orgId  ");
		sql.append(" left join tb_wxuser wu on wu.id=ent.creator  ");
//		sql.append(" left join tb_user u on u.id=wu.userId ");
		sql.append(" where ent.isEnabled='1'   and ent.state='" + state + "'  ");
		sql.append(" and ent.status in ('3','4') ");
		if (userId != 0) {
			if (status == 1) {//跟进的客服已选择，展示在客服人员的待处理列表里
				sql.append(" and ent.customerService='" + userId + "' ");
			} else if (status == 2) {//跟进工程人员，展示在工程人员的待处理列表里
				sql.append(" and ent.engPerson='" + userId + "' ");
			}
		}
		if (StringUtils.isNotEmpty(virName)) {
			sql.append(" and ent.virName like '%" + virName + "%' ");
		}
		if (StringUtils.isNotEmpty(floorIds)) {
			floorIds = floorIds.substring(0, floorIds.length() - 1);
			String[] floor = floorIds.split(";");
			sql.append(" and ( ent.floorIds like '%" + floor[0] + ";%' ");
			for (int i = 1; i < floor.length; i++) {
				sql.append(" or  ent.floorIds like '%" + floor[i] + ";%' ");
			}
			sql.append(" ) ");
		}
		sql.append(" order by ent.createTime desc ");
		return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
	}

	@Override
	public String isHavePower(String userId, int sysCode) throws Exception {
		StringBuilder sql = new StringBuilder(" select us.FULL_NAME userName,us.TELEPHONE userTel,rl.NAME roleName,fuc.SYSTEMCODE fucCode,fuc.FUNCTION_NAME fucName from tb_app_user us");
		sql.append(" left join tr_app_user_role ur on us.id=ur.USER_ID ");
		sql.append(" left join tb_app_role rl on rl.id=ur.role_id ");
		sql.append(" left join tr_app_role_function fu on fu.ROLEID=ur.ROLE_ID ");
		sql.append(" left join tb_app_function fuc on fuc.id=fu.FUNCTION_ID ");
		sql.append(" where us.ISENABLED='1' and us.id=" + userId + " and fuc.SYSTEMCODE=" + sysCode);
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		if (list != null && list.size() > 0) {
			return "1";//1代表有权限
		}
		return "0";
	}

	@Override
	public List<Map<String, Object>> getPower(String floors, int sysCode) throws Exception {
		StringBuilder sql = new StringBuilder(" select DISTINCT us.device_type deviceType,us.device_no deviceNo,us.id usId,us.FULL_NAME userName,us.TELEPHONE userTel,fuc.SYSTEMCODE fucCode,fuc.FUNCTION_NAME fucName from tb_app_user us");
		sql.append(" left join tr_app_user_role ur on us.id=ur.USER_ID ");
		sql.append(" left join tb_app_role rl on rl.id=ur.role_id ");
		sql.append(" left join tr_app_role_function fu on fu.ROLEID=ur.ROLE_ID ");
		sql.append(" left join tb_app_function fuc on fuc.id=fu.FUNCTION_ID ");
		sql.append(" left join tr_app_user_floor uf on uf.user_id=us.id ");
		sql.append(" where us.ISENABLED='1' and fuc.SYSTEMCODE=" + sysCode);
		sql.append(" and us.USERNAME<>'admin' ");
		if (StringUtils.isNotEmpty(floors)) {
			String[] floor = floors.split(";");
			String floorIds = "";
			for (int i = 0; i < floor.length; i++) {
				floorIds = floorIds + "'" + floor[i] + "',";
			}
			if (StringUtils.isNotEmpty(floorIds)) {
				floorIds = floorIds.substring(0, floorIds.length() - 1);
				sql.append(" and uf.floor_id in (" + floorIds + ") ");
			}
		} else {
			return null;
		}
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		return list;
	}

	@Override
	public List<Map<String, Object>> getPowerFloor(int userId, int sysCode)
			throws Exception {
		StringBuilder sql = new StringBuilder(" select DISTINCT us.id,us.FULL_NAME userName,us.TELEPHONE userTel,fuc.SYSTEMCODE fucCode,fuc.FUNCTION_NAME fucName,uf.floor_id floorId from tb_app_user us");
		sql.append(" left join tr_app_user_role ur on us.id=ur.USER_ID ");
		sql.append(" left join tb_app_role rl on rl.id=ur.role_id ");
		sql.append(" left join tr_app_role_function fu on fu.ROLEID=ur.ROLE_ID ");
		sql.append(" left join tb_app_function fuc on fuc.id=fu.FUNCTION_ID ");
		sql.append(" left join tr_app_user_floor uf on uf.user_id=us.id ");
		sql.append(" left join tb_floor flo on flo.id=uf.floor_id ");
		sql.append(" where  fuc.SYSTEMCODE=" + sysCode);
		sql.append(" and  us.id=" + userId);
		sql.append(" and  us.ISENABLED='1' ");
		sql.append(" and  flo.ISENABLED=1 ");
		sql.append(" order by  flo.id ");
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		return list;
	}

	/**
	 * @param userId 用户id
	 * @param type   1-入驻 2-迁出
	 * @param port   当type为2时 port:1微信2app
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<EnterpriseInfo> getEnterInfoList(int userId, int type, String port, String orgId) throws Exception {
//		String strHql="from EnterpriseInfo where isEnabled='1'  and state='"+type+"'  and creator="+userId+" order by createTime desc";
//		List<EnterpriseInfo> list=getSession().createQuery(strHql).list();
		StringBuilder sql = new StringBuilder("SELECT t1.*  FROM tb_enterprise t1 ");
		sql.append(" left join tb_build build on build.id=t1.orgId  ");
		sql.append(" left join tb_organization org on org.id=build.organizationId  ");
		sql.append("  WHERE t1.isEnabled='1' AND t1.state = " + type + " AND t1.creator=" + userId);
		if (type == 2 && StringUtils.isNotBlank(port)) {
			sql.append(" AND emigNewWay ='" + port + "'");
		}
		if (StringUtil.isNotEmpty(orgId)) {
			sql.append(" AND org.id='" + orgId + "'");
		}
		sql.append("   order by createTime desc ");
		List<EnterpriseInfo> list = getSession().createSQLQuery(sql.toString()).addEntity(EnterpriseInfo.class).list();
		return list;
	}

	@Override
	public List<Map<String, Object>> getRepairNumberList(String repairNumbers)
			throws Exception {
		StringBuilder sql = new StringBuilder("");
		sql.append(" select re.id,re.`CODE` repairCode,re.repair_type repairType,item.itemname  ");
		sql.append(" from tb_repair_bills re  ");
		sql.append(" left join tb_dictionary_item item on item.id=re.repair_type where 1=1 ");
		if (StringUtils.isNotEmpty(repairNumbers)) {
			sql.append(" and re.code in (" + repairNumbers + ") ");
		}
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		return list;
	}

	@Override
	public List<EnterpriseInfo> getEnterListByBand() throws Exception {
		String strHql = "from EnterpriseInfo where isEnabled='1'  and state='1' and status<>'3' ";
		List<EnterpriseInfo> list = getSession().createQuery(strHql).list();
		return list;
	}

	@Override
	public List<EnterpriseInfo> getEnterListByVirId(String virId)
			throws Exception {
		String strHql = "from EnterpriseInfo where isEnabled='1'  and state='2' and status<>'3' and virId=" + virId;
		List<EnterpriseInfo> list = getSession().createQuery(strHql).list();
		return list;
	}

	@Override
	public List<Map<String, Object>> getPower(int sysCode) throws Exception {
		StringBuilder sql = new StringBuilder(" select DISTINCT us.device_type deviceType,us.device_no deviceNo ");
		sql.append(" ,us.id usId,us.FULL_NAME userName,us.TELEPHONE userTel,fuct.SYSTEMCODE fucCode,fuct.FUNCTION_NAME fucName ");
		sql.append("  from tb_app_user us  ");
		sql.append("  left join tr_app_user_role rl on rl.user_id=us.ID ");
		sql.append("  left join tb_app_role ro on rl.role_id=ro.id  ");
		sql.append("  left join tr_app_role_function fuc on fuc.roleid=ro.id    ");
		sql.append("  left join tb_app_function fuct on fuct.id=fuc.FUNCTION_ID  ");
		sql.append("  where fuct.SYSTEMCODE= " + sysCode + " and  us.ISENABLED='1'  and us.USERNAME<>'admin'  ");
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		return list;
	}


	@Override
	public List<Map<String, Object>> getPowerByOrg(int orgId, int sysCode) throws Exception {
		StringBuilder sql = new StringBuilder(" select DISTINCT us.device_type deviceType,us.device_no deviceNo ");
		sql.append(" ,us.id usId,us.FULL_NAME userName,us.TELEPHONE userTel,fuct.SYSTEMCODE fucCode,fuct.FUNCTION_NAME fucName ");
		sql.append("  from tb_app_user us  ");
		sql.append("  left join tr_app_user_role rl on rl.user_id=us.ID ");
		sql.append("  left join tb_app_role ro on rl.role_id=ro.id  ");
		sql.append("  left join tr_app_role_function fuc on fuc.roleid=ro.id    ");
		sql.append("  left join tb_app_function fuct on fuct.id=fuc.FUNCTION_ID  ");
		sql.append("  left join tr_app_user_orgnization tauo ON tauo.user_id=us.id ");
		sql.append("  where fuct.SYSTEMCODE= " + sysCode + " and  us.ISENABLED='1'  and us.USERNAME<>'admin' and tauo.org_id=" + orgId + " ");
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		return list;
	}


	@Override
	public List<Map<String, Object>> getFileList(String type, String orgId, String fileIds) {
		StringBuilder sql = new StringBuilder("SELECT fileName,fileUrl,id FROM tb_model WHERE type = " + type);
		if (StringUtils.isNotBlank(orgId)) {
			sql.append(" and orgId in(" + orgId + ")");
		}
		if (StringUtils.isNotBlank(fileIds)) {
			sql.append(" and id in(" + fileIds + ")");
		}
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		return list;
	}

	@Override
	public List<EnterpriseInfo> getUnhandleOrder(int virId) {
		String sql = "from EnterpriseInfo where isEnabled='1'  and state='2' and status='1' and virId=" + virId;
		List<EnterpriseInfo> list = getSession().createQuery(sql).list();
		return list;
	}

	@Override
	public Integer getEnterprisePendingNum(int state, String orgIds) {

		StringBuilder sql = new StringBuilder(" select COUNT(DISTINCT(ent.id)) from tb_enterprise ent  ");
		sql.append(" left join tb_build build on build.id=ent.orgId  ");
		sql.append(" left join tb_organization org on org.id=build.organizationId  ");
		sql.append(" where ent.isEnabled='1' and ent. STATUS = '1' ");
		sql.append(" and ent.state ='").append(state).append("'");
		sql.append(" and org.id IN (").append(orgIds).append(")");

		String count = getSession().createSQLQuery(sql.toString()).uniqueResult().toString();
		return Integer.parseInt(count);
	}
}
