/**
 * Description: 直销人员楼盘推荐控制器
 * Copyright:   Copyright (c)2018
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2018-01-22 下午 13:57:27
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2018-01-22   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.entity.UserProjectRecommendEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.UserProjectRecommendVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.SessionConstants;
import com.house365.ws.beans.request.UserProjectRecommendListRequest;
import com.house365.ws.beans.request.UserProjectRecommendRequest;
import com.house365.ws.beans.response.UserProjectRecommendListResponse;
import com.house365.ws.beans.response.UserProjectRecommendResponse;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.IUserProjectRecommend;
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.*;
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;

/**
 * 直销人员楼盘推荐控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2018-01-22
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/userprojectrecommend")
public class UserProjectRecommendController extends BaseController {

    /**
     * 自动注入直销人员楼盘推荐WS实现
     */
    @Autowired
    private IUserProjectRecommend userProjectRecommend;

    /**
     * 去新增直销人员楼盘推荐
     *
     * @return 结果视图
     */
    @RequestMapping(value = "recommend")
    public String createForm(HttpServletRequest request, Model model) {
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityCode = departmentEntity.getDescripition();

        model.addAttribute("city", cityCode);
        return getAutoUrl("form");
    }

    /**
     * 新增直销人员楼盘推荐
     *
     * @param vo      直销人员楼盘推荐页面表单对象
     * @param result  表单验证数据
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/recommend", method = {RequestMethod.POST})
    public String createUserProjectRecommend(HttpServletRequest request, @Valid UserProjectRecommendVo vo,
                                             BindingResult result, RedirectAttributes redirectAttributes, Model model) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityCode = departmentEntity.getDescripition();

        model.addAttribute("city", cityCode);
        UserProjectRecommendEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                entity.setUserId(userEntity.getId());
                entity.setUserName(userEntity.getRealName());
                entity.setCreateTime(new Date());
                entity.setUpdateTime(new Date());
                entity.setIsDeleted(0);
                entity.setCity(cityCode);
                UserProjectRecommendRequest recommendRequest = new UserProjectRecommendRequest();
                recommendRequest.setEntity(entity);
                userProjectRecommend.addUserProjectRecommend(recommendRequest);
                return "redirect:/userprojectrecommend/";
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    @RequestMapping(value = "/save", method = {RequestMethod.POST})
    @ResponseBody
    public HResult save(@RequestBody UserProjectRecommendEntity entity, HttpServletRequest request) {
        HResult result = new HResult();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);
            String cityCode = departmentEntity.getDescripition();
            entity.setUserId(userEntity.getId());
            entity.setUserName(userEntity.getRealName());
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            entity.setIsDeleted(0);
            entity.setCity(cityCode);
            result = userProjectRecommend.save(entity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("新增推荐楼盘失败", e);
            result.setStatus(-1);
            result.setErrorMessage("新增推荐楼盘失败");
        }
        return result;
    }

    @RequestMapping(value = "/update", method = {RequestMethod.POST})
    @ResponseBody
    public HResult update(@RequestBody UserProjectRecommendEntity entity) {
        HResult result = new HResult();
        try {
            UserProjectRecommendResponse response = userProjectRecommend.getUserProjectRecommendById(entity.getId());
            UserProjectRecommendEntity oldEntity = response.getEntity();
            oldEntity.setRecommendReason(entity.getRecommendReason());
            oldEntity.setUpdateTime(new Date());
            UserProjectRecommendRequest request = new UserProjectRecommendRequest();
            request.setEntity(oldEntity);
            userProjectRecommend.updateUserProjectRecommend(request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改推荐楼盘失败", e);
            result.setStatus(-1);
            result.setErrorMessage("修改推荐楼盘失败");
        }
        return result;
    }

    /**
     * 删除直销人员楼盘推荐
     *
     * @param id 直销人员楼盘推荐页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id) {
        userProjectRecommend.deleteUserProjectRecommendById(Integer.valueOf(id));
    }

    /**
     * 去查看直销人员楼盘推荐
     *
     * @param id 直销人员楼盘推荐页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        UserProjectRecommendResponse response = userProjectRecommend
                .getUserProjectRecommendById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    /**
     * 去修改直销人员楼盘推荐
     *
     * @param id 直销人员楼盘推荐页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/recommend/{id}", method = {RequestMethod.GET})
    public String updateForm(@PathVariable(value = "id") Integer id, Model model) {
        UserProjectRecommendResponse response = userProjectRecommend
                .getUserProjectRecommendById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改直销人员楼盘推荐
     *
     * @param vo     直销人员楼盘推荐页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/recommend/{id}", method = {RequestMethod.POST})
    public String updateUserProjectRecommend(@Valid UserProjectRecommendVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes, Model model) {
        UserProjectRecommendEntity 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 {
                entity.setUpdateTime(new Date());
                UserProjectRecommendRequest request = new UserProjectRecommendRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused")
                UserProjectRecommendResponse rersponse = userProjectRecommend.updateUserProjectRecommend(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/userprojectrecommend/";
            } 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) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityCode = departmentEntity.getDescripition();
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(
                request, "search_");
        searchParams.put("EQ_userId", userEntity.getId());
        searchParams.put("EQ_isDeleted", 0);
        searchParams.put("EQ_city", cityCode);
        Page page = new Page();
        if (null != number) {
            page.setCurrentPage(number);
        }
        UserProjectRecommendListRequest listRequest = new UserProjectRecommendListRequest();
        listRequest.setOrderColumn("update_time");
        listRequest.setOrderMode("desc");
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        UserProjectRecommendListResponse response = userProjectRecommend.getUserProjectRecommendList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("userProjectRecommends", response.getObjectList());
        model.addAttribute("searchParams", Servlets
                .encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }
}
