package com.zcloud.controller.notice;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.notice.NoticeLogService;
import com.zcloud.service.notice.ServiceNoticeService;
import com.zcloud.service.system.FileUploadLogService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.DateUtil;
import com.zcloud.util.Jurisdiction;
import com.zcloud.util.ObjectExcelView;
import com.zcloud.util.Tools;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * 说明：通知公告
 * 作者：luoxiaobao
 * 官网：www.qdkjchina.com
 */
@Controller
@RequestMapping("/service/notice")
public class ServiceNoticeController extends BaseController {

	@Autowired
	private ServiceNoticeService noticeService;
	@Autowired
	private NoticeLogService noticelogService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private FileUploadLogService fileUploadLogService;
	/**新增
	 * @param
	 * @throws Exception
	 */
//	@RequestMapping(value="/add")
//	// @RequiresPermissions("serviceNotice:add")
//	@ResponseBody
//	public Object add() throws Exception{
//		Map<String,Object> map = new HashMap<String,Object>();
//		String errInfo = "success";
//		PageData pd = new PageData();
//		pd = this.getPageData();
//		pd.put("NOTICE_ID", this.get32UUID());							//主键
//		pd.put("ISDELETE", "0");	//删除标识（0：有效   1：删除）
//		pd.put("ISTOP", "0");	//是否置顶（0否 1是）
//		pd.put("STATUS", "0");	//状态（0：未发布   1：发布）
//		pd.put("USERNAME", Jurisdiction.getUsername());					//用户名
//		pd.put("CREATOR", Jurisdiction.getName());						//发布人
//		pd.put("CREATTIME", DateUtil.date2Str(new Date()));					//发布时间
//		pd.put("ISALL", pd.get("ISALL"));
//		noticeService.save(pd);
////		String corpAlls = "";
//		StringBuffer corpAlls =new StringBuffer();
//		if("no".equals(pd.get("ISALL"))) {//选择了部分企业通知
//			corpAlls.append(pd.get("corpInfoIds").toString());
//		}else {
//			//获取所有的企业
//			Page page2 = new Page();
//			List<PageData>	corpInfoList = corpinfoService.list(page2);	//列出CorpInfo列表
//			for (PageData pageData : corpInfoList) {
//				corpAlls.append(pageData.getString("CORPINFO_ID")+",");
//			}
//		}
//		String[] corpIds = corpAlls.toString().split(",");
//		PageData notCorpPd = new PageData();
//		List<Map<String, Object>> list = new ArrayList<>();
//		Map<String , Object> map2 = new HashMap<>();
//		for(int i =0; i<corpIds.length; i++) {
//			map2 = new HashMap<>();
//			map2.put("noticeId", pd.get("NOTICE_ID"));
//			map2.put("corpId", corpIds[i]);
//			map2.put("TYPE", "0");
//			map2.put("CREATOR", DateUtil.date2Str(new Date()));
//			list.add(map2);
//		}
//		notCorpPd.put("list", list);
//		noticeService.saveNotAndCorp(notCorpPd);
//		map.put("result", errInfo);
//		return map;
//	}

