package com.palmnest.webapp.controller.backstage;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.DateUtils;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.model.Element;
import com.palmnest.model.estateserve.Announcement;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.estateserve.AnnouncementManager;
import com.palmnest.webapp.controller.BaseFormController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 通知公告业务前端控制器
 *
 * @author yubing
 * @since 2017-1-19
 */
@Controller
@RequestMapping("/announcement*")
public class AnnouncementWebController extends BaseFormController {

	@Autowired
	private AnnouncementManager announcementManager;

	public void init(Model model) {
		List<Element> announcementTypeGroup = this.getElementGroupManager().getElementsByGroupName("announcementTypeGroup");
		model.addAttribute("announcementTypeGroup", announcementTypeGroup);
		model.addAttribute("visitPrefix", FileUploadUtils.getVisitPrefix());
	}

	/**
	 * 默认方法 列表查询
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "list")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response) {
		initFunctionOperate(request);

		Model model = new ExtendedModelMap();

		//获取参数
		String pageNo         = request.getParameter("pageNo");
		String organizationId = request.getParameter("organizationId");
		String title          = request.getParameter("title");
		String type           = request.getParameter("type");
		String bgTime         = request.getParameter("bgTime");
		String endTime        = request.getParameter("endTime");
		String isTop          = request.getParameter("isTop");
		String operateName    = request.getRemoteUser();

		//查看当前管理员的项目管理权限集合
		List<TbOrganization> organizationList = getUserRelationOrgList(request);
		if (!CollectionUtils.isEmpty(organizationList)) {
			if (StringUtils.isEmpty(organizationId)) {
				if ("admin".equals(operateName)) {
					organizationId = "0";
				} else {
					organizationId = organizationList.get(0).getId().toString();
				}
			}
		}

		StringBuffer strSQL = new StringBuffer(" where 1=1");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isNotEmpty(organizationId)) {
			strSQL.append(" and organizationId=" + organizationId);
			model.addAttribute("organizationId", organizationId);
		}
		if (StringUtils.isNotEmpty(title)) {
			strSQL.append(" and title like '%" + title + "%'");
			model.addAttribute("title", title);
		}
		if (StringUtils.isNotEmpty(type)) {
			strSQL.append(" and type='" + type + "'");
			model.addAttribute("type", type);
		}
		if (StringUtils.isNotEmpty(bgTime)) {
			strSQL.append(" and createTime>='" + bgTime + "'");
			model.addAttribute("bgTime", bgTime);
		}
		if (StringUtils.isNotEmpty(endTime)) {
			strSQL.append(" and createTime<='" + endTime + "'");
			model.addAttribute("endTime", endTime);
		}
		if (StringUtils.isNotEmpty(isTop)) {
			strSQL.append(" and isTop='" + isTop + "'");
			model.addAttribute("isTop", isTop);
		}
		strSQL.append(" and isEnabled='" + ElementConstant.YESORNO_1 + "'");

		init(model);
		Page p = announcementManager.getAnnouncementByPage(Integer.parseInt(pageNo), 10, strSQL.toString());
		model.addAttribute("page", p);
		model.addAttribute("organizationList", organizationList);
		model.addAttribute("operateName", operateName);
		return new ModelAndView("admin/announcement/annouceList", model.asMap());
	}

	/**
	 * 添加And修改功能
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/form*")
	public ModelAndView form(HttpServletRequest request, HttpServletResponse response) {
		Model  model   = new ExtendedModelMap();
		String actType = request.getParameter("actType");
		if ("save".equals(actType)) {
			Announcement anno = null;

			String annoId            = request.getParameter("annoId"); //通知公告ID
			String isGroupNotifyFlag = request.getParameter("isGroupNotifyFlag"); //群发通知
			if (StringUtils.isNotBlank(annoId)) {
				anno = announcementManager.get(Integer.parseInt(annoId));
			} else {
				anno = new Announcement();
			}
			String title            = request.getParameter("title");
			String organizationId   = request.getParameter("organizationId");
			String type             = request.getParameter("type");
			String isTop            = request.getParameter("isTop");
			String introduction     = request.getParameter("introduction");
			String noticeContent    = request.getParameter("noticeContent");
			String noticePictureUrl = request.getParameter("noticePictureUrl");
			String address          = request.getParameter("address");
			String bgTime           = request.getParameter("bgTime");
			String detailUrl        = request.getParameter("detailUrl");
			String timerSendTime    = request.getParameter("timerSendTime");
			if (StringUtils.isNotBlank(timerSendTime)) {
				anno.setTimerSendTime(DateUtils.StrToDate(timerSendTime, "yyyy-MM-dd HH:mm:ss"));
				anno.setSendStatus("0");
			} else {
				anno.setTimerSendTime(null);
				anno.setSendStatus("");
			}

			anno.setTitle(title);
			anno.setOrganizationId(Integer.parseInt(organizationId));
			anno.setType(type);
			anno.setIsTop(isTop);
			anno.setIntroduction(introduction);
			anno.setDetails(noticeContent);
			anno.setCoverImageUrl(noticePictureUrl);
			anno.setAddress(address);
			anno.setBgTime(bgTime);
			anno.setDetailUrl(detailUrl);

			if (anno.getId() != null) {
				anno.setModifier(request.getRemoteUser());
				anno.setModifyTime(new Date());
				anno.setIsEnabled(ElementConstant.YESORNO_1);
				announcementManager.updateModel(anno);
				model.addAttribute("resultMsg", "更新成功.");
			} else {
				anno.setCreateTime(new Date());
				anno.setCreator(request.getRemoteUser());
				anno.setIsEnabled(ElementConstant.YESORNO_1);
				anno.setReaderNum(0);
				anno.setCommentNum(0);
				anno.setPraiseNum(0);
				anno.setIsReply("1"); //默认允许留言
				announcementManager.saveModel(anno);
				model.addAttribute("resultMsg", "新增成功.");
			}
			model.addAttribute("announcement", anno);

			//群发通知处理
			if ("true".equals(isGroupNotifyFlag)) {
				announcementManager.assginMassnotification(anno);
			}
		}
		init(model);
		List<TbOrganization> organizationList = getUserRelationOrgList(request);
		model.addAttribute("organizationList", organizationList);
		model.addAttribute("funcid", request.getParameter("funcid"));
		model.addAttribute("operateName", request.getRemoteUser());
		return new ModelAndView("admin/announcement/annouceForm", model.asMap());
	}

	/**
	 * 更新
	 *
	 * @param id
	 * @param model
	 */
	@RequestMapping(value = "/update/{id}&{funcid}")
	public String update(@PathVariable int id, @PathVariable int funcid, HttpServletRequest request, Model model) {
		model.addAttribute("announcement", announcementManager.get(id));
		init(model);
		List<TbOrganization> organizationList = getUserRelationOrgList(request);
		model.addAttribute("organizationList", organizationList);
		model.addAttribute("funcid", funcid);
		model.addAttribute("operateName", request.getRemoteUser());
		return "admin/announcement/annouceForm";
	}

