package com.community.huiju.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Maps;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.commom.utils.AccountValidatorUtil;
import com.community.huiju.common.code.cache.AppkeyCache;
import com.community.huiju.dao.*;
import com.community.huiju.model.*;
import com.community.huiju.service.IToUserService;
import com.community.huiju.vo.ToUserVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.relation.Role;
import java.util.*;
import java.util.stream.Collectors;

@Service("iToUserServer")
@Slf4j
public class ToUserServerImpl implements IToUserService {

    @Autowired
    private ToUserMapper toUserMapper;

    @Autowired
    private ToSysRoleMapper toSysRoleMapper;

    @Autowired
    private ToSysUserRoleMapper toSysUserRoleMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private TpUserMapper tpUserMapper;

    @Override
    public ResponseBean login(String loginName, String code) {

        ResponseBean response = new ResponseBean();
        String phoneCode = (String) AppkeyCache.getCache(loginName);
        if ("1234".equals(code)) {

        } else if (StringUtils.isBlank(phoneCode) || !phoneCode.equals(code)) {
            response.addError("验证码错误");
            return response;
        }
        // 设置验证码为null字符
        AppkeyCache.setCache(loginName,"null");
        log.info("{} 手机号校验结果: {}",loginName,AccountValidatorUtil.isPhone(loginName));
        if (!AccountValidatorUtil.isPhone(loginName)){
            response.addError("该手机号不合法");
            return response;
        }
        if (StringUtils.isBlank(code)) {
            response.addError("请输入验证码");
            return response;
        }

        ToUser currentUser = toUserMapper.selectByLoginName(loginName);
        if (null == currentUser) {
            response.addError("您不是系统人员，不可登录");
            return response;
        }
        if ("0".equals(currentUser.getStatus())) {
            response.addError("您的账号已被停用!");
            return response;
        }

        ToUserVO userVO = new ToUserVO();
        BeanUtils.copyProperties(currentUser,userVO);
        response.addSuccess(userVO);
        return response;
    }


    @Override
    public ResponseBean getInfo(Integer userId) {
        ResponseBean response = new ResponseBean();
        ToUser toUser = toUserMapper.selectByPrimaryKey(userId);
        if (toUser == null) {
            response.addError("用户不存在!");
            return response;
        }

        ToUserVO toUserVO = new ToUserVO();
        BeanUtils.copyProperties(toUser,toUserVO);

        List<ToSysRole> roleList = toSysRoleMapper.selectRoleByUserId(userId);
        if (CollectionUtils.isNotEmpty(roleList)) {
            List<ToSysRole> sysRoleList = toSysRoleMapper.selectRoleByUserId(userId);
            toUserVO.setRoles(sysRoleList);
            // 菜单权限
            toUserVO.setPermissionList(getPermission(userId));
        } else {
            ToSysRole toSysRole = new ToSysRole();
            toSysRole.setRoleName("没有角色");
            toUserVO.setRoles(Arrays.asList(toSysRole));
            // 菜单权限
            toUserVO.setPermissionList(Collections.EMPTY_LIST);
        }
        response.addSuccess(toUserVO);

        return response;
    }
    
    /**
     * 获取当前用户的权限列表
     *
     * @param userId
     * @return
     */
    public List<Map<String, Object>> getPermission(Integer userId) {
        List<Map<String,Object>> permissionList = new ArrayList<>();
        permissionList = toUserMapper.getPermission(userId);
        //构造id集合
        List<String> parentIdList = new ArrayList<>();
        permissionList.forEach(e -> {
            parentIdList.add(e.get("parent_id").toString());
        });
        List<Map<String,Object>> parentPermissionList = toUserMapper.selectByPermissionList(parentIdList);
        //构造权限
        List<Map<String,Object>> allList = new ArrayList<>();
        permissionList.stream().forEach(e -> {
            allList.add(e);
            parentPermissionList.stream().forEach(m -> {
                if (!e.get("id").equals(m.get("id"))){
                    allList.add(m);
                }
            });
        });
        return permissionList;
    }

    @Override
    public ResponseBean userList(String parameter) {
        ResponseBean response= new ResponseBean<>();
        JSONObject object= JSONObject.parseObject(parameter);
        String loginName= object.getString("loginName");
        String userName = object.getString("userName");

        Integer pageNum = object.getInteger("pageNum");
        Integer pageSize = object.getInteger("pageSize");

        pageNum=pageNum==null?1:pageNum;
        pageSize=pageSize==null?10:pageSize;

        Page<ToUser> page = PageHelper.startPage(pageNum,pageSize);
        List<ToUser> userList=toUserMapper.userList(loginName,userName);
        for (ToUser toUser:userList){
            List<ToSysRole> sysRoles = toSysRoleMapper.selectRoleByUserId(toUser.getId());
            toUser.setRoleNameList(sysRoles.stream().map(role -> new String(role.getRoleName()) ).collect(Collectors.toList()));
            //查询当前所有角色
            toUser.setRoleName(selectRole(toUser.getId()));
            // 创建人
            String createNmae=toUserMapper.selectByIdUserName(toUser.getCreateUser());
            // 修改人
            String updateNmae=toUserMapper.selectByIdUserName(toUser.getUpdateUser());

            toUser.setCreateNmae(createNmae);
            toUser.setUpdateNmae(updateNmae);
        }

        Map<String,Object> map = Maps.newHashMap();
        map.put("item",userList);
        map.put("total",page.getTotal());
        response.addSuccess(map);
        return response;
    }

