package com.tuoheng.system.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tuoheng.common.config.CommonConfig;
import com.tuoheng.common.exception.ServiceException;
import com.tuoheng.system.constant.UserConstant;
import com.tuoheng.system.dto.ResetPwdDto;
import com.tuoheng.system.dto.UpdatePwdDto;
import com.tuoheng.system.dto.UpdateUserInfoDto;
import com.tuoheng.system.entity.*;
import com.tuoheng.system.mapper.*;
import com.tuoheng.system.entity.*;
import com.tuoheng.system.mapper.*;
import com.tuoheng.system.query.CityQuery;
import com.tuoheng.system.query.UserQuery;
import com.tuoheng.system.service.IMenuService;
import com.tuoheng.system.service.IUserRoleService;
import com.tuoheng.system.service.IUserService;
import com.tuoheng.system.utils.ShiroUtils;
import com.tuoheng.system.vo.user.UserInfoVo;
import com.tuoheng.system.vo.user.UserListVo;
import com.tuoheng.common.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 后台用户管理表 服务实现类
 * </p>
 *
 * @author 拓恒
 * @since 2020-10-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private LevelMapper levelMapper;
    @Autowired
    private PositionMapper positionMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private CityMapper cityMapper;

    /**
     * 获取用户列表
     *
     * @param userQuery 查询条件
     * @return
     */
    @Override
    public JsonResult getList(UserQuery userQuery) {
        // 查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 只显示非管理员用户
        queryWrapper.ne("is_admin", 1);
        // 租户ID
        queryWrapper.eq("tenant_id", ShiroUtils.getTenantId());
        // 真实姓名
        if (!StringUtils.isEmpty(userQuery.getRealname())) {
            queryWrapper.like("realname", userQuery.getRealname());
        }
        // 用户账号
        if (!StringUtils.isEmpty(userQuery.getUsername())) {
            queryWrapper.eq("username", userQuery.getUsername());
        }
        // 性别
        if (StringUtils.isNotNull(userQuery.getGender())) {
            queryWrapper.eq("gender", userQuery.getGender());
        }
        queryWrapper.eq("mark", 1);
        //判断是否终端用户 修改查询
        if (StringUtils.isNotNull(userQuery.getTerminalType()) && userQuery.getTerminalType() == 1) {
            queryWrapper.and(wrapper -> wrapper.eq("type", 1)
                    .or().eq("type", 2));
        } else {
            queryWrapper.and(wrapper -> wrapper.eq("type", 3)
                    .or().eq("type", 4).or().eq("type", 5).or().eq("type", 6));
        }
        // 用户类型筛选
        if (StringUtils.isNotNull(userQuery.getType())) {
            queryWrapper.eq("type", userQuery.getType());
        }
        // 状态筛选
        if (StringUtils.isNotNull(userQuery.getStatus())) {
            queryWrapper.eq("status", userQuery.getStatus());
        }
        // 角色ID
        if (StringUtils.isNotNull(userQuery.getRoleId())) {
            List<Integer> integerList = userRoleMapper.getUsersByURoleId(userQuery.getRoleId());
            Integer[] userIds = integerList.toArray(new Integer[integerList.size()]);
            if (userIds.length >= 1) {
                queryWrapper.in("id", userIds);
            } else {
                queryWrapper.in("id", 0);
            }
        }
        //end 判断是否终端用户 修改查询 2021 11 15
        queryWrapper.orderByAsc("sort");
        // 查询分页数据
        IPage<User> page = new Page<>(userQuery.getPage(), userQuery.getLimit());
        IPage<User> pageData = userMapper.selectPage(page, queryWrapper);
        pageData.convert(x -> {
            UserListVo userListVo = Convert.convert(UserListVo.class, x);
            // 用户头像
            if (!StringUtils.isEmpty(x.getAvatar())) {
                userListVo.setAvatar(CommonUtils.getImageURL(x.getAvatar()));
            }
            // 性别描述
            if (x.getGender() != null && x.getGender() > 0) {
                userListVo.setGenderName(UserConstant.USER_GENDER_LIST.get(x.getGender()));
            }
            // 职级
            if (StringUtils.isNotNull(x.getLevelId())) {
                Level levelInfo = levelMapper.selectById(x.getLevelId());
                if (StringUtils.isNotNull(levelInfo)) {
                    userListVo.setLevelName(levelInfo.getName());
                }
            }
            // 岗位
            if (StringUtils.isNotNull(x.getPositionId())) {
                Position positionInfo = positionMapper.selectById(x.getPositionId());
                if (StringUtils.isNotNull(positionInfo)) {
                    userListVo.setPositionName(positionInfo.getName());
                }
            }
            // 部门
            if (StringUtils.isNotNull(x.getDeptId())) {
                Dept dept = deptMapper.selectById(x.getDeptId());
                if (StringUtils.isNotNull(dept)) {
                    userListVo.setDeptName(dept.getName());
                }
            }
            // 城市数据处理
            if (StringUtils.isNotNull(x.getProvinceCode()) &&
                    StringUtils.isNotNull(x.getCityCode()) &&
                    StringUtils.isNotNull(x.getDistrictCode())) {
                // 初始化数组
                String[] strings = new String[3];
                strings[0] = x.getProvinceCode();
                strings[1] = x.getCityCode();
                strings[2] = x.getDistrictCode();
                userListVo.setCity(strings);
            }
            // 获取角色信息
            List<Role> roleList = roleMapper.getRolesByUserId(x.getId());
            userListVo.setRoles(roleList);
            return userListVo;
        });
        return JsonResult.success(pageData);
    }

    /**
     * 用于新增修改终端用户 回显所管辖区域名称
     *
     * @param x type
     * @return
     */
    private String selectCityName(User x) {
        QueryWrapper<City> queryWrapper = new QueryWrapper<>();
        String userCityCode = "";
        if (!StringUtils.isEmpty(x.getStreetCode()) && (x.getType() == 6 || x.getType() == 1 || x.getType() == 2 || x.getType() == 3)) {
            String citys = "";
            String[] s = x.getStreetCode().split(",");
            for (String scode : s) {
                queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("citycode", scode);
                queryWrapper.eq("mark", 1);
                List<City> listStreet = cityMapper.selectList(queryWrapper);
                if (listStreet.size() > 0) {
                    for (City cityone : listStreet) {
                        citys += cityone.getName() + ",";
                    }
                }
            }
            return citys.substring(0, citys.length() - 1);
        } else if (!StringUtils.isEmpty(x.getDistrictCode()) && (x.getType() == 5 || x.getType() == 1 || x.getType() == 2 || x.getType() == 3)) {
            userCityCode = x.getDistrictCode();
        } else if (!StringUtils.isEmpty(x.getCityCode()) && (x.getType() == 4 || x.getType() == 1 || x.getType() == 2 || x.getType() == 3)) {
            userCityCode = x.getCityCode();
        } else if (!StringUtils.isEmpty(x.getProvinceCode())) {
            userCityCode = x.getProvinceCode();
        }
        queryWrapper.eq("citycode", userCityCode);
        List<City> list = cityMapper.selectList(queryWrapper);
        if (list.size() > 0) {
            return list.get(0).getName();
        } else {
            return null;
        }
    }

    /**
     * 获取用户详情
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public JsonResult detail(Integer userId) {
        User info = userMapper.selectById(userId);
        if (info == null) {
            return JsonResult.error("用户不存在");
        }
        if (!info.getTenantId().equals(ShiroUtils.getTenantId())) {
            return JsonResult.error("当前用户非本租户用户");
        }

        // 获取用户详细信息
        UserListVo userInfo = new UserListVo();
        BeanUtils.copyProperties(info, userInfo);
        // 用户头像
        if (!StringUtils.isEmpty(info.getAvatar())) {
            userInfo.setAvatar(CommonUtils.getImageURL(info.getAvatar()));
        }
        // 性别描述
        if (info.getGender() != null && info.getGender() > 0) {
            userInfo.setGenderName(UserConstant.USER_GENDER_LIST.get(info.getGender()));
        }
        // 职级
        if (StringUtils.isNotNull(info.getLevelId())) {
            Level levelInfo = levelMapper.selectById(info.getLevelId());
            if (StringUtils.isNotNull(levelInfo)) {
                userInfo.setLevelName(levelInfo.getName());
            }
        }
        // 岗位
        if (StringUtils.isNotNull(info.getPositionId())) {
            Position positionInfo = positionMapper.selectById(info.getPositionId());
            if (StringUtils.isNotNull(positionInfo)) {
                userInfo.setPositionName(positionInfo.getName());
            }
        }
        // 城市数据处理
        if (StringUtils.isNotNull(info.getProvinceCode()) &&
                StringUtils.isNotNull(info.getCityCode()) &&
                StringUtils.isNotNull(info.getDistrictCode())) {
            // 初始化数组
            String[] strings = new String[3];
            strings[0] = info.getProvinceCode();
            strings[1] = info.getCityCode();
            strings[2] = info.getDistrictCode();
            userInfo.setCity(strings);
        }
        // 获取角色信息
        List<Role> roleList = roleMapper.getRolesByUserId(info.getId());
        userInfo.setRoles(roleList);
        return JsonResult.success(userInfo);
    }

    /**
     * 添加或编辑
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult edit(User entity) {
//        // 头像处理
//        if (StringUtils.isEmpty(entity.getAvatar())) {
//            return JsonResult.error("请上传头像");
//        }
        if (StringUtils.isNull(entity.getId()) || entity.getId().equals(0)) {
            // 添加
            Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>()
                    .eq(User::getUsername, entity.getUsername())
                    .eq(User::getMark, 1));
            if (count > 0) {
                return JsonResult.error("系统中已经存在相同的账号信息");
            }
        } else {
            // 编辑
            Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>()
                    .ne(User::getId, entity.getId())
                    .eq(User::getUsername, entity.getUsername())
                    .eq(User::getMark, 1));
            if (count > 0) {
                return JsonResult.error("系统中已经存在相同的账号信息");
            }
        }

        if (StringUtils.isNotNull(entity.getAvatar()) && entity.getAvatar().contains(CommonConfig.imageURL)) {
            entity.setAvatar(entity.getAvatar().replaceAll(CommonConfig.imageURL, ""));
        }
        // 设置密码
        if (StringUtils.isNotEmpty(entity.getPassword())) {
            entity.setPassword(CommonUtils.password(entity.getPassword()));
        } else {
            entity.setPassword(null);
        }
//        // 省市区处理
//        if (entity.getCity().length != 3) {
//            return JsonResult.error("请选择省市区");
//        }
//        // 省份
//        entity.setProvinceCode(entity.getCity()[0]);
//        // 城市
//        entity.setCityCode(entity.getCity()[1]);
//        // 省份
//        entity.setDistrictCode(entity.getCity()[2]);
        // 租户ID
        entity.setTenantId(ShiroUtils.getTenantId());
        entity.setCityName(selectCityName(entity));
        entity.setCreateUser(ShiroUtils.getUserId());
        entity.setCreateTime(DateUtils.now());
        boolean result = this.saveOrUpdate(entity);
        if (!result) {
            return JsonResult.error();
        }
        // 删除已存在的用户角色关系数据
        userRoleService.deleteUserRole(entity.getId());
        // 插入用户角色关系数据
        userRoleService.insertUserRole(entity.getId(), entity.getRoleIds());
        return JsonResult.success();
    }

    /**
     * 根据用户ID删除用户
     *
     * @param ids 记录ID
     * @return
     */
    @Override
    public JsonResult deleteByIds(Integer[] ids) {
        if (StringUtils.isNull(ids)) {
            return JsonResult.error("记录ID不能为空");
        }
        // 设置Mark=0
        Integer totalNum = 0;
        for (Integer id : ids) {
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.set("mark", 0);
            updateWrapper.eq("id", id);
            // 租户ID
            updateWrapper.eq("tenant_id", ShiroUtils.getTenantId());
            boolean result = update(updateWrapper);
            if (result) {
                totalNum++;
            }
        }
        if (totalNum != ids.length) {
            return JsonResult.error();
        }
        return JsonResult.success("删除成功");
    }

    /**
     * 设置状态
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult setStatus(User entity) {
        entity.setUpdateUser(ShiroUtils.getUserId());
        entity.setUpdateTime(DateUtils.now());
        boolean result = this.updateById(entity);
        if (!result) {
            return JsonResult.error();
        }
        return JsonResult.success();
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @Override
    public JsonResult getUserInfo() {
        Integer userId = ShiroUtils.getUserId();
        User user = userMapper.selectById(userId);
        if (StringUtils.isNull(user)) {
            return JsonResult.error("用户信息不存在");
        }
        if (!user.getTenantId().equals(ShiroUtils.getTenantId())) {
            return JsonResult.error("当前用户非本租户用户");
        }

        // 拷贝属性
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(user, userInfoVo);
        // 会员头像
        if (StringUtils.isNotNull(user.getAvatar())) {
            userInfoVo.setAvatar(CommonUtils.getImageURL(user.getAvatar()));
        }

        // 获取角色列表
        List<Role> roleList = userRoleMapper.getRolesByUserId(userId);
        userInfoVo.setRoles(roleList);

        // 获取权限菜单
        List<Menu> menuList = menuService.getMenuList(userId);
        userInfoVo.setAuthorities(menuList);

        // 获取节点权限
        List<String> permissionList = menuService.getPermissionList(userId);
        userInfoVo.setPermissionList(permissionList);
        return JsonResult.success(userInfoVo);
    }

    /**
     * 修改密码
     *
     * @param updatePwdDto 参数
     * @return
     */
    @Override
    public JsonResult updatePwd(UpdatePwdDto updatePwdDto) {
        User user = userMapper.selectById(ShiroUtils.getUserId());
        if (user == null) {
            return JsonResult.error("用户信息不存在");
        }
        if (!user.getTenantId().equals(ShiroUtils.getTenantId())) {
            return JsonResult.error("当前用户非本租户用户");
        }
        // 校验旧密码是否正确
        if (!CommonUtils.password(updatePwdDto.getOldPassword()).equals(user.getPassword())) {
            return JsonResult.error("原始密码不正确");
        }
        // 设置新密码
        user.setPassword(CommonUtils.password(updatePwdDto.getNewPassword()));
        Integer result = userMapper.updateById(user);
        if (result == 0) {
            return JsonResult.error("修改密码失败");
        }
        return JsonResult.success();
    }

    /**
     * 更新个人资料
     *
     * @param updateUserInfoDto 参数
     * @return
     */
    @Override
    public JsonResult updateUserInfo(UpdateUserInfoDto updateUserInfoDto) {
        // 用户ID验证
        if (StringUtils.isNull(ShiroUtils.getUserId()) || ShiroUtils.getUserId() <= 0) {
            return JsonResult.error("用户ID不能为空");
        }

        // 实例化用户对象
        User user = new User();
        BeanUtils.copyProperties(updateUserInfoDto, user);
        user.setId(ShiroUtils.getUserId());
        // 头像处理
        if (!StringUtils.isEmpty(updateUserInfoDto.getAvatar()) && updateUserInfoDto.getAvatar().contains(CommonConfig.imageURL)) {
            user.setAvatar(updateUserInfoDto.getAvatar().replaceAll(CommonConfig.imageURL, ""));
        }
        int result = userMapper.updateById(user);
        if (result == 0) {
            return JsonResult.error("更新失败");
        }
        return JsonResult.success("更新成功");
    }

    /**
     * 重置密码
     *
     * @param resetPwdDto 参数
     * @return
     */
    @Override
    public JsonResult resetPwd(ResetPwdDto resetPwdDto) {
        // 用户ID验证
        if (StringUtils.isNull(resetPwdDto.getId())) {
            return JsonResult.error("用户ID不能为空");
        }
        User user = userMapper.selectById(resetPwdDto.getId());
        if (StringUtils.isNull(user)) {
            return JsonResult.error("用户信息不存在");
        }
        if (!user.getTenantId().equals(ShiroUtils.getTenantId())) {
            return JsonResult.error("当前用户非本租户用户");
        }
        // 设置新密码
        user.setPassword(CommonUtils.password("123456"));
        int reuslt = userMapper.updateById(user);
        if (reuslt == 0) {
            return JsonResult.error(null, "密码重置失败");
        }
        return JsonResult.success(null, "密码重置成功");
    }

    /**
     * 获取用户列表
     *
     * @param type 用户类型：1普通用户 2飞手
     * @return
     */
    @Override
    public JsonResult getUserList(Integer type) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        queryWrapper.eq("mark", 1);
        queryWrapper.eq("tenant_id", ShiroUtils.getTenantId());
        queryWrapper.orderByAsc("sort");
        List<User> userList = list(queryWrapper);
        return JsonResult.success(userList);
    }
}
