package com.app.admin.framework.system.organization.service.impl;

import com.app.admin.framework.system.administrator.model.SysAdministrator;
import com.app.admin.framework.system.administrator.service.SysAdministratorService;
import com.app.admin.framework.system.organization.model.SysOrganization;
import com.app.admin.framework.system.organization.service.SysOrgPowerService;
import com.app.admin.framework.system.organization.service.SysOrganizationService;
import com.app.admin.framework.system.organization.view.SysOrganizationView;
import com.app.admin.framework.system.permission.authorization.model.SysAdministratorRole;
import com.app.admin.framework.system.permission.authorization.service.SysAdministratorRoleService;
import com.app.admin.framework.system.permission.role.model.SysRole;
import com.app.admin.framework.system.permission.role.service.SysRoleService;
import com.app.framework.core.support.auth.LoginUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 机构权限管理
 */
@Service
public class SysOrgPowerServiceImpl implements SysOrgPowerService {

    @Resource
    SysOrganizationService sysOrganizationService;

    @Resource
    SysAdministratorService sysAdministratorService;

    @Resource
    SysRoleService sysRoleService;

    @Resource
    SysAdministratorRoleService sysAdministratorRoleService;

    public void saveOrg(SysOrganizationView view, LoginUser loginUser) {
        //保存机构
        SysOrganization organization = sysOrganizationService.saveOrganization(view, loginUser);
        //保存管理员
        SysAdministrator administrator = new SysAdministrator();
        administrator.setRealName(view.getAdministratorRealName());
        administrator.setUsername(view.getAdministratorUsername());
        administrator.setPassword(view.getAdministratorPassword());
        administrator.setOrganizationId(organization.getId());
        administrator.setState(organization.getState());
        administrator.setCreateUserId(loginUser.getId());
        SysAdministrator orgAdministrator = sysAdministratorService.saveOrgAdministrator(administrator);
        //保存管理员角色
        SysRole orgAdminRole = sysRoleService.saveOrgAdminRole(organization.getId(), loginUser);
        //保存管理员与角色关联
        sysAdministratorRoleService.createIfAbsent(orgAdministrator.getOid(), orgAdminRole.getOid());
    }

    /**
     * 根据机构ID加载管理权限
     *
     * @param organizationId 机构ID
     * @return
     */
    public SysAdministratorRole getOrgPower(Long organizationId) {
        SysAdministrator administrator = sysAdministratorService.getOrgAdministrator(organizationId);
        SysRole role = sysRoleService.getOrgAdminRole(organizationId);
        return sysAdministratorRoleService.createIfAbsent(administrator.getOid(), role.getOid());
    }

}