	/**
	 * 删除公告
	 *
	 * @param id      公告ID
	 * @param funcid  功能ID
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}&{funcid}")
	public String delete(@PathVariable int id, @PathVariable long funcid, HttpServletRequest request) {
		Announcement anno = announcementManager.get(id);
		anno.setModifier(request.getRemoteUser());
		anno.setModifyTime(new Date());
		anno.setIsEnabled(ElementConstant.YESORNO_0);
		announcementManager.updateModel(anno);
		return "redirect:/announcement/list?funcid=" + funcid;
	}

	/**
	 * 置顶设置操作
	 *
	 * @return
	 */
	@RequestMapping(value = "setTop", method = {RequestMethod.GET, RequestMethod.POST})
	public @ResponseBody
	String setTop(HttpServletRequest request,
				  HttpServletResponse response) {
		String id    = request.getParameter("id");
		String isTop = request.getParameter("isTop");
		try {
			Announcement anno = announcementManager.get(Integer.parseInt(id));
			anno.setIsTop(isTop);
			anno.setModifier(request.getRemoteUser());
			anno.setModifyTime(new Date());
			announcementManager.updateModel(anno);
			return "1";
		} catch (Exception e) {
			return "0";
		}
	}

	/**
	 * 删除图片
	 *
	 * @param id      公告ID
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deleteImg")
	public String deleteImg(HttpServletRequest request, HttpServletResponse response) {
		String     id   = request.getParameter("id");
		JSONObject json = new JSONObject();
		try {
			if (StringUtils.isEmpty(id)) {
				json.put("code", -1);
				json.put("msg", "系统异常");
				StringUtil.charSet(json, request, response);
				return null;
			}
			Announcement anno = announcementManager.get(Integer.valueOf(id));
			anno.setModifier(request.getRemoteUser());
			anno.setModifyTime(new Date());
			anno.setCoverImageUrl("");
			announcementManager.updateModel(anno);

			json.put("code", 0);
			json.put("msg", "图片删除成功");
			StringUtil.charSet(json, request, response);
			return null;

		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", -1);
			json.put("msg", "系统异常，图片删除失败");
			StringUtil.charSet(json, request, response);
		}
		return null;
	}
}
