package com.palmnest.dao.notice.impl;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.core.util.CollectionUtils;
import com.palmnest.application.core.util.hangdian.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.palmnest.application.bean.Page;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.dao.notice.AppNoticeDao;
import com.palmnest.model.notice.AppNoticeModel;
import com.palmnest.model.notice.MobileConfigModel;

@Repository("appNoticeDao")
public class AppNoticeDaoImpl extends GenericDaoHibernate<AppNoticeModel, Integer> implements AppNoticeDao{

	public AppNoticeDaoImpl() {
		super(AppNoticeModel.class);

	}

	
	/**
	 * 原来的sql---2019-07-29update
	 */
	@Override
	public Page<AppNoticeModel,String> getDataList(Map<String, Object> map,int pageNo, int pageSize) throws Exception {

		StringBuffer sbf = new StringBuffer();
		sbf.append("  select '' roleId,0 isApproval,0 isPublish,'' roleName,apn.approval_type approvalType,apn.orgId, apn.content_type,apn.orgIds,apn.id,apn.title,apn.content,apn.content_txt,apn.url_address,apn.state,apn.approval_user,apn.summary_info,apn.cover_url,apn.notice_type,(if(IFNULL(apn.order_num,0) >0,1,0)) orderNum");
		sbf.append("  ,DATE_FORMAT(approval_time,'%Y/%m/%d %T') approval_time,DATE_FORMAT(	apn.createTime,	'%Y/%m/%d %T') createTime ,(if(IFNULL(apn.order_num,0) >0,apn.order_num,0)) orderNo ");
		sbf.append("  ,apn.creator,apn.modifier,DATE_FORMAT( apn.modifyTime,'%Y/%m/%d %T') modifyTime,apn.isEnabled,aus.FULL_NAME fullName,aus.FULL_NAME USERNAME   ");
		sbf.append("  from tb_app_notice apn  ");
		sbf.append("  left join tb_app_user aus on apn.creator=aus.id  ");
		sbf.append("  where 1=1 and apn.isEnabled <> 0");
		if(map.containsKey("from")&&"app".equals(map.get("from"))){
			sbf.append(" and apn.isEnabled='2' ");
		}
		if(map.get("c_beginTime")!=null){
			sbf.append(" and createTime>='");
			sbf.append(map.get("c_beginTime").toString()+" 00:00:00'");
		}
		if(map.get("c_endTime")!=null){
			sbf.append(" and createTime<='");
			sbf.append(map.get("c_endTime").toString()+" 23:59:59'");		
		}
		if(map.get("a_beginTime")!=null){
			sbf.append(" and approval_time>='");
			sbf.append(map.get("a_beginTime").toString()+" 00:00:00'");
		}
		if(map.get("a_endTime")!=null){
			sbf.append(" and approval_time<='");
			sbf.append(map.get("a_endTime").toString()+" 23:59:59'");
		}
		if(map.get("state")!=null){
			sbf.append(" and state="+map.get("state").toString());
		}else {
			sbf.append(" and state !=3");//去掉原文链接
		}
		if(map.get("noticeType")!=null){
			sbf.append(" and notice_type ="+map.get("noticeType"));
		}
		if(map.get("positionType")!=null){
			sbf.append(" and position_type in (0,"+map.get("positionType")+")");
		}
		if(map.get("positionTypes")!=null){
			sbf.append(" and position_type in ("+map.get("positionTypes")+")");
		}
        if(map.get("isEnabled")!=null){
            sbf.append(" and apn.isEnabled="+map.get("isEnabled"));
        }
        if(map.get("title")!=null){
            sbf.append(" and title like '%"+map.get("title")+"%'");
        }
		if(map.get("orgId")!=null){
			sbf.append(" and (orgId in ("+map.get("orgId")+")  or ( find_in_set("+map.get("orgId")+",orgIds ) and apn.state=1)  )");
		}

		if(map.get("orgIds")!=null){
			//系统管理员及以上看到的是所有的
			if(map.containsKey("userType")&&map.get("userType")!=null&&Integer.parseInt(map.get("userType").toString())<=2){
//				sbf.append(" and ( orgId in ("+map.get("orgIds")+")  or  apn.creator='"+map.get("userId")+"'  )");
			}else{
				//项目管理员及以下的，需要
				sbf.append(" and (orgId in ("+map.get("orgIds")+")  or ( find_in_set("+map.get("orgIds")+",orgIds ) and apn.state=1)  )");
			}
		}
		
		//多级审核下的过滤条件
		if(null != map.get("approvalType")){
			sbf.append(" and  apn.approval_type="+map.get("approvalType"));
		}
		
		sbf.append(" ORDER BY orderNo DESC,createTime DESC ,apn.id DESC");

		return pagedQueryByJdbcTemplate(sbf.toString(), pageNo, pageSize);

	}


