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

import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.vo.PermissionVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.PathUtil;
import com.house365.web.util.SessionConstants;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.PermissionListRequest;
import com.house365.ws.beans.request.PermissionRequest;
import com.house365.ws.beans.request.RolePermissionListRequest;
import com.house365.ws.beans.request.WeChatPermissionListRequest;
import com.house365.ws.beans.response.PermissionListResponse;
import com.house365.ws.beans.response.PermissionResponse;
import com.house365.ws.interfaces.server.IPermission;
import com.house365.ws.interfaces.server.IRolePermission;
import com.house365.ws.interfaces.server.IWeChatPermission;
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.*;

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

    @Autowired
    private IRolePermission rolePermission;

    @Autowired
    private IWeChatPermission weChatPermission;

    @Autowired
    private IPermission permission;

    @RequestMapping(value = "/permissionListSection/{roleId}")
    public String permissionListSection(@PathVariable Integer roleId, HttpServletRequest request, Model model) {
        RolePermissionListRequest rolePermissionListRequest = new RolePermissionListRequest();
        rolePermissionListRequest.setPaging(new Page(Integer.MAX_VALUE));
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("EQ_roleId", roleId);
        rolePermissionListRequest.setSearchParams(paraMap);
        List<RolePermissionEntity> rolePermissionList = rolePermission.getRolePermissionList(
                rolePermissionListRequest).getObjectList();

        PermissionListRequest permissionListRequest = new PermissionListRequest();
        permissionListRequest.setPaging(new Page(Integer.MAX_VALUE));
        permissionListRequest.setOrderColumn("parentId asc,orderNum");
        permissionListRequest.setOrderMode("asc");
        List<PermissionEntity> permissions = permission.getPermissionList(permissionListRequest).getObjectList();
        List<PermissionEntity> permissionsRe = new LinkedList<>();
        for (PermissionEntity permissionEntity : permissions) {
            if (permissionEntity.getHierarchy() == 0) {
                permissionsRe.add(permissionEntity);
                continue;
            }
            for (RolePermissionEntity rolePermissionEntity : rolePermissionList) {
                if (permissionEntity.getId().intValue() == rolePermissionEntity.getPermissionId().intValue()) {
                    permissionsRe.add(permissionEntity);
                    break;
                }
            }
        }

        //menu tree
        PermissionTreeEntity permissionTree = new PermissionTreeEntity(true);
        PermissionEntity root = new PermissionEntity();
        root.setId(0);
        root.setHierarchy(-1);
        permissionTree.setEntity(root);

        //func tree
        PermissionTreeEntity funcTree = new PermissionTreeEntity(true);
        PermissionEntity funcRoot = new PermissionEntity();
        funcRoot.setId(0);
        funcTree.setEntity(funcRoot);

        for (PermissionEntity permissionEntity : permissionsRe) {
            if (1 == permissionEntity.getType()) {
                permissionTree.add(permissionEntity);
            }
            if (2 == permissionEntity.getType()) {
                funcTree.add(permissionEntity);
            }
        }
        List<PermissionEntity> list = permissionTree.toShowList();
        List<PermissionEntity> funcList = funcTree.toShowList();

        //wechat list
        WeChatPermissionListRequest weChatPermissionListRequest = new WeChatPermissionListRequest();
        weChatPermissionListRequest.setPaging(new Page(Integer.MAX_VALUE));
        weChatPermissionListRequest.setOrderColumn("parentId");
        weChatPermissionListRequest.setOrderMode("asc");
        List<WeChatPermissionEntity> weChatPermissions = weChatPermission.getPermissionList(weChatPermissionListRequest).getObjectList();
        List<WeChatPermissionEntity> wePermissionsRe = new LinkedList<>();
        for (WeChatPermissionEntity weChatPermissionEntity : weChatPermissions) {
            if (weChatPermissionEntity.getHierarchy() == 0) {
                wePermissionsRe.add(weChatPermissionEntity);
                continue;
            }
            for (RolePermissionEntity rolePermissionEntity : rolePermissionList) {
                if (weChatPermissionEntity.getId().intValue() == rolePermissionEntity.getPermissionId().intValue()) {
                    wePermissionsRe.add(weChatPermissionEntity);
                    break;
                }
            }
        }

        PermissionTreeEntity wePermissionTree = new PermissionTreeEntity(true);
        WeChatPermissionEntity weroot = new WeChatPermissionEntity();

        weroot.setId(0);
        weroot.setHierarchy(-1);
        wePermissionTree.setWeChatEntity(weroot);
        for (WeChatPermissionEntity wepermissionEntity : wePermissionsRe) {
            wePermissionTree.addWeEntity(wepermissionEntity);
        }
        List<WeChatPermissionEntity> welist = wePermissionTree.toWechatShowList();

        model.addAttribute("permissions", list);
        model.addAttribute("wepermissions", welist);
        model.addAttribute("funcList", funcList);

        return getAutoUrl();
    }

    /**
     * 去新增权限
     *
     * @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 createPermission(
            @Valid PermissionVo vo, BindingResult result, RedirectAttributes redirectAttributes,
            HttpServletRequest httpRequest, Model model
    ) {
        PermissionEntity entity = vo.getEntity();

        Integer parentId = entity.getParentId();
        if (parentId == null) {
            entity.setHierarchy(0);
        } else {
            entity.setHierarchy(permission.getPermissionById(parentId).getEntity().getHierarchy() + 1);
        }

        UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        Date date = new Date();
        entity.setType(1);
        entity.setCreateUserid(userEntity.getId());
        entity.setCreateUsername(userEntity.getName());
        entity.setCreateTime(date);
        entity.setUpdateUserid(userEntity.getId());
        entity.setUpdateUsername(userEntity.getName());
        entity.setUpdateTime(date);
        entity.setIsShow("1");
        entity.setPermission(entity.getCode());
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                PermissionRequest request = new PermissionRequest();
                request.setEntity(entity);
                PermissionResponse response = permission.addPermission(request);
                Integer id = response.getEntity().getId();
                return "redirect:/permission/" + 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++) {
                    permission.deletePermissionById(Integer.valueOf(ids[i]));
                }
            } else {
                permission.deletePermissionById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看权限
     *
     * @param id 权限页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        PermissionResponse response = permission.getPermissionById(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) {
        PermissionResponse response = permission.getPermissionById(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 updatePermission(
            @Valid PermissionVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes,
            Model model
    ) {
        PermissionEntity 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 {
                PermissionRequest request = new PermissionRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused") PermissionResponse rersponse = permission.updatePermission(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/permission/" + 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) {
        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_ORIGIN_DEPT_KEY);

        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(300);
        if (null != number) {
            page.setCurrentPage(number);
        }
        if (!PathUtil.isAdminDept(dept)) {
            searchParams.put("EQ_special", false);
        }

        PermissionListRequest listRequest = new PermissionListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        listRequest.setOrderColumn("parentId");
        listRequest.setOrderMode("asc");
        PermissionListResponse response = permission.getPermissionList(listRequest);
        model.addAttribute("page", response.getPaging());
        List<PermissionEntity> permissionList = response.getObjectList();

        PermissionTreeEntity permissionTree = new PermissionTreeEntity(true);
        PermissionEntity root = new PermissionEntity();
        root.setId(0);
        permissionTree.setEntity(root);
        for (PermissionEntity permissionEntity : permissionList) {
            permissionTree.add(permissionEntity);
        }
        List<PermissionEntity> list = permissionTree.toList();
        model.addAttribute("permissions", list);
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    private String levelStr(Integer level) {
        String result = "";
        if (level == null || level == 0) {
            return result;
        }

        for (int i = 0; i < level; i++) {
            result += "      ";
        }
        return result;
    }
}
