package com.ssm.manage.service.impl;

import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.BaseDao;
import com.ssm.manage.dao.SsmSysUserDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.UserRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.UserResponse;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.util.RedisClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class SsmSysUserServiceImpl extends BaseServiceImpl<SysUser> implements SsmSysUserService {

    @Autowired
    private RedisClient<UserResponse> redisClient;
    @Autowired
    private SsmSysRoleUserService ssmSysRoleUserService;
    @Autowired
    private SsmSysRoleService ssmSysRoleService;
    @Autowired
    private SsmSysRolePowerService ssmSysRolePowerService;
    @Autowired
    private SsmSysMenuPowerService ssmSysMenuPowerService;

    @Autowired
    private SsmSysUserDao dao;

    @Override
    public BaseDao<SysUser> getDao() {
        return dao;
    }

    @Override
    public PageInfo<SysUser> selectByPage(UserRequest userRequest) {
        return dao.selectByPage(userRequest);
    }

    @Override
    public int deleteSysUser(UserRequest userRequest) {
        return dao.deleteSysUser(userRequest);
    }

    @Override
    public int deleteSingleSysUser(UserRequest userRequest) {
        return dao.deleteByPrimaryKey(userRequest.getId());
    }

    @Override
    public int saveSysUser(SysUser sysUser, String userNum) throws SmsException {
        //校验手机是否已存在
        getUser(sysUser.getMobilePhone(),null);
        //校验账号是否已存在
        getUser(null,sysUser.getUserNum());
        //从redis获取当前操作人信息 将添加用户的创建人和创建时间进行赋值
        if (redisClient.hasKey(getKey(userNum))){
            UserResponse userResponse = redisClient.get(getKey(userNum));
            sysUser.setFounder(userResponse.getUserName());
            sysUser.setFounderDatetime(new Date());
        }
//        //生成动态密码 发送到当前生成用户的手机上
//        String code = ObjectUtils.toString((int)((Math.random()*9+1)*1000));
//        String msg = code+"(登录验证码，请完成验证)，如非本人操作，请忽略本短信。";
//        UserResponse userResponse = ChuangLanSmsUtil.sendSmsCode(Constant.smsUrl, Constant.smsAccount,
//                Constant.smsPassword, sysUser.getMobilePhone(), msg);
//        code = AESUtils.encrypt(code);
        // TODO 短信暂时拿掉 密码设为固定初始密码
        //生成主键ID
        sysUser.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        sysUser.setPassword(AESUtils.encrypt("123456"));
        sysUser.setState(1);
        int i = dao.saveNotNull(sysUser);
        return i;
    }

    @Override
    public int updateSysUser(SysUser sysUser, String userNum) throws SmsException {
        if (StringUtils.isNotBlank(sysUser.getMobilePhone())) {
            getUser(sysUser.getMobilePhone(), null);
        }

        //从redis获取当前操作人信息 将修改用户的修改人和修改时间进行赋值
        if (redisClient.hasKey(getKey(userNum))){
            UserResponse userResponse = redisClient.get(getKey(userNum));
            sysUser.setModifyBy(userResponse.getUserName());
            sysUser.setModifyDatetime(new Date());
        }
        int i = dao.updateByPrimaryKeySelective(sysUser);
        return i;
    }

    @Override
    public int updateSysUserState(UserRequest userRequest, String userNum){
        Example example = new Example(SysUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",userRequest.getId());
        SysUser sysUser = new SysUser();
        sysUser.setState(userRequest.getState());
        //从redis获取当前操作人信息 将修改用户的修改人和修改时间进行赋值
        if (redisClient.hasKey(getKey(userNum))){
            UserResponse userResponse = redisClient.get(getKey(userNum));
            sysUser.setModifyBy(userResponse.getUserName());
            sysUser.setModifyDatetime(new Date());
        }
        return dao.updateByExampleSelective(sysUser,example);
    }


    @Override
    public List userHasPower(Long userId) throws SmsException {
        //查询角色用户表
        Example roleUserExample = new Example(SysRoleUser.class);
        Example.Criteria criteria = roleUserExample.createCriteria();
        criteria.andEqualTo("userId",userId);
        List<SysRoleUser> keyList = ssmSysRoleUserService.selectByExample(roleUserExample);
        //将角色ID提取出来
        List<Long> roleIdList = new ArrayList<>(keyList.size());
        for (SysRoleUser sysRoleUser : keyList) {
            roleIdList.add(sysRoleUser.getRoleId());
        }
        //查询角色表
        Example roleExample = new Example(SysRole.class);
        Example.Criteria roleCriteria = roleExample.createCriteria();
        roleCriteria.andIn("roleId",roleIdList);
        List<SysRole> roles =  ssmSysRoleService.selectByExample(roleExample);
        if (null == roles && roles.size() == 0){
            throw new SmsException(ResponseCode.DATA_DOES_NOT_EXISTS_S,"用户角色不存在");
        }
        //将角色ID提取出来
        List<Long> roleIds = new ArrayList<>(roles.size());
        for (SysRole role : roles) {
            roleIds.add(role.getRoleId());
        }
        //查询角色权限表
        Example rolePowerExample = new Example(SysRolePower.class);
        rolePowerExample.createCriteria().andIn("roleId",roleIds);
        List<SysRolePower> rolePowerList = ssmSysRolePowerService.selectByExample(rolePowerExample);
        if (null == rolePowerList && rolePowerList.size() == 0){
            throw new SmsException(ResponseCode.NO_PERMISSIONS);
        }
        //将权限ID提取出来
        List<Integer> powerIds = new ArrayList<>(rolePowerList.size());
        for (SysRolePower sysRolePower : rolePowerList){
            powerIds.add(sysRolePower.getPowerId());
        }
        //查询权限表
        Example powerExample = new Example(SysMenuPower.class);
        powerExample.createCriteria().andIn("id",powerIds);
        List<SysMenuPower> list = ssmSysMenuPowerService.selectByExample(powerExample);
//        return getList(list);
        return list;
    }

//    //对菜单权限返回格式进行修改
//    public List getList(List<SysRolePower> list){
//        List resultList = new ArrayList();
//        MenuPowerRequest menuPowerRequest = null;
//        List<PowerRequest> checkList = null;
//        Map<String,MenuPowerRequest> tempMap = new HashMap();
//        for (SysRolePower sysRolePower : list){
//            if (tempMap.get(sysRolePower.getMenuId()) == null) {
//                menuPowerRequest = new MenuPowerRequest();
//                checkList = new ArrayList<>();
//                menuPowerRequest.setMenuId(sysRolePower.getMenuId());
//                menuPowerRequest.setMenuName(sysRolePower.getMenuName());
//                PowerRequest powerRequest = new PowerRequest();
//                powerRequest.setPowerId(sysRolePower.getPowerId());
//                powerRequest.setPowerName(sysRolePower.getPowerName());
//                powerRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
//                checkList.add(powerRequest);
//                menuPowerRequest.setCheckList(checkList);
//            }else {
//                //后面进来 直接使用tempMap中的实体  tempMap中的powerList
//                menuPowerRequest =  tempMap.get(sysRolePower.getMenuId());
//                checkList = menuPowerRequest.getCheckList();
//                PowerRequest powerRequest = new PowerRequest();
//                powerRequest.setPowerId(sysRolePower.getPowerId());
//                powerRequest.setPowerName(sysRolePower.getPowerName());
//                //手动塞一个ID 前台渲染需要
//                powerRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
//                checkList.add(powerRequest);
//                menuPowerRequest.setCheckList(checkList);
//            }
//            tempMap.put(sysRolePower.getMenuId(), menuPowerRequest);
////            SysPower sysPower = new SysPower();
////            sysPower.setPowerId(sysMenuPower.getPowerId());
////            sysPower.setPowerName(sysMenuPower.getPowerName());
////            checkList.add(sysPower);
//        }
//        for (Map.Entry<String, MenuPowerRequest> stringMenuPowerRequestEntry : tempMap.entrySet()) {
//            MenuPowerRequest menuPowerRequest1 = stringMenuPowerRequestEntry.getValue();
//            resultList.add(menuPowerRequest1);
//        }
//        return resultList;
//    }

    //判断用户手机号码和账号
    private void getUser(String mobilePhone, String userNum) throws SmsException {
        SysUser sysUser = new SysUser();
        sysUser.setState(1);
        if (mobilePhone != null) {
            sysUser.setMobilePhone(mobilePhone);
            sysUser = selectOne(sysUser);
            if (sysUser != null){
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"手机号码");
            }
        }else if (userNum != null) {
            sysUser.setUserNum(userNum);
            sysUser = selectOne(sysUser);
            if (sysUser != null){
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"账号");
            }
        }
    }

    public String getKey(String userNum){
        String key = "";
        if (StringUtils.isNotBlank(userNum)){
            key = Constant.userKey + userNum;
        }
        return key;
    }
}
