/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.base.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.base.api.entity.User;
import com.tofly.base.entity.Menu;
import com.tofly.base.entity.System;
import com.tofly.base.entity.UserRole;
import com.tofly.base.mapper.UserMapper;
import com.tofly.base.service.*;
import com.tofly.common.core.constant.CommonConstants;
import com.tofly.common.core.util.PasswordUtil;
import com.tofly.common.core.util.SpringContextHolder;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.core.util.io.ExcelUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.feign.FlowableDeleteUserEvent;
import com.tofly.common.oauth.util.SecurityUtils;
import lombok.SneakyThrows;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户表
 *
 * @author admin
 * @date Thu Oct 10 00:00:00 CST 2019
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private SystemService systemService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private SourceService sourceService;
    @Autowired
    private UserRoleService userRoleService;

    @Override
    public User getUserById(Long id) {
        return baseMapper.getUserById(id);
    }

    @Override
    public List<User> getExistUserListByRole(Long roleId) {
        return baseMapper.getExistUserListByRole(roleId);
    }

    @Override
    public List<User> getNoExistUserListByRole(Long roleId) {
        return baseMapper.getNoExistUserListByRole(roleId);
    }

    @Override
    public List<System> getSystemListByUser(String platform) {
        return systemService.getSystemListByUser(platform);
    }

    @Override
    public List<Menu> getMenuListByUser(String platform) {
        return menuService.getMenuListByUser(platform);
    }

    @Override
    public List<Map> getSourceByUser() {
        return sourceService.getSourceByUser();
    }

    @Override
    public List<Map> getSources(Long departmentId) {
        return baseMapper.getSources(departmentId);
    }

    @Override
    @Transactional
    @SneakyThrows
    public boolean deleteUserByIds(String ids) {
        String[] idss=ids.split(",");
        List<Long> list=new ArrayList();
        boolean flag=true;
        StringBuffer sb=new StringBuffer();

        List<Long> userRole=new ArrayList<>();

        List<User> userList=new ArrayList();
        for(String id:idss){
            list.add(Long.valueOf(id));
            if(checkHandler(Long.valueOf(id))){
                throw new Exception("当前用户不能删除其他人创建的用户");
            }
//            if(checkHandler(Long.valueOf(id))){
//                return new Exception("当前用户不能删除其他人创建的用户");
//            }

            List<UserRole> roleMneuList=userRoleService.list(Wrappers.<UserRole>lambdaQuery()
                    .eq(UserRole::getUserId,Long.valueOf(id)));
            if(roleMneuList.size()>0){
                userRole.addAll(roleMneuList.stream().map(UserRole::getId).collect(Collectors.toList()));

            }

            userList.add(this.getById(Long.valueOf(id)));
        }

        if(userRole.size()>0){
            userRoleService.removeByIds(userRole);
        }
        this.removeByIds(list);

        //flowable中推送
        userList.forEach(u->{
            SpringContextHolder.publishEvent(new FlowableDeleteUserEvent(u));
        });
        return true;
    }


//    private boolean checkHandler(String ulevel){
//        if(StringUtil.isEmpty(ulevel)){
//            return false;
//        }
//        String userlevel= SecurityUtils.getUser().getUserLevel();
//        if(Integer.parseInt(userlevel)>=Integer.parseInt(ulevel)){
//            return true;
//        }
//        return false;
//    }
        private boolean checkHandler(Long userid){

            if(CommonConstants.SUPER_ADMIN_ULEVEL.equals(SecurityUtils.getUser().getUserLevel())){
                return false;
            }
            User user=this.getById(userid);

            if(SecurityUtils.getUserId().equals(user.getCreateUser())){
                return false;
            }else {
                if(CommonConstants.SUPER_ADMIN_ULEVEL.equals(user.getUserLevel())){
                    return true;
                }else {
                    return checkHandler(user.getCreateUser());
                }
            }
        }

    @Override
    public Page<Map> getUserPage(Page page,User user){ return  page.setRecords(baseMapper.getUserPage(page,user));}

    @Override
    @SneakyThrows
    @Transactional
    public String uploadBatchUser(MultipartFile file) {
        if(file==null){
            throw new ToflyDeniedException("上传文件为空");
        }
        InputStream inputStream = file.getInputStream();
        ExcelUtil userExcel=new ExcelUtil(User.class);
        List<User> listUser= userExcel.importExcel(inputStream);
        List<User> listAllUser=this.list();
        Map<String, User> collect = listAllUser.stream().collect(Collectors.toMap(User::getUsername, m ->m));
        StringBuffer sb=new StringBuffer();
        List<String> collect1 = listUser.stream().filter(k -> collect.get(k.getUsername()) != null)
                .map(User::getUsername).collect(Collectors.toList());
        if(collect1.size()>0){
            throw new ToflyDeniedException("数据库已经存在用户名，不能导入"+ JSONArray.toJSONString(collect1));
        }
        collect1 = listUser.stream().filter(k -> StringUtil.isEmpty(k.getUsername()) || StringUtil.isEmpty(k.getPassword()))
                .map(User::getUsername).collect(Collectors.toList());
        if(collect1.size()>0){
            throw new ToflyDeniedException("用户名或密码存在为空的数据，不能导入"+ JSONArray.toJSONString(collect1));
        }

        listUser.stream().forEach(user -> {
            user.setPassword(PasswordUtil.passwordEncode(DigestUtils.sha1Hex(user.getPassword())));
            this.save(user);
        });

        return "成功导入"+listUser.size()+"条数据";
    }

    @Override
    public List<Map> getUserByMenu(String menuName) {
        return baseMapper.getUserByMenu(menuName);
    }

}
