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

import com.house365.beans.entity.RolePermissionEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.RolePermissionVo;
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.RolePermissionListRequest;
import com.house365.ws.beans.request.RolePermissionRequest;
import com.house365.ws.beans.response.RolePermissionListResponse;
import com.house365.ws.beans.response.RolePermissionResponse;
import com.house365.ws.interfaces.server.IRolePermission;
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.Date;
import java.util.Map;

/**
 * 角色权限关联控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-14
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/rolepermission")
public class RolePermissionController extends BaseController {

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

    /**
     * 去新增角色权限关联
     *
     * @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 createRolePermission(@Valid RolePermissionVo vo,
                                       BindingResult result, RedirectAttributes redirectAttributes,
                                       Model model) {
        RolePermissionEntity 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 {
                RolePermissionRequest request = new RolePermissionRequest();
                request.setEntity(entity);
                RolePermissionResponse response = rolePermission
                        .addRolePermission(request);
                Integer id = response.getEntity().getId();
                return "redirect:/rolepermission/" + 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++) {
                    rolePermission.deleteRolePermissionById(Integer.valueOf(ids[i]));
                }
            } else {
                rolePermission.deleteRolePermissionById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看角色权限关联
     *
     * @param id 角色权限关联页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        RolePermissionResponse response = rolePermission
                .getRolePermissionById(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) {
        RolePermissionResponse response = rolePermission
                .getRolePermissionById(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 updateRolePermission(@Valid RolePermissionVo vo,
                                       BindingResult result, @PathVariable Integer id,
                                       RedirectAttributes redirectAttributes, Model model) {
        RolePermissionEntity 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 {
                RolePermissionRequest request = new RolePermissionRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused")
                RolePermissionResponse rersponse = rolePermission
                        .updateRolePermission(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/rolepermission/" + 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);
        }
        RolePermissionListRequest listRequest = new RolePermissionListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        RolePermissionListResponse response = rolePermission
                .getRolePermissionList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("rolePermissions", response.getObjectList());
        model.addAttribute("searchParams", Servlets
                .encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    @RequestMapping(value = "authorize/{roleId}/{permissionIds}", method = RequestMethod.GET)
    public String authorize(@PathVariable Integer roleId,
                            @PathVariable String permissionIds, HttpServletRequest httpRequest,
                            Model model) {
        UserEntity userEntity = (UserEntity) httpRequest.getSession()
                .getAttribute(SessionConstants.THREAD_USER_KEY);
        if (!StringUtils.isEmpty(permissionIds) && !"-1".equals(permissionIds)) {
            rolePermission.deleteRolePermissionById(roleId);
            if (permissionIds.contains(",")) {
                String[] ids = permissionIds.split(",");
                for (int i = 0; i < ids.length; i++) {
                    RolePermissionRequest rolePermissionRequest = new RolePermissionRequest();
                    rolePermissionRequest.setEntity(newEntity(roleId,
                            Integer.valueOf(ids[i]), userEntity.getId()));
                    rolePermission.addRolePermission(rolePermissionRequest);
                }
            } else {
                RolePermissionRequest rolePermissionRequest = new RolePermissionRequest();
                rolePermissionRequest.setEntity(newEntity(roleId,
                        Integer.valueOf(permissionIds), userEntity.getId()));
                rolePermission.addRolePermission(rolePermissionRequest);
            }
        } else {
            rolePermission.deleteRolePermissionById(roleId);
        }
        return "redirect:/role/" + roleId;
    }

    private RolePermissionEntity newEntity(Integer roleId, Integer permissionId, Integer userId) {
        RolePermissionEntity entity = new RolePermissionEntity();
        entity.setRoleId(roleId);
        entity.setPermissionId(permissionId);
        entity.setCreateTime(new Date());
        entity.setCreateUserid(userId);
        return entity;
    }
}
