/**
 * Description: 公告控制器
 * Copyright:   Copyright (c)2016
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2016-09-14 下午 17:27:17
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016-09-14   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.NoticeEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.NoticeVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.NoticeListRequest;
import com.house365.ws.beans.request.NoticeRequest;
import com.house365.ws.beans.response.NoticeListResponse;
import com.house365.ws.beans.response.NoticeResponse;
import com.house365.ws.beans.response.UserResponse;
import com.house365.ws.interfaces.server.INotice;
import com.house365.ws.interfaces.server.IUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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.ResponseStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.Map;

import static com.house365.web.util.SessionConstants.*;

/**
 * 公告控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-14
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/notice")
public class NoticeController extends BaseController {

    /**
     * 自动注入公告WS实现
     */
    @Autowired
    private INotice notice;

    @Autowired
    private IUser userService;

    /**
     * 去新增公告
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model) {
        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    /**
     * 新增公告
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createNotice(
            @Valid NoticeVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model,
            HttpServletRequest request
    ) {
        UserEntity user = (UserEntity) request.getSession().getAttribute(THREAD_USER_KEY);
        NoticeEntity entity = vo.getEntity();
        entity.setCreateUserid(user.getId());
        entity.setCreateIp(String.valueOf(request.getSession().getAttribute(SESSION_IP)));
        entity.setCreateUsername(user.getName());
        entity.setCreateTime(new Date());

        entity.setUpdateUserid(user.getId());
        entity.setUpdateIp(String.valueOf(request.getSession().getAttribute(SESSION_IP)));
        entity.setUpdateTime(new Date());
        entity.setUpdateUsername(user.getName());

        DepartmentEntity department = (DepartmentEntity) request.getSession().getAttribute(SESSION_CURRNET_DEPT_KEY);
        entity.setCity(department.getCityID());
        entity.setCityName(department.getName());

        model.addAttribute("entity", entity);
        //         subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                NoticeRequest noticeRequest = new NoticeRequest();
                noticeRequest.setEntity(entity);
                NoticeResponse response = notice.addNotice(noticeRequest);
                Integer id = response.getEntity().getId();

                return "redirect:/notice/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除公告
     *
     * @param id 公告页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id) {
        if (!StringUtils.isEmpty(id)) {
            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    notice.deleteNoticeById(Integer.valueOf(ids[i]));
                }
            } else {
                notice.deleteNoticeById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看公告
     *
     * @param id 公告页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        NoticeResponse response = notice.getNoticeById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    /**
     * 去修改公告
     *
     * @param id 公告页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, Model model) {
        NoticeResponse response = notice.getNoticeById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改公告
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateNotice(
            @Valid NoticeVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes,
            Model model, HttpServletRequest request
    ) {
        NoticeEntity entity = vo.getEntity();

        UserEntity user = (UserEntity) request.getSession().getAttribute(THREAD_USER_KEY);
        entity.setUpdateUserid(user.getId());
        entity.setUpdateIp(String.valueOf(request.getSession().getAttribute(SESSION_IP)));
        entity.setUpdateTime(new Date());
        entity.setUpdateUsername(user.getName());

        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                NoticeRequest noticeRequest = new NoticeRequest();
                noticeRequest.setEntity(entity);
                @SuppressWarnings("unused") NoticeResponse rersponse = notice.updateNotice(noticeRequest);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/notice/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 查询公告
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        DepartmentEntity department = (DepartmentEntity) request.getSession().getAttribute(SESSION_CURRNET_DEPT_KEY);
        searchParams.put("EQ_city", department.getCityID());
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }
        NoticeListRequest listRequest = new NoticeListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        NoticeListResponse response = notice.getNoticeList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("notices", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    @RequestMapping(value = "viewList", method = RequestMethod.GET)
    public String viewList(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        DepartmentEntity department = (DepartmentEntity) request.getSession().getAttribute(SESSION_CURRNET_DEPT_KEY);
        searchParams.put("EQ_city", department.getCityID());
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }
        NoticeListRequest listRequest = new NoticeListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        NoticeListResponse response = notice.getNoticeList(listRequest);

        Date threeDaysAgo = DateTimeUtils.getDaysAgo(new Date(), 3);
        for (NoticeEntity notice : response.getObjectList()) {
            if (notice.getCreateTime().after(threeDaysAgo)) {
                notice.setCity("new");
            }
        }

        model.addAttribute("page", response.getPaging());
        model.addAttribute("notices", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    @RequestMapping(value = "/view/{id}", method = {RequestMethod.GET})
    public String view(@PathVariable(value = "id") Integer id, Model model) {
        NoticeResponse response = notice.getNoticeById(id);

        if (response != null && response.getEntity() != null) {
            UserResponse ur = userService.getUserById(response.getEntity().getCreateUserid());
            if (ur != null && ur.getEntity() != null) {
                response.getEntity().setCreateUsername(ur.getEntity().getRealName());
            }

            model.addAttribute("entity", response.getEntity());
        }

        model.addAttribute("action", "edit");
        return getAutoUrl("view");
    }

}
