package com.tykj.workflowcore.user.controller;

import com.sun.istack.NotNull;
import com.tykj.workflowcore.user.dao.AuthorityOrganizationDao;
import com.tykj.workflowcore.user.pojo.*;
import com.tykj.workflowcore.user.pojo.vo.OrgAuthLogVo;
import com.tykj.workflowcore.user.pojo.vo.PageResponse;
import com.tykj.workflowcore.user.pojo.vo.ServerResponse;
import com.tykj.workflowcore.user.pojo.vo.uservo.*;
import com.tykj.workflowcore.user.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/authOrg")
@Api(tags = "组织架构权限管理")
public class AuthorityOrganizationController {
    @Autowired
    private AuthorityOrganizationService authorityOrganizationService;
    @Autowired
    private LogContentService logContentService;
    @Autowired
    private AuthorityOrganizationDao authorityOrganizationDao;
    @Autowired
    private UserAuthorityService userAuthorityService;
    @Autowired
    private CenterUserService centerUserService;
    @Autowired
    private AuthorityService authorityService;

    @ApiOperation("根据组织架构id 查找该组织架构的权限")
    @PostMapping("/authList")
    public ServerResponse authList(@Validated @RequestBody AuthOrgVo authOrgVo) {
        List<Authority> authorityList = authorityOrganizationService.findByOrgId(authOrgVo.getOrgId());
        if (authorityList != null) {

            return ServerResponse.ok(authorityList);
        }
        return ServerResponse.error("查看组织架构权限失败");
    }

    @ApiOperation("为组织架构分配权限")
    @PostMapping("/addAuth")
    public ServerResponse addAuth(@Validated @RequestBody AuthOrgLogVo authOrgLogVo){
        LogContent logContent = new LogContent();
        logContent.setOperator(authOrgLogVo.getLoginer());
        logContent.setOperateTime(new Date());
        logContent.setContent("为组织架构分配权限");

        ArrayList<OrgAuthsVo> orgAuthsVos = new ArrayList<>();
        List<Integer> orgIds = authOrgLogVo.getOrgIds();
        List<Integer> authIds = authOrgLogVo.getAuthIds();
        for (Integer orgId : orgIds) {
            OrgAuthsVo orgAuthsVo = new OrgAuthsVo();
            List<AuthorityOrganization> authorityOrganizations = authorityOrganizationService.findAllByOrgId(orgId);
        List<Authority> authorityList = authorityOrganizationService.findByOrgId(orgId);
        //删除多余的权限
        for (Authority authority : authorityList) {
            if (!authIds.contains(authority.getId())){
                AuthorityOrganization authorityOrganization = authorityOrganizationDao.findByOrgIdAndAuthId(orgId, authority.getId());
                authorityOrganizationDao.delete(authorityOrganization);
            }
        }
        //在更新之后的组织权限映射表中添加 之前没有的权限
        for (Integer authId : authIds) {
            AuthorityOrganization authorityOrganization2 = authorityOrganizationService.findByOrgIdAndAuthId(orgId, authId);
            if (!authorityOrganizations.contains(authorityOrganization2)) {
                AuthorityOrganization authorityOrganization = new AuthorityOrganization();
                authorityOrganization.setAuthId(authId);
                authorityOrganization.setOrgId(orgId);
                AuthorityOrganization authorityOrganization1 = authorityOrganizationDao.save(authorityOrganization);
                authorityOrganizations.add(authorityOrganization1);
            }
        }
        //为组织架构分配完权限之后，也要为该组织架构所有人员分配权限
        List<User> userList = centerUserService.findAllByOrganizationId(orgId);
        if (userList!=null){
            for (User user : userList) {
                List<Integer> authIdList = userAuthorityService.findAuthByUid(user.getId());
                for (Integer authId : authOrgLogVo.getAuthIds()) {
                    Authority authority = authorityService.findById(authId);
                    if (!authIdList.contains(authId) && authority!=null){
                        UserAuthority userAuthority = new UserAuthority();
                        userAuthority.setUid(user.getId());
                        userAuthority.setAuthorityId(authId);
                        userAuthority.setName(authority.getName());
                        userAuthority.setType(authority.getType());
                        userAuthorityService.save(userAuthority);
                    }
                }
            }
            if (authorityOrganizations!=null){
                orgAuthsVo.setOrgId(orgId);
                orgAuthsVo.setOrgs(authorityOrganizations);
                orgAuthsVos.add(orgAuthsVo);
            }
        }
        }
        if (orgAuthsVos!=null){
            logContent.setResult("操作成功");
            logContentService.save(logContent);
            return ServerResponse.ok(orgAuthsVos);
        }

        logContent.setResult("操作失败");
        logContentService.save(logContent);
        return ServerResponse.error("分配失败");
    }



