package com.community.huiju.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.huiju.dao.*;
import com.community.huiju.exception.WisdomException;
import com.community.huiju.model.*;
import com.community.huiju.service.IToSysRoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色业务
 * @author weiximei
 */
@Service("iToSysRoleService")
@Slf4j
public class ToSysRoleServiceImpl implements IToSysRoleService {

    @Autowired
    private ToSysRoleMapper toSysRoleMapper;

    @Autowired
    private ToSysRoleMenuMapper toSysRoleMenuMapper;

    @Autowired
    private ToUserMapper toUserMapper;

    @Autowired
    private ToSysUserRoleMapper toSysUserRoleMapper;

    @Override
    public List<ToSysRole> selectRoleByUserId(Integer userId) {

        return toSysRoleMapper.selectRoleByUserId(userId);
    }

    @Override
    public ResponseBean getAll(String parameter) {
        ResponseBean responseBean = new ResponseBean();

        JSONObject jsonObject = JSONObject.parseObject(parameter);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        String roleName = jsonObject.getString("roleName").trim();

        Page<ToSysRole> pageInfo = PageHelper.startPage(pageNum, pageSize);
        List<ToSysRole> roleList = toSysRoleMapper.selectAll(roleName);
        roleList.forEach(e -> {
            ToUser createUser = toUserMapper.selectByPrimaryKey(e.getCreateUser());
            e.setCreateUserName(createUser.getUserName());
            ToUser updateUser = toUserMapper.selectByPrimaryKey(e.getUpdateUser());
            if (null != updateUser) {
                e.setUpdateUserName(updateUser.getUserName());
            }

        });

        Map<String, Object> resMap = new HashMap<>();
        resMap.put("list", roleList);
        resMap.put("pageNum", pageInfo.getPageNum());
        resMap.put("pageSize", pageInfo.getPageSize());
        resMap.put("total", pageInfo.getTotal());


        responseBean.addSuccess(resMap);
        return responseBean;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addRole(String parameter, UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();

        JSONObject jsonObject = JSONObject.parseObject(parameter);
        String roleName = jsonObject.getString("roleName");
        String description = jsonObject.getString("description");
        Integer [] menuIdArray = jsonObject.getJSONArray("menuArray").toArray(new Integer[] {});

        // 校验这个角色是否存在
        ToSysRole toSysRole = toSysRoleMapper.selectByRoleName(roleName);
        if (toSysRole != null) {
            responseBean.addError("角色已存在!");
            return responseBean;
        }

        ToSysRole createRole = new ToSysRole();
        createRole.setRoleName(roleName);
        createRole.setDescription(description);
        createRole.setCreateUser(userElement.getId());
        createRole.setCreateDate(new Date());
        //createRole.setUpdateUser(userElement.getId());
        //createRole.setUpdateDate(new Date());
        createRole.setStatus("1");
        int rows = toSysRoleMapper.insertSelective(createRole);

        // 存入角色和菜单关联
        insertRole(createRole, menuIdArray);

        responseBean.addSuccess("操作成功!");
        return responseBean;
    }

    /**
     * 添加角色菜单关联
     * @param toSysRole
     * @param menuIdArray
     */
    private void insertRole(ToSysRole toSysRole, Integer [] menuIdArray){
        if (null == menuIdArray || menuIdArray.length == 0) {
            throw new WisdomException("角色没有关联的菜单id");
        }
        List<ToSysRoleMenu> roleMenuList = new ArrayList<>();
        for (Integer menuId : menuIdArray) {
            ToSysRoleMenu toSysRoleMenu = new ToSysRoleMenu();
            toSysRoleMenu.setMenuId(menuId);
            toSysRoleMenu.setRoleId(toSysRole.getId());
            roleMenuList.add(toSysRoleMenu);
        }

        int rows = toSysRoleMenuMapper.banchInsert(roleMenuList);
        if (rows <= 0) {
            throw new WisdomException("创建角色失败!");
        }
    }

    @Override
    public ResponseBean getInfo(Integer id) {
        ResponseBean responseBean = new ResponseBean();
        ToSysRole toSysRole = toSysRoleMapper.selectByPrimaryKey(id);
        if (null == toSysRole || "0".equals(toSysRole.getStatus())) {
            responseBean.addError("角色不存在!");
            return responseBean;
        }

        List<ToSysRoleMenu> toSysRoleMenuList = toSysRoleMenuMapper.selectByRoleId(toSysRole.getId());
        Map<String, Object> map = Maps.newHashMap();
        map.put("info", toSysRole);
        map.put("menuIdList",toSysRoleMenuList);

        responseBean.addSuccess(map);
        return responseBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean updateRole(String parameter, UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();
        JSONObject jsonObject = JSONObject.parseObject(parameter);
        Integer id = jsonObject.getInteger("id");
        String roleName = jsonObject.getString("roleName");
        String description = jsonObject.getString("description");
        Integer [] menuIdArray = jsonObject.getJSONArray("menuArray").toArray(new Integer[] {});

        // 校验这个角色是否存在
        ToSysRole toSysRole = toSysRoleMapper.selectByPrimaryKey(id);
        if (null == toSysRole || "0".equals(toSysRole.getStatus())) {
            responseBean.addError("角色不存在!");
            return responseBean;
        }

        // 根据角色名称查询
        ToSysRole selectRole = toSysRoleMapper.selectByRoleName(roleName);
        // 如果 selectRole 不等于null, 并且 toSysRole 的id 和 selectRole 的id 不相等
        if (null != selectRole && toSysRole.getId().intValue() != selectRole.getId().intValue()) {
            responseBean.addError("角色已存在!");
            return responseBean;
        }

        toSysRole.setRoleName(roleName);
        toSysRole.setDescription(description);
        toSysRole.setUpdateDate(new Date());
        toSysRole.setUpdateUser(userElement.getId());
        toSysRoleMapper.updateByPrimaryKeySelective(toSysRole);

        // 删除旧权限
        toSysRoleMenuMapper.deleteByRoleId(toSysRole.getId());

        // 存入角色和菜单关联
        insertRole(toSysRole, menuIdArray);

        responseBean.addSuccess("操作成功!");
        return responseBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean deleteRole(List<Integer> ids, UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();
        ids.forEach(e ->{
//            List<ToSysUserRole> userRoleList = toSysUserRoleMapper.selelctByRoleId(e);
//            if (CollectionUtils.isNotEmpty(userRoleList)) {
//                throw new WisdomException("角色存在用户关联关系, 无法删除!");
//            }
            ToSysRole toSysRole = toSysRoleMapper.selectByPrimaryKey(e);
            if (null == toSysRole) {
                throw new WisdomException("删除失败, 角色编号 " + e + " 不存在!");
            }
            // 删除这个角色
            toSysRoleMapper.deleteByPrimaryKey(e);
            // 删除角色和菜单关联关系
            toSysRoleMenuMapper.deleteByRoleId(e);
        });
        // 删除这个角色和用户关联关系
        toSysUserRoleMapper.deleteByRoleId(ids);

        responseBean.addSuccess("操作成功!");
        return responseBean;
    }
}