	@Override
	public Page<AppNoticeModel,String> getNewDataList(Map<String, Object> map,int pageNo, int pageSize) throws Exception {

		StringBuffer sbf = new StringBuffer();
		sbf.append("  SELECT apn.content_type, apn.orgIds, apn.id noticeId,(case when apnd.id is null then 1 else 2 end) sourceType, ifnull(apnd.id,apn.id) id, ifnull(apnd.title,apn.title) title, ifnull(apnd.content,apn.content) content,(if(IFNULL(apn.order_num,0) >0,1,0)) orderNum, ");
		sbf.append("  ifnull(apnd.contentTxt,apn.content_txt) content_txt, ifnull(apnd.url_address,apn.url_address) url_address, apn.state, apn.approval_user, ifnull(apnd.summaryInfo,apn.summary_info) summary_info,(if(IFNULL(apn.order_num,0) >0,apn.order_num,0)) orderNo,   ");
		sbf.append("  ifnull(apnd.coverUrl,apn.cover_url) cover_url, apn.notice_type, DATE_FORMAT( approval_time, '%Y/%m/%d %T' ) approval_time, ifnull(DATE_FORMAT( apnd.createTime, '%Y/%m/%d %T' ),DATE_FORMAT( apn.createTime, '%Y/%m/%d %T' )) createTime,   ");
		sbf.append("   ifnull(apnd.creator,apn.creator) creator, apn.modifier, DATE_FORMAT( apn.modifyTime, '%Y/%m/%d %T' ) modifyTime, apn.isEnabled, aus.FULL_NAME fullName,aus.FULL_NAME USERNAME   ");
		sbf.append("  from tb_app_notice apn  ");
		sbf.append("   LEFT JOIN tb_app_notice_detail apnd ON apnd.sourceId = apn.id AND apnd.isEnabled <> 0   ");
		sbf.append("  left join tb_app_user aus on apn.creator=aus.id  ");
		sbf.append("  where 1=1 AND apn.isEnabled = 2 ");
		//原先0为删除 1代表下线,2代表上线
		if(map.get("c_beginTime")!=null){
			sbf.append(" and createTime>='");
			sbf.append(map.get("c_beginTime").toString()+" 00:00:00'");
		}
		if(map.get("c_endTime")!=null){
			sbf.append(" and createTime<='");
			sbf.append(map.get("c_endTime").toString()+" 23:59:59'");
		}
		if(map.get("a_beginTime")!=null){
			sbf.append(" and approval_time>='");
			sbf.append(map.get("a_beginTime").toString()+" 00:00:00'");
		}
		if(map.get("a_endTime")!=null){
			sbf.append(" and approval_time<='");
			sbf.append(map.get("a_endTime").toString()+" 23:59:59'");
		}
		if(map.get("state")!=null){
			sbf.append(" and state="+map.get("state").toString());
		}else {
			sbf.append(" and state !=3");//去掉原文链接
		}
		if(map.get("noticeType")!=null){
			sbf.append(" and notice_type ="+map.get("noticeType"));
		}
		if(map.get("positionType")!=null){
			sbf.append(" and position_type in (0,"+map.get("positionType")+")");
		}

		if(map.get("orgIds")!=null && StringUtils.isNotEmpty(map.get("orgIds").toString())){
			//系统管理员及以上看到的是所有的
			if(map.containsKey("userType")&&map.get("userType")!=null&&Integer.parseInt(map.get("userType").toString())<=2){
//				sbf.append(" and ( orgId in ("+map.get("orgIds")+")  or  apn.creator='"+map.get("userId")+"'  )");
			}else{
				//项目管理员及以下的，需要
				sbf.append(" and (orgId in ("+map.get("orgIds")+")  or ( find_in_set("+map.get("orgIds")+",orgIds ) and apn.state=1)  )");
			}
		}
        sbf.append("  ORDER BY orderNo DESC,apn.createTime DESC,id DESC ");

		return pagedQueryByJdbcTemplate(sbf.toString(), pageNo, pageSize);
		
	}
	
	@Override
	public AppNoticeModel getDataById(int id) throws Exception {

		String sql="from  AppNoticeModel where id=?";

		return (AppNoticeModel)getSession().createQuery(sql).setInteger(0, id).uniqueResult();
		
	}

	@Override
	public Integer getTotal(String orgIds) {
		String sql="SELECT COUNT(t.id) total" + 
				" FROM tb_app_notice t" + 
				" WHERE state = 0 AND isEnabled <> 0 AND position_type IN (0,1) AND orgId IN ("+orgIds+")";
		return ((BigInteger)getSession().createSQLQuery(sql).uniqueResult()).intValue();
	}

	@Override
	public List<AppNoticeModel> getByType(Integer noticeType,String positionType,String orgIds) {
		String sql="select * from tb_app_notice where notice_type=? and position_type in (?,0,6) ";

		if (StringUtils.isNotBlank(orgIds)){
			sql += " and (orgId in ("+orgIds+") or ( find_in_set("+orgIds+",orgIds ) and state=1) )";
		}

		sql += " AND isEnabled =2  and state=1 order by order_num ";
		return getSession().createSQLQuery(sql).addEntity(AppNoticeModel.class).setInteger(0, noticeType).setString(1, positionType).list();
	}

	@Override
	public Integer getMaxSortNum() {
		StringBuffer sql = new StringBuffer();
		sql.append("  SELECT MAX(IFNULL(order_num,0)) max FROM tb_app_notice  ");
		sql.append("  WHERE  isEnabled <> 0");

		return  ((BigInteger)getSession().createSQLQuery(sql.toString()).uniqueResult()).intValue();
	}

}