    @ApiOperation("为权限分配组织架构")
    @PostMapping("/addClientAuth")
    public ServerResponse addClientAuth(@Validated @RequestBody OrgAuthLogVo orgAuthLogVo){
        LogContent logContent = new LogContent();
        logContent.setOperator(orgAuthLogVo.getLoginer());
        logContent.setOperateTime(new Date());
        logContent.setContent("为权限分配组织架构");

        List<Integer> orgIdList = orgAuthLogVo.getOrgIds();
        Integer authId = orgAuthLogVo.getAuthId();
        List<AuthorityOrganization> authorityOrganizationList = new ArrayList<>();

        //删除该权限原来不需要的一些组织架构
        List<AuthorityOrganization> authorityOrganizations = authorityOrganizationService.findByAuthId(authId);
        if (authorityOrganizations != null){
            for (AuthorityOrganization authorityOrganization : authorityOrganizations) {
                if (authorityOrganization!=null && !orgIdList.contains(authorityOrganization.getOrgId())){
                    authorityOrganizationDao.delete(authorityOrganization);
                }
                if (authorityOrganization!=null && orgIdList.contains(authorityOrganization.getOrgId())){
                    orgIdList.remove(authorityOrganization.getOrgId());
                    authorityOrganizationList.add(authorityOrganization);
                }

            }
        }
        //增加新添加的组织架构

        Authority authority = authorityService.findById(authId);
        for (Integer orgId : orgIdList) {
            AuthorityOrganization authorityOrganization = new AuthorityOrganization();
            authorityOrganization.setOrgId(orgId);
            authorityOrganization.setAuthId(authId);
            authorityOrganization.setName(authority.getName());
            authorityOrganization.setType(authority.getType());
            authorityOrganizationService.save(authorityOrganization);
            authorityOrganizationList.add(authorityOrganization);
        }

        //为组织架构分配完权限之后，也要为该组织架构所有人员分配权限
        for (Integer orgId : orgIdList) {
            List<User> userList = centerUserService.findAllByOrganizationId(orgId);
            if (userList!=null){
                for (User user : userList) {
                    List<Integer> authIdList = userAuthorityService.findAuthByUid(user.getId());
                    Authority authority1 = authorityService.findById(authId);
                    if (authority1!=null &&  authIdList!=null && !authIdList.contains(authId) ){
                        UserAuthority userAuthority = new UserAuthority();
                        userAuthority.setUid(user.getId());
                        userAuthority.setAuthorityId(authId);
                        userAuthority.setName(authority.getName());
                        userAuthority.setType(authority.getType());
                        userAuthorityService.save(userAuthority);
                    }
                }
            }
        }
        if (authorityOrganizationList != null){
            logContent.setResult("操作成功");
            logContentService.save(logContent);
            return ServerResponse.ok(authorityOrganizationList);
        }
        logContent.setResult("操作失败");
        logContentService.save(logContent);
        return ServerResponse.error("操作失败");
    }


    @ApiOperation("根据权限id 查找组织架构")
    @PostMapping("/orgList")
    public ServerResponse orgList(@Validated @RequestBody OrgAuthVo orgAuthVo) {
        int page = orgAuthVo.getPage();
        int size = orgAuthVo.getSize();
        PageResponse<Organization> organizationList = authorityOrganizationService.findByAuthId(orgAuthVo.getAuthId(), page, size);
        if (organizationList!= null){
            return ServerResponse.ok(organizationList);
        }
        return ServerResponse.error("未找到该组织架构");
    }

    @ApiOperation("为组织架构删除某个权限")
    @DeleteMapping("/delete")
    public ServerResponse delete(@NotNull @RequestBody DelOrgAuthVo delOrgAuthVo) {
        LogContent logContent = new LogContent();
        logContent.setOperator(delOrgAuthVo.getLoginer());
        logContent.setOperateTime(new Date());
        logContent.setContent("为组织架构删除权限");

        try {
            authorityOrganizationService.delete(delOrgAuthVo.getOrgId(),delOrgAuthVo.getAuthId());
        }catch (Exception e) {
            logContent.setResult("操作失败");
            logContentService.save(logContent);
            return ServerResponse.error("删除失败");
        }
        logContent.setResult("操作成功");
        logContentService.save(logContent);
        return ServerResponse.ok("删除成功");
    }

}






