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

import com.house365.beans.entity.UserEntity;
import com.house365.beans.entity.UserRoleEntity;
import com.house365.beans.entity.UserWxRelation;
import com.house365.beans.system.Page;
import com.house365.beans.vo.UserRoleVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.SessionConstants;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.UserRoleListRequest;
import com.house365.ws.beans.request.UserRoleRequest;
import com.house365.ws.beans.response.MapListResponse;
import com.house365.ws.beans.response.UserRoleListResponse;
import com.house365.ws.beans.response.UserRoleResponse;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.IUser;
import com.house365.ws.interfaces.server.IUserRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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, 2016-09-14
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/userrole")
public class UserRoleController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 自动注入角色权限关联WS实现
     */
    @Autowired
    private IUserRole userRole;

    @Autowired
    private IUser user;

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

    /**
     * 新增角色权限关联
     *
     * @param vo     角色权限关联页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createUserRole(@Valid UserRoleVo vo, BindingResult result,
                                 RedirectAttributes redirectAttributes, Model model) {
        UserRoleEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                UserRoleRequest request = new UserRoleRequest();
                request.setEntity(entity);
                UserRoleResponse response = userRole.addUserRole(request);
                Integer id = response.getEntity().getId();
                return "redirect:/userrole/" + 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++) {
                    userRole.deleteUserRoleById(Integer.valueOf(ids[i]));
                }
            } else {
                userRole.deleteUserRoleById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看角色权限关联
     *
     * @param id 角色权限关联页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        UserRoleResponse response = userRole.getUserRoleById(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) {
        UserRoleResponse response = userRole.getUserRoleById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改角色权限关联
     *
     * @param vo     角色权限关联页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateUserRole(@Valid UserRoleVo vo, BindingResult result,
                                 @PathVariable Integer id, RedirectAttributes redirectAttributes,
                                 Model model) {
        UserRoleEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                UserRoleRequest request = new UserRoleRequest();
                request.setEntity(entity);
                userRole.updateUserRole(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/userrole/" + 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_");
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }
        UserRoleListRequest listRequest = new UserRoleListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        UserRoleListResponse response = userRole.getUserRoleList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("userRoles", response.getObjectList());
        model.addAttribute("searchParams", Servlets
                .encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    @RequestMapping(value = "authorize/{userId}/{roleIds}", method = RequestMethod.GET)
    public String authorize(@PathVariable Integer userId,
                            @PathVariable String roleIds, HttpServletRequest httpRequest,
                            Model model) {
        UserEntity userEntity = (UserEntity) httpRequest.getSession()
                .getAttribute(SessionConstants.THREAD_USER_KEY);
        if (!StringUtils.isEmpty(roleIds) && !"-1".equals(roleIds)) {
            userRole.deleteUserRoleById(userId);
            if (roleIds.contains(",")) {
                String[] ids = roleIds.split(",");
                for (int i = 0; i < ids.length; i++) {
                    UserRoleRequest userRoleRequest = new UserRoleRequest();
                    userRoleRequest.setEntity(newEntity(userId, Integer.valueOf(ids[i]), userEntity.getId()));
                    userRole.addUserRole(userRoleRequest);
                }
            } else {
                UserRoleRequest userRoleRequest = new UserRoleRequest();
                userRoleRequest.setEntity(newEntity(userId, Integer.valueOf(roleIds), userEntity.getId()));
                userRole.addUserRole(userRoleRequest);
            }
        } else {
            userRole.deleteUserRoleById(userId);
        }
        Integer deptId = user.getUserById(userId).getEntity().getDeptId();
        return "redirect:/user/" + userId + "?search_EQ_deptId=" + deptId;
    }

    private UserRoleEntity newEntity(Integer userId, Integer roleId,
                                     Integer createUserId) {
        UserRoleEntity entity = new UserRoleEntity();
        entity.setRoleId(roleId);
        entity.setUserId(userId);
        entity.setCreateTime(new Date());
        entity.setCreateUserId(createUserId);
        return entity;
    }

    /**
     * 云迹活动列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/wxUserList")
    public String wxUserList(Model model, HttpServletRequest request) {
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");

            searchParams.put("userId", userEntity.getId());
            MapListResponse response = user.list(searchParams);

            model.addAttribute("dataList", response.getObjectList());
        } catch (Exception e) {
            logger.error("查询云迹活动列表失败", e);
        }
        return getAutoUrl();
    }

    /**
     * 解绑关系
     *
     * @return 标签信息列表
     */
    @ResponseBody
    @RequestMapping(value = "/deleteRelation/{id}")
    public HResult deleteRelation(@PathVariable int id, HttpServletRequest request) {
        HResult result = new HResult();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            UserWxRelation entity = user.getRelationById(id);
            entity.setIsDelete(1);
            entity.setUpdateName(userEntity.getRealName());
            entity.setUpdateId(userEntity.getId());
            entity.setUpdateTime(new Date());
            user.update(entity);
        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("解除用户微信关系失败");
            logger.error("解除用户微信关系失败", e);
        }
        return result;
    }
}
