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

import com.house365.beans.constant.CommentConstant;
import com.house365.beans.entity.CmBrokerCommentEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.beans.entity.KlfCityEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CmBrokerCommentVo;
import com.house365.rest.context.CmConstant;
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.CmBrokerCommentListRequest;
import com.house365.ws.beans.request.CmBrokerCommentRequest;
import com.house365.ws.beans.request.CmUserRequest;
import com.house365.ws.beans.response.CmBrokerCommentListResponse;
import com.house365.ws.beans.response.CmBrokerCommentResponse;
import com.house365.ws.beans.response.CmUserResponse;
import com.house365.ws.interfaces.server.ICmBrokerComment;
import com.house365.ws.interfaces.server.ICmCreditRecord;
import com.house365.ws.interfaces.server.ICmUser;
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.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.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

    /**
     * 自动注入CmBrokerCommentWS实现
     */
    @Autowired
    private ICmBrokerComment cmBrokerComment;

    @Autowired
    private ICmUser cmUser;

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

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

    /**
     * 新增CmBrokerComment
     *
     * @param vo     CmBrokerComment页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createCmBrokerComment(
            @Valid CmBrokerCommentVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model
    ) {
        CmBrokerCommentEntity 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 {
                CmBrokerCommentRequest request = new CmBrokerCommentRequest();
                request.setEntity(entity);
                CmBrokerCommentResponse response = cmBrokerComment.addCmBrokerComment(request);
                Integer id = response.getEntity().getId();
                return "redirect:/cmbrokercomment/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

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

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

        if (!StringUtils.isEmpty(id)) {
            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {

                    CmBrokerCommentResponse response = cmBrokerComment.getCmBrokerCommentById(Integer.valueOf(ids[i]));

                    CmBrokerCommentEntity entity = response.getEntity();

                    //数据逻辑删除
                    entity.setIsDeleted(1);
                    //禁言48小时
                    if (!StringUtils.isEmpty(isNoTalk) && "true".equals(isNoTalk)) {
                        Calendar c = Calendar.getInstance();
                        c.add(Calendar.MINUTE, gagTimeInMinutes);

                        //entity.setActivateTime(c.getTime());
                        CmUserResponse cmUserRes = cmUser.getCmUserById(entity.getCriticCode());
                        CmUserEntity userEntity = cmUserRes.getEntity();
                        if (userEntity.getGagTime() == null || userEntity.getGagTime().compareTo(new Date()) <= 0) {
                            userEntity.setGagTime(c.getTime());
                            CmUserRequest userRequest = new CmUserRequest();
                            userRequest.setEntity(userEntity);
                            cmUser.updateCmUser(userRequest);
                        }

                    }

                    CmBrokerCommentRequest commentRequest = new CmBrokerCommentRequest();

                    commentRequest.setEntity(entity);
                    cmBrokerComment.updateCmBrokerComment(commentRequest);

                    if (entity.getSource() == CommentConstant.COMMENT_SOURCE_WEB) {
                        continue;
                    }
                    //扣除积分
                    cmCreditRecord.removeCredit(Integer.valueOf(ids[i]), CmConstant.CREDITS_RULE_BROKER_COMMENT);

                }
            } else {
                CmBrokerCommentResponse response = cmBrokerComment.getCmBrokerCommentById(Integer.valueOf(id));

                CmBrokerCommentEntity entity = response.getEntity();

                //数据逻辑删除
                entity.setIsDeleted(1);
                //禁言48小时
                if (!StringUtils.isEmpty(isNoTalk) && "true".equals(isNoTalk)) {
                    Calendar c = Calendar.getInstance();
                    c.add(Calendar.MINUTE, gagTimeInMinutes);
                    CmUserResponse cmUserRes = cmUser.getCmUserById(entity.getCriticCode());
                    CmUserEntity userEntity = cmUserRes.getEntity();
                    userEntity.setGagTime(c.getTime());

                    CmUserRequest userRequest = new CmUserRequest();
                    userRequest.setEntity(userEntity);
                    cmUser.updateCmUser(userRequest);
                }

                CmBrokerCommentRequest commentRequest = new CmBrokerCommentRequest();

                commentRequest.setEntity(entity);
                cmBrokerComment.updateCmBrokerComment(commentRequest);

                if (entity.getSource() == CommentConstant.COMMENT_SOURCE_WEB) {
                    return;
                }
                //扣除积分
                cmCreditRecord.removeCredit(Integer.valueOf(id), CmConstant.CREDITS_RULE_BROKER_COMMENT);

            }
        }
    }

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

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

    /**
     * 修改CmBrokerComment
     *
     * @param vo     CmBrokerComment页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateCmBrokerComment(
            @Valid CmBrokerCommentVo vo, BindingResult result, @PathVariable Integer id,
            RedirectAttributes redirectAttributes, Model model
    ) {
        CmBrokerCommentEntity 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 {
                CmBrokerCommentRequest request = new CmBrokerCommentRequest();
                request.setEntity(entity);
                cmBrokerComment.updateCmBrokerComment(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/cmbrokercomment/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 修改CmBrokerComment
     *
     * @param id      CmBrokerComment页面表单对象
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST}, params = "action=updateComment")
    @ResponseStatus(HttpStatus.OK)
    public void updateComment(@PathVariable String id, Model model, HttpServletRequest request) {
        try {
            String isReaded = request.getParameter("isReaded");
            String isKicked = request.getParameter("isKicked");
            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    CmBrokerCommentRequest commentRequest = new CmBrokerCommentRequest();

                    CmBrokerCommentResponse commentResponse = cmBrokerComment.getCmBrokerCommentById(Integer.valueOf(ids[i]));

                    CmBrokerCommentEntity entity = commentResponse.getEntity();
                    entity.setIsReaded(1);
                    commentRequest.setEntity(entity);
                    cmBrokerComment.updateCmBrokerComment(commentRequest);
                }
            } else {
                CmBrokerCommentRequest commentRequest = new CmBrokerCommentRequest();

                CmBrokerCommentResponse commentResponse = cmBrokerComment.getCmBrokerCommentById(Integer.valueOf(id));
                CmBrokerCommentEntity entity = commentResponse.getEntity();
                if (!StringUtils.isEmpty(isReaded)) {
                    entity.setIsReaded(Integer.valueOf(isReaded));
                }
                if (!StringUtils.isEmpty(isKicked)) {
                    entity.setIsKicked(Integer.valueOf(isKicked));
                }
                commentRequest.setEntity(entity);
                cmBrokerComment.updateCmBrokerComment(commentRequest);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            addErrorMessage(model, ex.getMessage());
            model.addAttribute("action", "edit");
        }
    }

    /**
     * 查询CmBrokerComment
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {
        try {
            // 获取查询条件
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");

            searchParams.put("EQ_city", null);
            searchParams.put("EQ_cityId", null);
            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);

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

            searchParams.remove("EQ_other");
            //不限  1 置顶  2 举报
            if (!StringUtils.isEmpty(other)) {
                if ("1".equals(other)) {
                    searchParams.put("EQ_isKicked", 1);
                }
                if ("2".equals(other)) {
                    searchParams.put("EQ_isReported", 1);
                }
            }

            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);
            }
            CmBrokerCommentListRequest listRequest = new CmBrokerCommentListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            CmBrokerCommentListResponse response = cmBrokerComment.getCmBrokerCommentList(listRequest);
            model.addAttribute("page", response.getPaging());
            model.addAttribute("cmBrokerComments", response.getObjectList());
            model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
            return getAutoUrl();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }
}
