package com.muchinfo.mtp3century.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.IRolefuncmenuService;
import com.muchinfo.mtp3century.service.ISystemRoleService;
import com.muchinfo.mtp3common.enumtype.MessageType;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.SystemRoleVo;
import com.muchinfo.mtp3common.enumtype.Constants;
import com.muchinfo.mtp3common.enumtype.SysConstants;
import com.muchinfo.mtp3common.enumtype.SysEnums;
import com.muchinfo.mtp3century.utils.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SystemRoleServiceImpl implements ISystemRoleService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ISystemmanagerroleMapper iSystemmanagerroleMapper;
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private IRolefuncmenuService iRolefuncmenuService;
    @Resource
    private IRolefuncmenuMapper iRolefuncmenuMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private IFuncmenulistMapper iFuncmenulistMapper;
    @Resource
    private IRoleuserMapper iRoleuserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult dealRoleMenus(SystemRoleVo systemRoleVo, HttpServletRequest request) {
        log.info("当前角色权限信息={}", systemRoleVo);
        //获取当前登录用户
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        //判断当前角色权限信息是否存在，存在则更改
        Systemmanagerrole role = iSystemmanagerroleMapper.selectOne(new QueryWrapper<Systemmanagerrole>().eq("ROLENAME", systemRoleVo.getRolename()));
        if (ObjectUtils.isEmpty(systemRoleVo.getAutoid())) {
            if (Objects.nonNull(role)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ROLE_ERROR_CODE_001.getCode(), request.getHeader("Accept-Language"));
            }
            Systemmanagerrole systemmanagerrole = new Systemmanagerrole();
            getSystemManagerRole(systemRoleVo, systemmanagerrole, systemmanager);
            iSystemmanagerroleMapper.insert(systemmanagerrole);
            //添加菜单权限信息
            insertRoleMenu(systemRoleVo, systemmanagerrole.getAutoid());
        } else {
            Systemmanagerrole currentRole = iSystemmanagerroleMapper.selectOne(new QueryWrapper<Systemmanagerrole>().eq("AUTOID", systemRoleVo.getAutoid()));
            //更新数据信息
            getSystemManagerRole(systemRoleVo, currentRole, systemmanager);
            iSystemmanagerroleMapper.update(currentRole, new QueryWrapper<Systemmanagerrole>().eq("AUTOID", currentRole.getAutoid()));
            //清空角色菜单权限后重新插入
            iRolefuncmenuMapper.delete(new QueryWrapper<Rolefuncmenu>().eq("ROLEID", currentRole.getAutoid()));
            //重新插入菜单权限信息
            insertRoleMenu(systemRoleVo, currentRole.getAutoid());
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult deleteRoleMenus(SystemRoleVo systemRoleVo, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));

        Systemmanagerrole systemmanagerrole = iSystemmanagerroleMapper.selectOne(new QueryWrapper<Systemmanagerrole>().eq("autoid", systemRoleVo.getAutoid()));
        if(systemmanagerrole!=null && systemmanager.getAreauserid().compareTo(systemmanagerrole.getAreauserid()) != 0){
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }

        // 判断 用户类型和角色类型
        List<Roleuser> roleUsers = iRoleuserMapper.selectList(new QueryWrapper<Roleuser>()
                .eq("roleid",systemRoleVo.getAutoid())
                .eq("roletype", systemmanager.getReletype()));
        if(!CollectionUtils.isEmpty(roleUsers)){
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM019.getCode(), request.getHeader("Accept-Language"));
        }

        //获取当前登录用户
        iRoleuserMapper.delete(new QueryWrapper<Roleuser>().eq("roleid",systemRoleVo.getAutoid()));
        iSystemmanagerroleMapper.delete(new QueryWrapper<Systemmanagerrole>().eq("autoid", systemRoleVo.getAutoid()));
        iRolefuncmenuMapper.delete(new QueryWrapper<Rolefuncmenu>().eq("ROLEID", systemRoleVo.getAutoid()));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<SystemRoleVo> query(Integer type, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));

        SystemRoleVo systemRoleVo = new SystemRoleVo();
        systemRoleVo.setRoletype(SysConstants.SYS_TYPE_MANAGE);
        systemRoleVo.setType(type);
        systemRoleVo.setAreauserid(systemmanager.getAreauserid());
        IPage<SystemRoleVo> page = new Page<>(pageNum, pageSize);
        IPage<SystemRoleVo> systemRoleVoPage = iSystemmanagerroleMapper.selectByPage(page, systemRoleVo);
        //列表返回
        PageResult<SystemRoleVo> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(systemRoleVoPage.getPages());
        pageResult.setCurrent(systemRoleVoPage.getCurrent());
        pageResult.setTotal(systemRoleVoPage.getTotal());
        pageResult.setPageSize(systemRoleVoPage.getSize());
        pageResult.setData(systemRoleVoPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<SystemRoleVo> queryDetail(Integer autoId, HttpServletRequest request) {
        Systemmanagerrole systemmanagerrole = iSystemmanagerroleMapper.selectOne(new QueryWrapper<Systemmanagerrole>().eq("autoid", autoId));
        SystemRoleVo systemRoleVo = new SystemRoleVo();
        BeanUtils.copyProperties(systemmanagerrole, systemRoleVo);
        List<String> strings = new ArrayList<>();
        strings.add(String.valueOf(systemmanagerrole.getAutoid()));
        List<Funcmenulist> funcmenulists = iFuncmenulistMapper.fingByAuthorities(strings, 6);
        //获取所有菜单
        List<String> nameList = funcmenulists.stream().map(Funcmenulist::getResourcecode).collect(Collectors.toList());
        systemRoleVo.setMenuids(nameList);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), systemRoleVo);
    }

    @Override
    public AjaxResult<SystemRoleVo> queryByAdd(HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        SystemRoleVo systemRoleVo = new SystemRoleVo();
        systemRoleVo.setRoletype(SysConstants.SYS_TYPE_MANAGE);
        systemRoleVo.setType(2);
        systemRoleVo.setAreauserid(systemmanager.getAreauserid());
        List<SystemRoleVo> systemRoleVoList = iSystemmanagerroleMapper.selectByPage(systemRoleVo);
        systemRoleVoList.forEach(a -> {
            a.setModifiername(systemmanager.getUsername());
        });
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), systemRoleVoList);
    }

    private void insertRoleMenu(SystemRoleVo systemRoleVo, Long autoId) {
        if (systemRoleVo.getMenuids() != null) {
            List<Rolefuncmenu> rolefuncmenus = new ArrayList<>();
            for (String menucode : systemRoleVo.getMenuids()) {
                Rolefuncmenu mr = new Rolefuncmenu();
                mr.setResourcecode(menucode);
                mr.setRoleid(autoId);
                rolefuncmenus.add(mr);
            }
            iRolefuncmenuService.saveBatchYourEntities(rolefuncmenus);
        }
    }

    private void getSystemManagerRole(SystemRoleVo systemRoleVo, Systemmanagerrole systemmanagerrole, Systemmanager systemmanager) {
        systemmanagerrole.setRoletype(SysConstants.SYS_TYPE_MANAGE);
        systemmanagerrole.setRolename(systemRoleVo.getRolename());
        systemmanagerrole.setAreauserid(systemmanager.getAreauserid());
        systemmanagerrole.setModifierid(systemmanager.getAutoid());
        systemmanagerrole.setModifytime(new Date());
        systemmanagerrole.setRolestatus(SysEnums.SysStatus.ok.getCode());
        systemmanagerrole.setSensitivefields(systemRoleVo.getSensitivefields());
        systemmanagerrole.setSystemtype(2);
    }
}
