package com.bonus.gs.sub.evaluate.manager.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.bonus.gs.sub.evaluate.evaluate.beans.OutSourceBean;
import com.bonus.gs.sub.evaluate.evaluate.beans.TeamEvaluateBean;
import com.bonus.gs.sub.evaluate.evaluate.dao.OutsourcerEvaluateDao;
import com.bonus.gs.sub.evaluate.evaluate.service.OutsourcerEvaluateService;
import com.bonus.gs.sub.evaluate.evaluate.service.TeamEvaluateService;
import com.bonus.gs.sub.evaluate.manager.annotation.LogAnnotation;
import com.bonus.gs.sub.evaluate.manager.dao.PermissionDao;
import com.bonus.gs.sub.evaluate.manager.entity.LoginUser;
import com.bonus.gs.sub.evaluate.manager.model.Permission;
import com.bonus.gs.sub.evaluate.manager.service.PermissionService;
import com.bonus.gs.sub.evaluate.manager.utils.AjaxRes;
import com.bonus.gs.sub.evaluate.manager.utils.GlobalConst;
import com.bonus.gs.sub.evaluate.manager.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;

/**
 * 权限相关接口
 */
@Api(tags = "权限")
@RestController
@RequestMapping("/permissions")
@Slf4j
public class PermissionController {

    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private PermissionService permissionService;
    @Resource
    private OutsourcerEvaluateService outsourcerEvaluateService;
    @Resource
    private OutsourcerEvaluateDao outsourcerEvaluateDao;

    @Autowired
    private TeamEvaluateService service;

    @ApiOperation(value = "当前登录用户拥有的权限")
    @GetMapping("/current")
    public List<Permission> permissionsCurrent() {
        LoginUser loginUser = UserUtil.getLoginUser();
        List<Permission> list = loginUser.getPermissions();
        final List<Permission> permissions = list.stream().filter(l -> l.getType().equals(1))
                .collect(Collectors.toList());

//		setChild(permissions);
//
//		return permissions.stream().filter(p -> p.getParentId().equals(0L)).collect(Collectors.toList());
        // 2018.06.09 支持多级菜单
        List<Permission> firstLevel = permissions.stream().filter(p -> p.getParentId().equals(0L)).collect(Collectors.toList());
        firstLevel.parallelStream().forEach(p -> {
            setChild(p, permissions);
        });

        List<OutSourceBean> outSourceBeans = checkExamine(new OutSourceBean());
        List<TeamEvaluateBean> teamEvaluateBeans = TeamEvaluateBean(new TeamEvaluateBean());
        for (Permission permission : firstLevel) {
            permission.getChild().forEach(c -> {
                if (c.getHref().equals("pages/evaluate/outsourceAudit/outsourceAuditList.html")) {
                    for (OutSourceBean outSourceBean : outSourceBeans) {
                        if ((Integer.parseInt(outSourceBean.getEvaluateNum())) > 0 && (Integer.parseInt(outSourceBean.getIsApprove())) == 0){
                            c.setIsCheck(1);
                        }
                    }
                }
            });
            permission.getChild().forEach(cc -> {
                cc.getChild().forEach(c -> {
                    if (c.getHref().equals("pages/evaluate/team/evaluateCheckList.html")) {
                        for (TeamEvaluateBean teamEvaluateBean : teamEvaluateBeans) {
                            if ("5".equals(loginUser.getRoleId()) ||
                                    Arrays.asList(loginUser.getRoleId().split(",")).contains("5")) {
                                if ("1".equals(teamEvaluateBean.getStatus())) {
                                    if ("待审核".equals(teamEvaluateBean.getCheckStatus())) {
                                        c.setIsCheck(1);
                                    }
                                }
                            }
                            if ("6".equals(loginUser.getRoleId()) ||
                                    Arrays.asList(loginUser.getRoleId().split(",")).contains("6")) {
                                if (!"1".equals(teamEvaluateBean.getStatus())) {
                                    if ("待审核".equals(teamEvaluateBean.getCheckStatus())) {
                                        c.setIsCheck(1);
                                    }
                                }
                            }
                        }
                    }
                });
            });
        }
        return firstLevel;
    }

