package com.usoftchina.bi.server.service.user;

import com.usoftchina.bi.core.base.BaseContextHolder;
import com.usoftchina.bi.core.base.RepCode;
import com.usoftchina.bi.core.base.RepEntity;
import com.usoftchina.bi.core.exception.MyException;
import com.usoftchina.bi.core.jdbc.DynamicDataSourceContextHolder;
import com.usoftchina.bi.core.utils.EncryUtil;
import com.usoftchina.bi.server.aspect.JwtTokenAspect;
import com.usoftchina.bi.server.dao.user.UserMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.usoftchina.bi.server.model.po.MessageLog;
import com.usoftchina.bi.server.model.po.TokenData;
import com.usoftchina.bi.server.model.po.User;
import com.usoftchina.bi.server.model.po.UserGroup;
import com.usoftchina.bi.server.model.vo.configVo.LoginInfo;
import com.usoftchina.bi.server.model.vo.configVo.UserGroupInfo;
import com.usoftchina.bi.server.model.vo.configVo.UserGroupSetInfo;
import com.usoftchina.bi.server.service.common.MessageLogService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {
    @Autowired
    private JwtTokenAspect jwtTokenUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MessageLogService messageLogService;

    /**
     * 登录接口,涉及UAS用户同步：
     *      1.登陆时,若此时BI_USERS表中没有数据,则将UASE中EMPLOYEE表数据同步至BI_USERS
     *      2.登陆时,在EMPLOYEE表中查询此人的人员在职状态(EM_CLASS)。若离职,则不允许登录,同时更新BI中BI_USERS对应人员的在职状态
     *      3.通过定时任务的方式每晚比对EMPLOYEE和BI_USERS,进行insert和update操作。
     * @param loginInfo
     * @return
     */
    public RepEntity<TokenData> login(LoginInfo loginInfo){
        String userName = loginInfo.getUserName(), pws = loginInfo.getPassWord();
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(pws)){
            return new RepEntity(RepCode.NoUser);
        }
        //1.从UAS中将人员资料同步过来
        copyUserFromUAS();
        //2.校验用户名密码在BI中是否存在
        User user = userMapper.getBIUserByName(userName);
        if (null == user) {
            user = userMapper.getBIUserByMobile(userName);
        }
        String password = "";
        if (null == user) {
            //3.校验用户名密码在UAS中是否存在
            user = findUserFromUAS(userName, pws);
            if ("离职".equals(user.getState())) {
                throw new MyException(RepCode.NoUser);
            }
            //插入
            userMapper.addUser(user);
        }else {
            String role = user.getRole();
            password = user.getPassWord();

            user = findUserFromUAS(userName, pws);
            if ("离职".equals(user.getState())) {
                //更新离职状态
                userMapper.updateUser(user);
                throw new MyException(RepCode.NoUser);
            }
            user.setRole(role);
            int userId = userMapper.getUserId(user.getUserName());
            user.setId(userId);
            if (!pws.equals(password)){
                //更新密码
                userMapper.updateUser(user);
            }else {
                if ("离职".equals(user.getState())) {
                    //更新离职状态
                    userMapper.updateUser(user);
                    throw new MyException(RepCode.NoUser);
                }
            }
        }
        TokenData tokenData = jwtTokenUtil.createToke(user);
        tokenData.setUser(user);
        return new RepEntity(RepCode.success, tokenData);
    }

    /**
     * 从UAS复制人员资料
     */
    private void copyUserFromUAS(){
        int count = userMapper.getCount();
        if (count == 0) {
            DynamicDataSourceContextHolder.setDataSourceType(userMapper.getMasterId());
            List<User> userList = userMapper.getUASEmployee();
            DynamicDataSourceContextHolder.clearDataSourceType();
            userMapper.batchInsert(userList);
        }
    }

    /**
     * 在UAS中查找用户
     * @param userName
     * @param pws
     * @return
     */
    private User findUserFromUAS(String userName, String pws){
        DynamicDataSourceContextHolder.setDataSourceType(userMapper.getMasterId());
        User user = userMapper.getUserMessByName(userName);
        if (null == user) {
            user = userMapper.getUserMessByMobile(userName);
        }
        DynamicDataSourceContextHolder.clearDataSourceType();
        if (null == user) {
            throw new MyException(RepCode.NoUser);
        }
        String password = user.getPassWord();
        String pw = EncryUtil.decryptPassword(password);
        if (!EncryUtil.decryptPassword(pws).equals(pw)){
            throw new MyException(RepCode.NoUser);
        }
        return user;
    }

    /*
    更新用户信息
     */
    public RepEntity updateUser(User user){
        userMapper.updateUser(user);
        return new RepEntity(RepCode.success);
    }

    /*
    查询用户列表
     */
    @Cacheable(value = "userList")
    public RepEntity getUserList(){
        List<User> userList = userMapper.getUserList();
        return new RepEntity(RepCode.success, userList);
    }

    public RepEntity<User> getUserById(int id){
        return new RepEntity<User>(RepCode.success, userMapper.getUserById(id));
    }

    /*
    查询匹配用户
     */
    public RepEntity getNameList(String condition, Long count){
        String value = "like '%" + condition + "%'";
        List<User> userName = userMapper.getNameList(value, count);
        return new RepEntity(RepCode.success, userName);
    }


    /*
    创建用户组
     */
    public RepEntity createUserGroup(UserGroupInfo userGroupInfo){
        int count = userMapper.getGroupCountByGroupName(userGroupInfo.getUserGroupName());
        if (count > 0) {
            throw new MyException(RepCode.USER_GROUP_EXISTS);
        }
        UserGroup userGroup = new UserGroup();
        BeanUtils.copyProperties(userGroupInfo,userGroup);
        if (userGroup.getUserGroupNote() == null){
            userGroup.setUserGroupNote("");
        }
        userMapper.insUserGroup(userGroup);
        return new RepEntity(RepCode.success, userGroup.getId());
    }

    /*
    更新用户组
     */
    public  RepEntity updateUserGroup(UserGroupInfo userGroupInfo){
        UserGroup userGroup = new UserGroup();
        BeanUtils.copyProperties(userGroupInfo,userGroup);
        userMapper.updateUserGroup(userGroup);
        return new RepEntity(RepCode.success);
    }

    /*
    查询用户组
     */
    public RepEntity getUserGroup(){
        List<UserGroup> userGroup= userMapper.getUserGroupList();
        return new RepEntity(RepCode.success, userGroup);
    }

    /*
    删除用户组
     */
    public RepEntity delUserGroup(Long id){
        UserGroup userGroup = userMapper.getUserGroup(id.intValue());
        userMapper.delUserGroup(id);
        //删除用户组相关的权限
        userMapper.deletePowerByGroupId(id);
        messageLogService.delete("用户管理", userGroup.getUserGroupName(), BaseContextHolder.getUserName(), "删除用户组");
        return new RepEntity(RepCode.success);
    }

    /*
    添加用户到用户组
     */
    public RepEntity setUserInto(UserGroupSetInfo userGroupSetInfo){
        String username = BaseContextHolder.getUserName();
        int userGroupId = userGroupSetInfo.getUserGroupId();
        String groupName = userMapper.getUserGroup(userGroupId).getUserGroupName();
        List<Integer> userList = userGroupSetInfo.getUserList();
        Iterator isList = userList.iterator();
        while (isList.hasNext()){
            int userId = (int) isList.next();
            int count = userMapper.getUserCountInGroup(userId, userGroupId);
            if (count > 0){
                return new RepEntity(RepCode.UserIn);
            }else {
                userMapper.setUserInto(userId, userGroupId);
            }
        }
        //记录LOG
        userGroupLog(userList, username, groupName, "add");
        return new RepEntity(RepCode.success);
    }

    /*
    查询用户组下的用户信息
     */
    public RepEntity getUserInGroup(int id){
        List<User> user = userMapper.getGroupUserList(id);
        return new RepEntity(RepCode.success, user);
    }

    /*
    删除用户组下的用户
     */
    public RepEntity delUserInGroup(UserGroupSetInfo userGroupSetInfo){
        List<Integer> list = userGroupSetInfo.getUserList();
        int userGroupId = userGroupSetInfo.getUserGroupId();
        String username = BaseContextHolder.getUserName();
        String groupName = userMapper.getUserGroup(userGroupId).getUserGroupName();
        Iterator isList = list.iterator();
        while (isList.hasNext()){
            int userId = (int) isList.next();
            userMapper.delUserInGroup(userId, userGroupId);
        }
        //记录LOG
        userGroupLog(list, username, groupName, "delete");
        return new RepEntity(RepCode.success);
    }

    private void userGroupLog(List<Integer> userList, String username, String groupName, String type){
        //记录LOG
        String userIds = userList.stream().map(Object::toString).collect(Collectors.joining(","));
        String userNames = userMapper.getUserByIds(userIds);
        String[] userNameArray = userNames.split(",");
        StringBuilder sb = new StringBuilder();
        MessageLog messageLog = new MessageLog();
        String content = "", result = "";
        if (userNameArray.length > 10) {
            for (int i = 0, len = userNameArray.length; i < len; i = i+10) {
                for (int j = 0; j < 10; j++) {
                    sb.append(userNameArray[i+j] + ",");
                }
                String names = sb.substring(0, sb.length() - 1);
                if ("add".equals(type)) {
                    content = "添加用户：" + names + " 到用户组" + groupName + "中";
                    result = "添加成功";
                }else if ("delete".equals(type)){
                    content = "从用户组" + groupName + "删除用户：" + names;
                    result = "删除成功";
                }
                messageLog = new MessageLog(username, content,result, null, "用户管理", null);
                messageLogService.customizeLog(messageLog);
                sb.delete(0, sb.length());
            }

        }else {
            for (int i = 0, len = userNameArray.length; i < len; i++) {
                sb.append(userNameArray[i] + ",");
            }
            String names = sb.substring(0, sb.length() - 1);
            if ("add".equals(type)) {
                content = "添加用户：" + names + " 到用户组" + groupName + "中";
                result = "添加成功";
            }else if ("delete".equals(type)){
                content = "从用户组" + groupName + "删除用户：" + names;
                result = "删除成功";
            }
            messageLog = new MessageLog(username, content,result, null, "用户管理", null);
            messageLogService.customizeLog(messageLog);
        }
    }
}
