/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.sys.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.Channel;
import com.yami.shop.bean.model.DeptUser;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.DeptService;
import com.yami.shop.service.DeptUserService;
import com.yami.shop.sys.dao.SysUserChannelMapper;
import com.yami.shop.sys.dao.SysUserMapper;
import com.yami.shop.sys.dao.SysUserRoleMapper;
import com.yami.shop.bean.model.SysUser;
import com.yami.shop.sys.service.SysUserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


/**
 * 系统用户
 *
 * @author lgh
 */
@Service("sysUserService")
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserChannelMapper sysUserChannelMapper;

    private SysUserMapper sysUserMapper;
    @Autowired
    private DeptService deptService; // 注入部门服务
    private DeptUserService deptUserService; // 注入部门服务

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserAndUserRole(SysUser user) {
        user.setCreateTime(new Date());
        sysUserMapper.insert(user);
        if (CollUtil.isEmpty(user.getRoleIdList())) {
            return;
        }
        //保存用户与角色关系
        sysUserRoleMapper.insertUserAndUserRole(user.getUserId(), user.getRoleIdList());

        //保存用户与企业关系
        sysUserChannelMapper.insertUserAndUserChannel(user.getUserId(), user.getChannelIdList());
        saveUserDepartments(user);
    }

    private void saveUserDepartments(SysUser user) {
        //保存用户对应的部门信息
        if (CollUtil.isEmpty(user.getDeptIds())) {
            return;
        }
        Date now = new Date();
        for (Long deptId : user.getDeptIds()) {
            DeptUser deptUser = new DeptUser();
            deptUser.setDeptId(deptId);
            deptUser.setUserId(user.getUserId());
            deptUser.setCreateTime(now);
            deptUser.setUpdateTime(now);
            deptUserService.save(deptUser);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserAndUserRole(SysUser user) {
        // 更新用户
        sysUserMapper.updateById(user);

        //先删除用户与角色关系
        sysUserRoleMapper.deleteByUserId(user.getUserId());

        //删除用户与企业关系表
        sysUserChannelMapper.deleteByUserId(user.getUserId());
        if (CollUtil.isEmpty(user.getRoleIdList())&& CollUtil.isEmpty(user.getChannelIdList())) {
            return;
        }
        if (!CollUtil.isEmpty(user.getRoleIdList())){
            //保存用户与角色关系
            sysUserRoleMapper.insertUserAndUserRole(user.getUserId(), user.getRoleIdList());
        }
        if (!CollUtil.isEmpty(user.getChannelIdList())){
            //保存用户与企业关系
            sysUserChannelMapper.insertUserAndUserChannel(user.getUserId(), user.getChannelIdList());
        }

        // 更新用户部门信息
        updateUserDepartments(user);
    }

    /**
     * 更新用户部门关联信息
     * @param user 用户信息
     */
    private void updateUserDepartments(SysUser user) {
        // 先删除用户原有的部门关联
        deptUserService.remove(new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<DeptUser>()
                .eq(DeptUser::getUserId, user.getUserId()));

        // 如果没有新的部门分配，直接返回
        if (CollUtil.isEmpty(user.getDeptIds())) {
            return;
        }

        // 保存新的部门关联
        Date now = new Date();
        for (Long deptId : user.getDeptIds()) {
            DeptUser deptUser = new DeptUser();
            deptUser.setDeptId(deptId);
            deptUser.setUserId(user.getUserId());
            deptUser.setCreateTime(now);
            deptUser.setUpdateTime(now);
            deptUserService.save(deptUser);
        }
    }
    @Override
    public void updatePasswordByUserId(Long userId, String newPassword) {
        SysUser user = new SysUser();
        user.setPassword(newPassword);
        user.setUserId(userId);
        sysUserMapper.updateById(user);
    }

    @Override
    public SysUser getByUserName(String username) {
        return sysUserMapper.selectByUsername(username);
    }

    @Override
    public SysUser getSysUserById(Long userId) {
        SysUser user = sysUserMapper.selectById(userId);
        //获取用户所属部门
        if (user != null) {
            // 通过关联表查询用户对应的部门信息
            user.setDepts(deptService.listDeptsByUserId(userId));
        }
        //获取用户所属企业
        if (user != null) {
            // 通过关联表查询用户对应的部门信息
            user.setChannelIdList(sysUserChannelMapper.listChannelByUserId(userId));
        }
        return user;
    }

    @Override
    public IPage<SysUser> selectPage(String username, PageParam<SysUser> page) {

        IPage<SysUser> sysUserPage = page(page, new LambdaQueryWrapper<SysUser>()
                .like(StrUtil.isNotBlank(username), SysUser::getUsername, username));

        sysUserPage.getRecords().forEach(user -> {
            //获取用户所属部门
            user.setDepts(deptService.listDeptsByUserId(user.getUserId()));
        });
        return sysUserPage;

    }

    @Override
    public List<Channel> findByUserId(Long userId) {
        return sysUserMapper.findByUserId(userId);
    }

    @Override
    public List<Long> findByUserIdListId(Long userId) {
        return sysUserChannelMapper.listChannelByUserId(userId);
    }
}