    private List<OutSourceBean> checkExamine(OutSourceBean o) {
        try {
            o.setDeptId(UserUtil.getLoginUser().getDeptId());
            String isBusinessDivision = outsourcerEvaluateDao.getIsBusinessDivision(o.getDeptId());
            if (!org.apache.commons.lang3.StringUtils.isBlank(isBusinessDivision) && "1".equals(isBusinessDivision)) {
                o.setIsBusinessDivision("1");
            } else {
                o.setIsBusinessDivision("0");
            }
            List<OutSourceBean> list = outsourcerEvaluateService.getEvaluateAuditList(o);
            return list;
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return new ArrayList<>();
    }
    private List<TeamEvaluateBean> TeamEvaluateBean(TeamEvaluateBean o) {
        List<TeamEvaluateBean> list = service.getTeamEvaluateList(o);
        for (TeamEvaluateBean bean : list) {
            String sendPhone = bean.getSendPhone();
            if (org.apache.commons.lang3.StringUtils.isBlank(sendPhone)) {
                String sendPhone2 = service.getSendPhone(bean);
                bean.setSendPhone(sendPhone2);
            }
        }
        return list;
    }

    /**
     * 设置子元素
     * 2018.06.09
     *
     * @param p
     * @param permissions
     */
    private void setChild(Permission p, List<Permission> permissions) {
        List<Permission> child = permissions.parallelStream().filter(a -> a.getParentId().equals(p.getId())).collect(Collectors.toList());
        p.setChild(child);
        if (!CollectionUtils.isEmpty(child)) {
            child.parallelStream().forEach(c -> {
                //递归设置子元素，多级菜单支持
                setChild(c, permissions);
            });
        }
    }

//	private void setChild(List<Permission> permissions) {
//		permissions.parallelStream().forEach(per -> {
//			List<Permission> child = permissions.stream().filter(p -> p.getParentId().equals(per.getId()))
//					.collect(Collectors.toList());
//			per.setChild(child);
//		});
//	}

    /**
     * 菜单列表
     *
     * @param pId
     * @param permissionsAll
     * @param list
     */
    private void setPermissionsList(Long pId, List<Permission> permissionsAll, List<Permission> list) {
        for (Permission per : permissionsAll) {
            if (per.getParentId().equals(pId)) {
                list.add(per);
                if (permissionsAll.stream().filter(p -> p.getParentId().equals(per.getId())).findAny() != null) {
                    setPermissionsList(per.getId(), permissionsAll, list);
                }
            }
        }
    }

    @GetMapping
    @ApiOperation(value = "菜单列表")
    @PreAuthorize("hasAuthority('sys:menu:query')")
    public List<Permission> permissionsList() {
        List<Permission> permissionsAll = permissionDao.listAll();

        List<Permission> list = Lists.newArrayList();
        setPermissionsList(0L, permissionsAll, list);

        return list;
    }

    @GetMapping("/all")
    @ApiOperation(value = "所有菜单")
    @PreAuthorize("hasAuthority('sys:menu:query')")
    public JSONArray permissionsAll() {
        List<Permission> permissionsAll = permissionDao.listAll();
        JSONArray array = new JSONArray();
        setPermissionsTree(0L, permissionsAll, array);

        return array;
    }

    @GetMapping("/parents")
    @ApiOperation(value = "一级菜单")
    @PreAuthorize("hasAuthority('sys:menu:query')")
    public List<Permission> parentMenu() {
        List<Permission> parents = permissionDao.listParents();

        return parents;
    }

    /**
     * 菜单树
     *
     * @param pId
     * @param permissionsAll
     * @param array
     */
    private void setPermissionsTree(Long pId, List<Permission> permissionsAll, JSONArray array) {
        for (Permission per : permissionsAll) {
            if (per.getParentId().equals(pId)) {
                String string = JSONObject.toJSONString(per);
                JSONObject parent = (JSONObject) JSONObject.parse(string);
                array.add(parent);

                if (permissionsAll.stream().filter(p -> p.getParentId().equals(per.getId())).findAny() != null) {
                    JSONArray child = new JSONArray();
                    parent.put("child", child);
                    setPermissionsTree(per.getId(), permissionsAll, child);
                }
            }
        }
    }

    @GetMapping(params = "roleId")
    @ApiOperation(value = "根据角色id获取权限")
    @PreAuthorize("hasAnyAuthority('sys:menu:query','sys:role:query')")
    public List<Permission> listByRoleId(Long roleId) {
        return permissionDao.listByRoleId(roleId);
    }

    @LogAnnotation
    @PostMapping
    @ApiOperation(value = "保存菜单")
    @PreAuthorize("hasAuthority('sys:menu:add')")
    public void save(@RequestBody Permission permission) {
        permissionDao.save(permission);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据菜单id获取菜单")
    @PreAuthorize("hasAuthority('sys:menu:query')")
    public Permission get(@PathVariable Long id) {
        return permissionDao.getById(id);
    }

    @LogAnnotation
    @PutMapping
    @ApiOperation(value = "修改菜单")
    @PreAuthorize("hasAuthority('sys:menu:add')")
    public void update(@RequestBody Permission permission) {
        permissionService.update(permission);
    }

    /**
     * 校验权限
     *
     * @return
     */
    @GetMapping("/owns")
    @ApiOperation(value = "校验当前用户的权限")
    public Set<String> ownsPermission() {
        List<Permission> permissions = UserUtil.getLoginUser().getPermissions();
        if (CollectionUtils.isEmpty(permissions)) {
            return Collections.emptySet();
        }

        return permissions.parallelStream().filter(p -> !StringUtils.isEmpty(p.getPermission()))
                .map(Permission::getPermission).collect(Collectors.toSet());
    }

    @LogAnnotation
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除菜单")
    @PreAuthorize("hasAuthority('sys:menu:del')")
    public void delete(@PathVariable Long id) {
        permissionService.delete(id);
    }
}
