package org.nl.system.service.user.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import org.apache.commons.beanutils.ConvertUtils;
import org.nl.common.domain.query.PageQuery;
import org.nl.config.FileProperties;
import org.nl.common.utils.FileUtil;
import org.nl.common.utils.SecurityUtils;
import org.nl.config.IdUtil;
import org.nl.system.service.dept.ISysDeptService;
import org.nl.system.service.role.ISysRoleService;
import org.nl.system.service.user.ISysUserService;
import org.nl.system.service.user.dao.SysUser;
import org.nl.system.service.user.dao.mapper.SysUserMapper;
import org.nl.system.service.user.dto.SysUserDetail;
import org.nl.system.service.user.dto.UserDataPermissionDto;
import org.nl.system.service.user.dto.UserQuery;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author generator
 * @since 2022-12-15
 */
@Service
public class ISysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private FileProperties properties;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysRoleService roleService;

    @Override
    public Map<String, String> updateAvatar(MultipartFile multipartFile) {
        SysUser user = this.getOne(new QueryWrapper<SysUser>().eq("username", SecurityUtils.getCurrentUsername()));
        String oldPath = user.getAvatar_path();
        File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar());
        user.setAvatar_path(Objects.requireNonNull(file).getPath());
        user.setAvatar_name(file.getName());
        this.saveOrUpdate(user);
        if (StrUtil.isNotEmpty(oldPath)) {
            FileUtil.del(oldPath);
        }
        return new HashMap<String, String>(1) {{
            put("avatar", file.getName());
        }};
    }

    @Override
    public List<SysUserDetail> getUserDetail(UserQuery query, PageQuery pageQuery) {
        List<SysUserDetail> userDetail = sysUserMapper.getUserDetail(query, pageQuery);
        return userDetail;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @SneakyThrows
    public void create(Map userDetail) {
        SysUser sysUser = new SysUser();
        BeanUtils.populate(sysUser,userDetail);
        // 默认密码 123456
        if (ObjectUtil.isEmpty(sysUser.getPassword())) {
            sysUser.setPassword(SaSecureUtil.md5BySalt("123456", "salt"));
        } else {
            sysUser.setPassword(SaSecureUtil.md5BySalt(sysUser.getPassword(), "salt"));
        }
        String userId = IdUtil.getStringId();
        sysUser.setUser_id(userId);
        this.save(sysUser);
        if (userDetail.get("depts") !=null){
            deptService.saveUserDeptRelation(userId,(List)userDetail.get("depts"));
        };
        if (userDetail.get("roles") !=null){
            roleService.saveUserRoleRelation(userId,(List)userDetail.get("roles"));
        };
    }

    @Override
    @Transactional
    public void update(Map userDetail) {
        if(CollectionUtils.isEmpty(userDetail) || ObjectUtil.isEmpty(userDetail.get("user_id"))){
            return;
        }

        SysUser sysUser = new SysUser();
        org.springframework.beans.BeanUtils.copyProperties(userDetail,sysUser);
        //转换器
        ConvertUtils.register((aClass, o) -> {
            try {
                if (o == null){ return null; }
                return new SimpleDateFormat("yyyy-MM-dd").parse(o.toString());
            }catch (Exception ex){
                return null;
            }
        }, Date.class);
        try {
            BeanUtils.populate(sysUser,userDetail);
        }catch (Exception ex){
            throw new RuntimeException();
        }
        sysUser.setUpdate_time(new Date());
        sysUser.setUpdate_id(SecurityUtils.getCurrentUserId());
        this.updateById(sysUser);
        if (userDetail.get("deptIds")!=null){
            deptService.delUserDeptRelation(sysUser.getUser_id());
            deptService.saveUserDeptRelation(sysUser.getUser_id(), (List) userDetail.get("deptIds"));
        };
        if (userDetail.get("rolesIds") !=null){
            roleService.delUserRoleRelation(sysUser.getUser_id());
           roleService.saveUserRoleRelation(sysUser.getUser_id(),(List) userDetail.get("rolesIds"));
        }
    }

    @Override
    public List<UserDataPermissionDto> getUserDataPermissionByPermissionId(String permissionId) {
        return sysUserMapper.getUserDataPermissionByPermissionId(permissionId);
    }

    @Override
    public List<UserDataPermissionDto> getUserDataPermissionByUserId(String userId) {
        return sysUserMapper.getUserDataPermissionByUserId(userId);
    }

    @Override
    public void deleteDataPermissionById(String userId) {
        sysUserMapper.deleteDataPermissionById(userId);
    }

    @Override
    public void insertDataPermission(UserDataPermissionDto userDataPermissionDto) {
        sysUserMapper.insertDataPermission(userDataPermissionDto);
    }

    @Override
    public List<String> getUserIdByDeptId(String deptId) {
        return sysUserMapper.getUserIdByDeptId(deptId);
    }
}
