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

import com.google.common.base.Strings;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CmHouseCommentReplyVo;
import com.house365.rest.context.CmConstant;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.CityUtil;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.CmHouseCommentReplyListRequest;
import com.house365.ws.beans.request.CmHouseCommentReplyRequest;
import com.house365.ws.beans.request.CmHouseCommentRequest;
import com.house365.ws.beans.request.CmUserRequest;
import com.house365.ws.beans.response.*;
import com.house365.ws.interfaces.server.ICmDictionary;
import com.house365.ws.interfaces.server.ICmHouseComment;
import com.house365.ws.interfaces.server.ICmHouseCommentReply;
import com.house365.ws.interfaces.server.ICmUser;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.*;
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.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

    Logger commentLogger = LoggerFactory.getLogger(getClass());

    /**
     * 自动注入CmHouseCommentReplyWS实现
     */
    @Autowired
    private ICmHouseCommentReply cmHouseCommentReply;

    @Autowired
    private ICmUser cmUser;

    @Autowired
    private ICmHouseComment cmHouseComment;

    @Autowired
    private ICmDictionary cmDictionary;

    /**
     * 被禁言时间
     */
    @Value("#{system.gagTimeInMinutes}")
    private Integer gagTimeInMinutes;

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

    /**
     * 新增CmHouseCommentReply
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createCmHouseCommentReply(
            @Valid CmHouseCommentReplyVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model
    ) {
        CmHouseCommentReplyEntity 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 {
                CmHouseCommentReplyRequest request = new CmHouseCommentReplyRequest();
                request.setEntity(entity);
                CmHouseCommentReplyResponse response = cmHouseCommentReply.addCmHouseCommentReply(request);
                Integer id = response.getEntity().getId();
                return "redirect:/cmhousecommentreply/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除CmHouseCommentReply
     *
     * @param id      CmHouseCommentReply页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id, boolean isGaged, HttpServletRequest request) {
        if (!StringUtils.isEmpty(id)) {
            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    try {
                        boolean isNotOk = deleteReply(ids[i], isGaged);
                        if (isNotOk) {
                            continue;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }

                }
            } else {
                deleteReply(id, isGaged);
            }
        }
    }

    /**
     * 删除CmHouseCommentReply
     *
     * @param commentId CmHouseCommentReply页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/commentReply/add", method = {RequestMethod.POST})
    @ResponseBody
    public void commentReply(HttpServletRequest req, Integer commentId, String content, Model model) {
        CmHouseCommentReplyEntity entity = new CmHouseCommentReplyEntity();
        try {
            String userName = (String) req.getSession().getAttribute(CmConstant.USER_NAME);
            String cityKey = (String) req.getSession().getAttribute(CmConstant.CITY_KEY);

            entity.setCommentId(commentId);
            entity.setContent(content);
            entity.setCriticName("小编回复(" + userName + ")");
            entity.setCreateTime(new Date());
            entity.setCityKey(cityKey);
            entity.setCheckStatus(1);
            entity.setIsReplyByManager(1);
            entity.setIsDeleted(0);
            entity.setPraiseCount(0);
            entity.setIsReported(0);

            CmHouseCommentReplyRequest request = new CmHouseCommentReplyRequest();
            request.setEntity(entity);
            cmHouseCommentReply.addCmHouseCommentReply(request);
        } catch (Exception ex) {
            addErrorMessage(model, ex.getMessage());
        }
    }

    /**
     * 小编回复
     *
     * @param id CmHouseCommentReply页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/commentReply/update", method = {RequestMethod.POST})
    @ResponseBody
    public void commentReplyUpdate(HttpServletRequest req, Integer id, String content, Model model) {
        CmHouseCommentReplyResponse cmRes = cmHouseCommentReply.getCmHouseCommentReplyById(id);

        CmHouseCommentReplyEntity entity = cmRes.getEntity();
        try {
            String userName = (String) req.getSession().getAttribute(CmConstant.USER_NAME);
            String cityKey = (String) req.getSession().getAttribute(CmConstant.CITY_KEY);

            entity.setContent(content);
            entity.setCriticName("小编回复(" + userName + ")");
            entity.setCreateTime(new Date());
            entity.setCityKey(cityKey);

            CmHouseCommentReplyRequest request = new CmHouseCommentReplyRequest();
            request.setEntity(entity);
            cmHouseCommentReply.updateCmHouseCommentReply(request);
        } catch (Exception ex) {
            addErrorMessage(model, ex.getMessage());
        }
    }

    /**
     * 功能描述: <br>
     * 〈功能详细描述〉
     * 删除回复
     *
     * @param id
     * @param isGaged
     * @return 是否不成功
     * @author yinchangming
     * @version [v1.0.0, 2015年10月31日]
     * @since [产品/模块版本](可选)
     */
    public boolean deleteReply(String id, boolean isGaged) {
        CmHouseCommentReplyResponse response = cmHouseCommentReply.getCmHouseCommentReplyById(Integer.valueOf(id));
        CmHouseCommentReplyEntity entity = response.getEntity();
        if (entity != null) {
            //数据逻辑删除
            entity.setIsDeleted(1);
            CmHouseCommentReplyRequest replyRequest = new CmHouseCommentReplyRequest();
            replyRequest.setEntity(entity);
            cmHouseCommentReply.updateCmHouseCommentReply(replyRequest);
            //审核通过的普通回复被删除时，评论统计数量减一
            if (entity.getCheckStatus() == 1 && entity.getIsReplyByManager() == 0) {
                minusCommentAmount(entity);
            }
            //禁言
            if (isGaged) {
                //获取要更新的对象
                CmUserResponse userResponse = cmUser.getCmUserById(entity.getCriticId());
                CmUserEntity userEntity = userResponse.getEntity();
                if (userEntity == null) {
                    return true;
                }
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.MINUTE, gagTimeInMinutes);

                if (userEntity.getGagTime() == null || userEntity.getGagTime().compareTo(new Date()) <= 0) {
                    userEntity.setGagTime(cal.getTime());
                    CmUserRequest cur = new CmUserRequest();
                    cur.setEntity(userEntity);
                    cmUser.updateCmUser(cur);
                }
            }
        }
        return false;
    }

    //删除的时候，评论数目减一
    public void minusCommentAmount(CmHouseCommentReplyEntity entity) {
        CmHouseCommentResponse cmRes = cmHouseComment.getCmHouseCommentById(entity.getCommentId());
        CmHouseCommentEntity houseCommentEntity = cmRes.getEntity();
        if (houseCommentEntity != null) {
            Integer cAmount = houseCommentEntity.getCommentAmount();
            if (cAmount == null) {
                cAmount = 0;
            }
            houseCommentEntity.setCommentAmount(cAmount - 1);
            CmHouseCommentRequest cmre = new CmHouseCommentRequest();
            cmre.setEntity(houseCommentEntity);
            cmHouseComment.updateCmHouseComment(cmre);
        }
    }

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

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

    /**
     * 修改CmHouseCommentReply
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateCmHouseCommentReply(
            @Valid CmHouseCommentReplyVo vo, BindingResult result, @PathVariable Integer id,
            RedirectAttributes redirectAttributes, Model model
    ) {
        CmHouseCommentReplyEntity 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 {
                CmHouseCommentReplyRequest request = new CmHouseCommentReplyRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused") CmHouseCommentReplyResponse rersponse = cmHouseCommentReply.updateCmHouseCommentReply(
                        request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/cmhousecommentreply/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }


    /**
     * 修改CmHouseCommentReply
     *
     * @return 结果视图
     */
    @RequestMapping(value = "/setReaded", method = {RequestMethod.POST})
    @ResponseBody
    public String setIsReaded(String ids, Model model) {
        String[] idsA = ids.split(",");
        for (String idStr : idsA) {
            Integer id = Integer.parseInt(idStr);
            CmHouseCommentReplyEntity entity = cmHouseCommentReply.getCmHouseCommentReplyById(id).getEntity();
            if (entity == null) {
                continue;
            }
            try {
                CmHouseCommentReplyRequest request = new CmHouseCommentReplyRequest();
                entity.setIsReaded(1);
                request.setEntity(entity);
                @SuppressWarnings("unused") CmHouseCommentReplyResponse rersponse = cmHouseCommentReply.updateCmHouseCommentReply(
                        request);

            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                continue;
            }
        }

        return "success";
    }


    /**
     * 查询CmHouseCommentReply
     *
     * @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 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());
        }
        //获取城市列表
        List<KlfCityEntity> cityList = CityUtil.getCityList();
        model.addAttribute("cityList", cityList);

        boolean needCheck = false;
        String sessionCity = String.valueOf(request.getSession().getAttribute(CmConstant.CITY_KEY));
        CmDictionaryResponse dictionary = cmDictionary.getCmDictionaryById(16);
        if (dictionary.getEntity() != null) {
            CmDictionaryEntity dic = dictionary.getEntity();
            String cities = "," + dic.getDicValue() + ",";
            if (cities.contains("," + sessionCity + ",")) {
                needCheck = true;
            }

        }

        model.addAttribute("needCheck", needCheck);

        // 开始时间 结束时间
        if (searchParams.get("GTE_createTimeStart") != "" && searchParams.get("GTE_createTimeStart") != null) {
            String createTimeStart = searchParams.get("GTE_createTimeStart") + " 00:00:00";
            searchParams.put("GTE_createTimeStart", createTimeStart);
        }
        if (searchParams.get("LTE_createTimeEnd") != "" && searchParams.get("LTE_createTimeEnd") != null) {
            String createTimeEnd = searchParams.get("LTE_createTimeEnd") + " 23:59:59";
            searchParams.put("LTE_createTimeEnd", createTimeEnd);
        }

        Page page = new Page(Page.TWENTY_PAGE_SIZE);
        if (null != number) {
            page.setCurrentPage(number);
        }
        CmHouseCommentReplyListRequest listRequest = new CmHouseCommentReplyListRequest();
        listRequest.setOrderColumn("create_time");
        listRequest.setOrderMode("desc");
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        CmHouseCommentReplyListResponse response = cmHouseCommentReply.getCmHouseCommentReplyList(listRequest);

        CmDictionaryResponse cmDictionaryResponse = cmDictionary.getCmDictionaryById(2);
        model.addAttribute("applyWhiteList", cmDictionaryResponse.getEntity().getDicValue());

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

    @RequestMapping(value = "check/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String check(@PathVariable String id, Model model, HttpServletRequest request, @RequestParam String op) {

        House365RestResponse restResponse = new House365RestResponse();
        if (Strings.isNullOrEmpty(id)) {
            restResponse.setResult("0");
            restResponse.setMsg("记录不存在");
            return JSONObject.fromObject(restResponse).toString();
        }

        String userName = String.valueOf(request.getSession().getAttribute(CmConstant.USER_NAME));
        commentLogger.info("user {} check comments [{}]", userName, id);

        try {
            restResponse = cmHouseCommentReply.checkHouseComment(id, op);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse.setResult("0");
            restResponse.setMsg(e.getMessage());
        }

        return JSONObject.fromObject(restResponse).toString();
    }
}