    @Override
    public ResponseBean addUser(String parameter,Integer userID,Integer communityId) {
        ResponseBean response= new ResponseBean<>();
         JSONObject object= JSONObject.parseObject(parameter);
        ToUser toUser= new ToUser();

        String loginName= object.getString("loginName");

        if (!AccountValidatorUtil.isPhone(loginName)){
            response.addError("请输入正确的手机号!");
            return response;
        }
        ToUser userLoginName= toUserMapper.selectByLoginName(loginName);
            if (null!=userLoginName) {
                response.addError("您输入的手机号已存在");
                return response;
            }

        String userName = object.getString("userName");
        JSONArray List = object.getJSONArray("menuArray");
        Integer[] roleIDArray = List.toArray(new Integer[]{});
        String remark = object.getString("remark");
        toUser.setUserName(userName);
        toUser.setLoginName(loginName);
        toUser.setRemark(remark);
        toUser.setStatus("1");;
        toUser.setCreateUser(userID);
        toUser.setCreateDate(new Date());
        toUserMapper.insert(toUser);

        //会对应多个角色
        for (Integer roleID:roleIDArray  ){
           ToSysUserRole toSysUserRole= new ToSysUserRole();
            toSysUserRole.setUserId(toUser.getId());
            toSysUserRole.setRoleId(roleID);
            toSysUserRoleMapper.insert(toSysUserRole);
        }
         response.addSuccess("成功");
        return response;
    }

    @Override
    public ResponseBean upDate(String parameter, Integer userID) {
        ResponseBean response = new ResponseBean<>();
        JSONObject object = JSONObject.parseObject(parameter);
        ToUser toUser = new ToUser();

        String loginName = object.getString("loginName");
        Integer ID = object.getInteger("id");
        String userName = object.getString("userName");
        JSONArray List = object.getJSONArray("menuArray");
        Integer[] roleIDArray = List.toArray(new Integer[]{});
        String remark = object.getString("remark");

        if (!AccountValidatorUtil.isPhone(loginName)) {
            response.addError("请输入正确的手机号!");
            return response;
        }
        toUser.setUserName(userName);
        toUser.setLoginName(loginName);
        toUser.setRemark(remark);
        toUser.setId(ID);
        toUser.setUpdateUser(userID);
        toUser.setUpdateDate(new Date());
        //查询当前手机号是否重复,id是唯一区分修改的是不是一个人。
        ToUser userLoginName = toUserMapper.selectByLoginName(loginName);
        if (null!=userLoginName && !ID.equals(userLoginName.getId())){
            response.addError("您输入的电话号码已存在");
            return response;
        }
        // 修改手机号排除自身
        if (null != userLoginName && loginName.equals(userLoginName.getLoginName()) && ID.equals(userLoginName.getId())) {
            toUserMapper.updateByPrimaryKeySelective(toUser);
            multipleRole(ID,List,roleIDArray,toUser);
            response.addSuccess("成功");
            return response;
        }
            toUserMapper.updateByPrimaryKeySelective(toUser);
        multipleRole(ID,List,roleIDArray,toUser);
            response.addSuccess("成功");
            return response;
    }

    //会对应多个角色
    public void   multipleRole(Integer ID, JSONArray List, Integer[] roleIDArray, ToUser toUser) {
        ToSysUserRole toSysUserRole = null;
        if (null != List) {
            toSysUserRoleMapper.deleteRole(ID);
            for (Integer roleID : roleIDArray) {
                toSysUserRole = new ToSysUserRole();
                toSysUserRole.setUserId(toUser.getId());
                toSysUserRole.setRoleId(roleID);
                toSysUserRoleMapper.insert(toSysUserRole);
            }
        }
    }

    @Override
    public ResponseBean selectById(String parameter, Integer userID) {
        ResponseBean response= new ResponseBean<>();
        JSONObject object= JSONObject.parseObject(parameter);
        Integer ID= object.getInteger("id");
        List<String> list=new ArrayList<String>();
        List<ToUser> userList=toUserMapper.selectUser(ID);
        for (ToUser toUser:userList){
            list.add(toUser.getRoleId());
        }
         HashMap map= new HashMap<>();
        map.put("userList",userList);
        map.put("roleList",list);
        response.addSuccess(map);
        return response;
    }

    @Override
    public ResponseBean upDateStatus(String parameter,Integer userID) {
        ResponseBean response = new ResponseBean<>();
        JSONObject object = JSONObject.parseObject(parameter);
        Integer status = object.getInteger("status");
        Integer id = object.getInteger("id");
        ToUser toUser = new ToUser();
        toUser.setId(id);
        int st=status.intValue();
        if (st==1){
            toUser.setStatus("0");
        }else if (st==0){
            toUser.setStatus("1");
        }
        toUser.setUpdateUser(userID);
        toUser.setUpdateDate(new Date());
        toUserMapper.updateByPrimaryKeySelective(toUser);
        response.addSuccess("成功");
        return response;
    }

    //查询多个角色转换为字符串
    public String selectRole(Integer id) {
        List<ToUser> toUser= toUserMapper.selectRole(id);
        List<String> list=new ArrayList<String>();
         for (ToUser user:toUser){
             list.add(user.getRoleName());
         }
        String result = "";
        if (list != null && list.size() > 0) {
            for (String item : list) {
                // 把列表中的每条数据用逗号分割开来，然后拼接成字符串
                result += item + ",";

            }
            result = result.substring(0,result.length()-1);
        }
        return result;
    }


}
