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

import com.google.common.base.Strings;
import com.house365.beans.entity.CmCommentReportEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CmCommentReportVo;
import com.house365.rest.context.CmConstant;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.CmCommentReportListRequest;
import com.house365.ws.beans.request.CmCommentReportRequest;
import com.house365.ws.beans.response.CmCommentReportListResponse;
import com.house365.ws.beans.response.CmCommentReportResponse;
import com.house365.ws.interfaces.server.ICmCommentReport;
import com.house365.ws.interfaces.server.ICmUser;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

    /**
     * 自动注入CmCommentReportWS实现
     */
    @Autowired
    private ICmCommentReport cmCommentReport;

    @Autowired
    private ICmUser cmUser;


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

    /**
     * 新增CmCommentReport
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createCmCommentReport(
            @Valid CmCommentReportVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model
    ) {
        CmCommentReportEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                CmCommentReportRequest request = new CmCommentReportRequest();
                request.setEntity(entity);
                CmCommentReportResponse response = cmCommentReport.addCmCommentReport(request);
                Integer id = response.getEntity().getId();
                return "redirect:/cmcommentreport/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除CmCommentReport
     *
     * @param id      CmCommentReport页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id, HttpServletRequest request) {

        String forbidHours = (Strings.isNullOrEmpty(request.getParameter("forbidHours")) || !StringUtils.isNumeric(
                request.getParameter("forbidHours"))) ? "0" : request.getParameter("forbidHours");

        String isIgnored = request.getParameter("isIgnored");

        cmCommentReport.deleteCommentReport(id, forbidHours, isIgnored);
    }

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

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

    /**
     * 修改CmCommentReport
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateCmCommentReport(
            @Valid CmCommentReportVo vo, BindingResult result, @PathVariable Integer id,
            RedirectAttributes redirectAttributes, Model model
    ) {
        CmCommentReportEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                CmCommentReportRequest request = new CmCommentReportRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused") CmCommentReportResponse rersponse = cmCommentReport.updateCmCommentReport(
                        request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/cmcommentreport/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 查询CmCommentReport
     *
     * @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_");

        //String cityId = (String) request.getSession().getAttribute(ServiceConstant.CITY_ID);
        searchParams.put("EQ_city", null);
        searchParams.put("EQ_cityId", null);
        //searchParams.put("EQ_cityKey", cityId);
        String userRole = String.valueOf(request.getSession().getAttribute(CmConstant.USER_ROLE));
        if (!userRole.equals(CmConstant.ROLE_ADMIN)) {
            searchParams.put("EQ_cityKey", request.getSession().getAttribute(CmConstant.CITY_KEY).toString());
        }

        String other = (String) searchParams.get("EQ_other");
        String mute = (String) searchParams.get("EQ_mute");
        String searchType = (String) searchParams.get("searchType");
        String searchContent = (String) searchParams.get("searchContent");

        if (StringUtils.isEmpty(other)) {
            searchParams.remove("EQ_other");
        }
        if (StringUtils.isEmpty(mute)) {
            searchParams.remove("EQ_mute");
        }

        searchParams.remove("searchType");
        searchParams.remove("searchContent");
        //1用户名  2 手机号
        if (!StringUtils.isEmpty(searchType)) {
            if ("1".equals(searchType)) {
                searchParams.put("LIKE_criticName", searchContent);
            }
            if ("2".equals(searchType)) {
                searchParams.put("LIKE_criticPhone", searchContent);
            }
        }

        // 开始时间 结束时间
        if (searchParams.get("GTE_publishTimeStart") != "" && searchParams.get("GTE_publishTimeStart") != null) {
            String publishTimeStart = searchParams.get("GTE_publishTimeStart") + " 00:00:00";
            searchParams.put("GTE_publishTimeStart", publishTimeStart);
        }
        if (searchParams.get("LTE_publishTimeEnd") != "" && searchParams.get("LTE_publishTimeEnd") != null) {
            String publishTimeEnd = searchParams.get("LTE_publishTimeEnd") + " 23:59:59";
            searchParams.put("LTE_publishTimeEnd", publishTimeEnd);
        }

        Page page = new Page(Page.TWENTY_PAGE_SIZE);
        if (null != number) {
            page.setCurrentPage(number);
        }
        CmCommentReportListRequest listRequest = new CmCommentReportListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        listRequest.setOrderColumn("create_time");
        listRequest.setOrderMode("desc");
        CmCommentReportListResponse response = cmCommentReport.getCmCommentReportList(listRequest);

        List<CmCommentReportEntity> list = response.getObjectList();
        List<CmCommentReportEntity> newList = new ArrayList<>();
        for (CmCommentReportEntity entity : list) {
            List<String> picList = new ArrayList<>();

            String criticPics = entity.getCriticPictures();
            if (!StringUtils.isEmpty(criticPics)) {
                if (criticPics.contains(",")) {
                    String[] picArr = criticPics.split(",");
                    for (String string : picArr) {
                        picList.add(string);
                    }
                } else {
                    picList.add(criticPics);
                }
            }

            entity.setPicList(picList);

            CmUserEntity user = cmUser.getCmUserById(entity.getCriticId()).getEntity();
            Date now = new Date();
            if (user != null && user.getGagTime() != null && user.getGagTime().compareTo(now) > 0) {
                int remainHours = Integer.parseInt(
                        "" + ((user.getGagTime().getTime() - now.getTime()) / 1000 / 60 / 60));
                int remainMinutes = Integer.parseInt(
                        "" + ((user.getGagTime().getTime() - now.getTime()) / 1000 / 60 % 60));
                entity.setIsDeleted(remainHours);
                entity.setIsIgnored(remainMinutes);
            }
            newList.add(entity);
        }

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