package cn.com.ctop.common.service.impl;

import cn.com.ctop.common.entity.SysRole;
import cn.com.ctop.common.entity.UserCompany;
import cn.com.ctop.common.mapper.SysRoleMapper;
import cn.com.ctop.common.mapper.SysUserMapper;
import cn.com.ctop.common.service.ISysDepartService;
import cn.com.ctop.common.service.IUserCompanyService;
import cn.com.ctop.common.utils.Check;
import cn.com.ctop.common.service.ISysRoleService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @Author scott
 * @since 2018-12-19
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Resource
    IUserCompanyService userCompanyService;
    @Autowired
    private ISysDepartService sysDepartService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRole(String roleid) {
        //1.删除角色和用户关系
        sysRoleMapper.deleteRoleUserRelation(roleid);
        //2.删除角色和权限关系
        sysRoleMapper.deleteRolePermissionRelation(roleid);
        //3.删除角色
        this.removeById(roleid);
        return true;
    }

    @Override
    public boolean deleteBatchRole(String[] roleids) {
        return false;
    }


    /**
     * 根据userId获取角色code
     *
     * @param userId
     * @return
     */
    @Override
    public String getRoleCodeByUserId(String userId) {
        return sysRoleMapper.getRoleCodeByUserId(userId);
    }

    @Override
    public List<String> getCompanyUsers(String roleCode, String userId) {
        UserCompany userCompany = userCompanyService.getByUserId(userId);
        if (Check.isNull(userCompany)) {
            return null;
        }
        List<String> ids = new ArrayList<>();
        String companyId = userCompany.getCompanyId();
        if ("CompanyManager".equals(roleCode)) {
            ids = userCompanyService.getUserIdListByCompanyId(companyId);
        } else if ("bytedanceDirector".equals(roleCode)) {
            JSONObject obj = sysUserMapper.getDepart(companyId);
            ids = sysDepartService.getAllUserIdsByDepId(obj.getString("tt_depart_id"));
        } else if ("kuaishouDirector".equals(roleCode)) {
            JSONObject obj = sysUserMapper.getDepart(companyId);
            ids = sysDepartService.getAllUserIdsByDepId(obj.getString("ks_depart_id"));
        }
        return ids;
    }

}