	/**去编辑页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goAdd")
	// @RequiresPermissions("serviceNotice:add")
	@ResponseBody
	public Object goAdd() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
//		List<PageData> precinctList = precinctService.listAll(pd);//列出所有管理区域
//		map.put("precinctList", precinctList);
		map.put("result", errInfo);
		return map;
	}

	/**删除
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	// @RequiresPermissions("serviceNotice:del")
	@ResponseBody
	public Object delete() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		noticeService.delete(pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	// @RequiresPermissions("serviceNotice:edit")
	@ResponseBody
	public Object edit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("ISTOP", "0");	//是否置顶（0否 1是）
		pd.put("STATUS", "0");	//状态（0：未发布   1：发布）
//		deleteNotAndCorpByNotId
		if("no".equals(pd.get("ISALL"))) {//选择了部分企业通知
			if(!Tools.isEmpty(pd.get("corpInfoIds").toString())) {//有选择企业id传入
				noticeService.deleteNotAndCorpByNotId(pd);
				String corpAlls =pd.get("corpInfoIds").toString();
				String[] corpIds = corpAlls.split(",");
				PageData notCorpPd = new PageData();
				List<Map<String, Object>> list = new ArrayList<>();
				Map<String , Object> map2 = new HashMap<>();
				for(int i =0; i<corpIds.length; i++) {
					map2 = new HashMap<>();
					map2.put("noticeId", pd.get("NOTICE_ID"));
					map2.put("corpId", corpIds[i]);
					list.add(map2);
				}
				notCorpPd.put("list", list);
				noticeService.saveNotAndCorp(notCorpPd);
			}
		}
		noticeService.edit(pd);
		map.put("result", errInfo);
		return map;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
//		String USERNAME = Jurisdiction.getUsername();					//用户名
//		String DEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//		if("".equals(DEPARTMENT_ID) || "无权".equals(DEPARTMENT_ID)){
//			pd.put("DEPARTMENT_ID","");									//根据部门ID过滤
//			if(!"admin".equals(USERNAME))pd.put("USERNAME", USERNAME);	//非admin用户时
//		}else{
//			pd.put("DEPARTMENT_ID", DEPARTMENT_ID);
//			pd.put("ORUSERNAME", USERNAME);
//		}
		page.setPd(pd);
		List<PageData>	varList = noticeService.list(page);	//列出Notice列表

		List<PageData> countNotList = new ArrayList<>();
		if(varList.size()>0) {
			String [] notids = new String [varList.size()];
			for(int i=0;i<varList.size();i++) {
				PageData pageData =varList.get(i);
				notids[i] = pageData.getString("NOTICE_ID");
			}
			PageData pd2 = new PageData();
			pd2.put("notIdsVal", notids);
			Page page2 = new Page();
			page2.setPd(pd2);
			countNotList = noticeService.getTypeCountByNotId(page2);
		}

		map.put("varList", varList);
		map.put("countNotList",countNotList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	/**读取最新的一条
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/getNewest")
	@ResponseBody
	public Object getNewest(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String USERNAME = Jurisdiction.getUsername();					//用户名
		String DEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
		if("".equals(DEPARTMENT_ID) || "无权".equals(DEPARTMENT_ID)){
			pd.put("DEPARTMENT_ID","");									//根据部门ID过滤
			if(!"admin".equals(USERNAME))pd.put("USERNAME", USERNAME);	//非admin用户时
		}else{
			pd.put("DEPARTMENT_ID", DEPARTMENT_ID);
			pd.put("ORUSERNAME", USERNAME);
		}
		page.setPd(pd);
		page.setShowCount(1);
		List<PageData>	varList = noticeService.list(page);	//列出Notice列表
		String notice = "", content = "",uname = "",ctime = "", noticeid = "1";
		if(varList.size() > 0) {
			noticeid = varList.get(0).getString("NOTICE_ID");	//ID
			notice = varList.get(0).getString("SYNOPSIS");		//简介
			content = varList.get(0).getString("CONTENT");		//内容
			uname = varList.get(0).getString("UNAME");			//发布人
			ctime = varList.get(0).getString("CTIME");			//创建时间
		}
		map.put("noticeid", noticeid);
		map.put("notice", notice);
		map.put("content", content);
		map.put("uname", uname);
		map.put("ctime", ctime);
		map.put("result", errInfo);
		return map;
	}

	 /**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	@ResponseBody
	public Object goEdit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = noticeService.findById(pd);	//根据ID读取
		List<PageData> notAndCorpList = new ArrayList<>();
		if("no".equals(pd.get("ISALL"))) {
			notAndCorpList = noticeService.getNotAndCorpByNotId(pd);//获取公告和显示企业信息关系
		}
		map.put("pdCorpList", notAndCorpList);
		map.put("pd", pd);

		PageData pd2 = new PageData();
		pd2.put("USER_ID", Jurisdiction.getUSER_ID());
		PageData userPd = usersService.findById(pd2);
		if(!Tools.isEmpty(userPd.get("ISMAIN"))) {
			if("1".equals(userPd.get("ISMAIN"))) {
				//获取平台公告的关系表,查看是存在关系
				PageData pdNotCorp = new PageData();
				pdNotCorp.put("NOTICE_ID", pd.getString("NOTICE_ID"));
				pdNotCorp.put("CORP_INFO_ID", Jurisdiction.getCORPINFO_ID());
				pdNotCorp.put("TYPE", "1");
				pdNotCorp.put("NOTICE_ID", pd.getString("NOTICE_ID"));
				pdNotCorp.put("CREATOR", DateUtil.date2Str(new Date()));
				List<PageData> noticeCorpInfo = noticeService.findNoticeCorpInfoById(pdNotCorp);//根据公告id企业id，获取关系信息
				if(noticeCorpInfo.size()>0) {//如果有关系信息,进去修改
					noticeService.editCorpInfo(pdNotCorp);
				}else {//没有关系信息,新增关系信息
					PageData notCorpPd = new PageData();
					notCorpPd.put("NOTICE_CORP_ID", this.get32UUID());
					notCorpPd.put("NOTICE_ID", pd.get("NOTICE_ID"));
					notCorpPd.put("CORP_INFO_ID", Jurisdiction.getCORPINFO_ID());
					notCorpPd.put("TYPE", "1");
					notCorpPd.put("CREATOR", DateUtil.date2Str(new Date()));
					noticeService.saveNotAndCorp(notCorpPd);
				}
//				PageData pdCorp = new PageData();
//				pdCorp.put("TYPE", "1");
//				pdCorp.put("NOTICE_ID", pd.getString("NOTICE_ID"));
//				pdCorp.put("CREATOR", DateUtil.date2Str(new Date()));
//				pdCorp.put("CORP_INFO_ID", Jurisdiction.getCORPINFO_ID());
//				noticeService.editCorpInfo(pdCorp);
			}
		}
//		List<PageData> precinctList = precinctService.listAll(pd2);//列出所有管理区域
//		map.put("precinctList", precinctList);
		map.put("result", errInfo);
		return map;
	}

	/**变更状态
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/changeStatus")
	// @RequiresPermissions("serviceNotice:edit")
	@ResponseBody
	@Transactional //开启事物
	public Object changeStatus() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = noticeService.findById(pd);
		if(pd.get("STATUS").equals("1")) {
			pd.put("STATUS",0);
			pd.put("OPERATOR", Jurisdiction.getUsername());	//操作人
			pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//操作时间
			noticeService.edit(pd);
			this.noticelogService.deleteAllByNoticeId(pd);
		}else {
			pd.put("STATUS",1);
			pd.put("OPERATOR", Jurisdiction.getUsername());	//操作人
			pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//操作时间
			noticeService.edit(pd);
			List<PageData> userList = usersService.listAllUser(pd);//列出所有用户
			for (PageData user : userList) {
				PageData log = new PageData();
				log.put("NOTICELOG_ID", this.get32UUID());							//主键
				log.put("USER_ID", user.getString("USER_ID"));
				log.put("NOTICE_ID", pd.getString("NOTICE_ID"));
				log.put("NOTICE", pd.getString("SYNOPSIS"));
				log.put("STATUS", 0);
				log.put("CREATOR", Jurisdiction.getName());						//发布人
				log.put("CREATTIME", DateUtil.date2Str(new Date()));					//发布时间
				log.put("ISDELETE", "0");	//删除标识（0：有效   1：删除）.
				this.noticelogService.save(log);
			}
		}
		map.put("result", errInfo);
		return map;
	}

	/**变更置顶状态
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/changeIsTop")
	// @RequiresPermissions("serviceNotice:edit")
	@ResponseBody
	public Object changeIsTop() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData notice = noticeService.findById(pd);
		notice.put("ISTOP", pd.getString("ISTOP"));
		this.noticeService.edit(notice);
		map.put("result", errInfo);
		return map;
	}

	 /**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	// @RequiresPermissions("serviceNotice:del")
	@ResponseBody
	public Object deleteAll() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String DATA_IDS = pd.getString("DATA_IDS");
		if(Tools.notEmpty(DATA_IDS)){
			String ArrayDATA_IDS[] = DATA_IDS.split(",");
			noticeService.deleteAll(ArrayDATA_IDS);
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	 /**导出到excel
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/excel")
	// @RequiresPermissions("toExcel")
	public ModelAndView exportExcel() throws Exception{
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		Map<String,Object> dataMap = new HashMap<String,Object>();
		List<String> titles = new ArrayList<String>();
		titles.add("部门ID");	//1
		titles.add("用户名");	//2
		titles.add("发布人");	//3
		titles.add("发布时间");	//4
		titles.add("公告简介");	//5
		titles.add("公告内容");	//6
		titles.add("是否全显");	//7
		dataMap.put("titles", titles);
		List<PageData> varOList = noticeService.listAll(pd);
		List<PageData> varList = new ArrayList<PageData>();
		for(int i=0;i<varOList.size();i++){
			PageData vpd = new PageData();
			vpd.put("var1", varOList.get(i).getString("DEPARTMENT_ID"));	    //1
			vpd.put("var2", varOList.get(i).getString("USERNAME"));	    //2
			vpd.put("var3", varOList.get(i).getString("UNAME"));	    //3
			vpd.put("var4", varOList.get(i).getString("CTIME"));	    //4
			vpd.put("var5", varOList.get(i).getString("SYNOPSIS"));	    //5
			vpd.put("var6", varOList.get(i).getString("CONTENT"));	    //6
			vpd.put("var7", varOList.get(i).getString("ISALL"));	    //7
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv,dataMap);
		return mv;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/listByCorpId")
	@ResponseBody
	public Object listByCorpId(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
//		pd.put("CORP_INFO_ID", Jurisdiction.getCORPINFO_ID());
		page.setPd(pd);
		List<PageData> varList = noticeService.getNotAndCorpByCorpId(page);//获取发给这个企业的公告

		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	/**列表 显示企业阅读情况
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/listCorpRead")
	@ResponseBody
	public Object listCorpRead(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		page.setPd(pd);
		List<PageData> varList = noticeService.getCorpReadType(page);//获取发给这个企业的公告

		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}
	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/listByIndex")
	@ResponseBody
	@LogAnno(menuType= "首页",menuServer= "首页",instructionsOperate = "首页",instructionsType = "列表")
	public Object listByIndex(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		//获取发布给这个企业的信息
		pd.put("CORP_INFO_ID", Jurisdiction.getCORPINFO_ID());
		page.setPd(pd);
		List<PageData>	varList = noticeService.getNotAndCorpByCorpId(page);

		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	/**获取最新企业通知
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/getNewNotice")
	@ResponseBody
	@Transactional //开启事物
	public Object getNewNotice() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		System.out.println(Jurisdiction.getCORPINFO_ID());
		//获取发布给这个企业的信息
		pd.put("CORP_INFO_ID", Jurisdiction.getCORPINFO_ID());
		pd = noticeService.getNewNotice(pd);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**获取最新企业通知
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/getMemoryUsage")
	@ResponseBody
	@Transactional //开启事物
	public Object getMemoryUsage() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		pd = fileUploadLogService.getMemoryUsage(pd);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}
}
