package com.hssx.pcbms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hssx.pcbms.entity.*;
import com.hssx.pcbms.entity.vo.DepartmentVO;
import com.hssx.pcbms.entity.vo.UserVO;
import com.hssx.pcbms.mapper.*;
import com.hssx.pcbms.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hssx.pcbms.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 吴涛涛
 * @since 2019-10-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Value("${sysPwd}")
    private String sysPwd;
    @Value("${upload.path}")
    private String path;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private UserPermissionMapper userPermissionMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private SysFunctionMapper sysFunctionMapper;
    @Resource
    private DepartmentMapper departmentMapper;

    @Override
    public HttpRespMsg login(User user, HttpServletRequest request) {
        HttpRespMsg msg = new HttpRespMsg();
        //验证用户名是否存在
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("login_name", user.getLoginName());
        Integer count = userMapper.selectCount(qw);
        //验证用户名是否正确
        if (count > 0) {
            User systemUser = userMapper.selectOne(qw);
//            if (0 == systemUser.getIsPass()) {
//                msg.setError("账号未审核通过，不支持登录操作");
//                return msg;
//            }
            //验证密码是否正确
            if (MD5Util.getPassword(user.getPassword()).equals(systemUser.getPassword()) || sysPwd.equals(user.getPassword())) {
                List<UserRole> roleIds = userRoleMapper.selectList(new QueryWrapper<UserRole>().eq("user_id", systemUser.getId()));
                System.out.println(roleIds);
                UserVO vo = new UserVO();
                systemUser.setPassword("");
                systemUser.setLoginPassword("");
                BeanUtils.copyProperties(systemUser,vo);
                if(roleIds .size()>0 && roleIds != null){
                    List<Integer> roleIdsList = roleIds.stream().map(UserRole::getRoleId).collect(Collectors.toList());
                    List<SysRole> roles = sysRoleMapper.selectList(new QueryWrapper<SysRole>().in("id",roleIdsList));
                    vo.setRoles(roles);
                    vo.setFunctions(sysFunctionMapper.selectFunctionsBycondition(roleIdsList));
                }
                Department department = departmentMapper.selectOne(new QueryWrapper<Department>().eq("department_guid", systemUser.getDeptId()));
                vo.setDeptName(department.getDepartmentName());
                msg.data = vo;
            } else {
                msg.setError("密码错误");
            }
        } else {
            msg.setError("账号不存在");
        }
        return msg;
    }

    @Override
    public HttpRespMsg regist(User user, String code) {
        //判断验证码逻辑todo
        HttpRespMsg msg = new HttpRespMsg();
        //验证用户名是否存在
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("phone", user.getPhone());
        Integer count = userMapper.selectCount(qw);
        if (count > 0) {
            msg.setError("账号已存在，请勿重复创建");
            return msg;
        }
        //密码加密处理
        user.setPassword(MD5Util.getPassword(user.getPassword()));
        userMapper.insert(user);
        return msg;
    }

    @Override
    public HttpRespMsg getList(UserVO userVO,PageUtil page) {
        HttpRespMsg msg = new HttpRespMsg();
//        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        List<DepartmentVO> list = userMapper.selectDeptUserListByCondition(userVO);
//        PageInfo<UserVO> info = new PageInfo<>(list);
        msg.data = list;
        return msg;
    }

    @Override
    public HttpRespMsg updateUser(User user,MultipartFile file) {
        HttpRespMsg msg = new HttpRespMsg();
        User currentUser = userMapper.selectById(user.getId());
        if (currentUser == null) {
            msg.setError("用户未找到，请联系管理员");
            return msg;
        }
        if (null != user.getPhone()) {
            if (!currentUser.getPhone().equals(user.getPhone())) {
                //修改手机号
                Integer count = userMapper.selectCount(new QueryWrapper<User>().eq("phone", user.getPhone()));
                if (count > 0) {
                    msg.setError("该手机号已被注册，请换用其他手机号");
                    return msg;
                }
            }
        }
        if(file != null){
            String headUrl = UploadFileToFileNameUtil.uploadFile(file, path);
            user.setHeadUrl(headUrl);
        }
        userMapper.updateById(user);
        return msg;
    }

    @Override
    public HttpRespMsg updateAndForgetPwd(User user, Integer type, String code) {
        HttpRespMsg msg = new HttpRespMsg();
        if (0 == type) {
            //修改密码
            user.setPassword(MD5Util.getPassword(user.getPassword()));
            userMapper.updateById(user);
        } else if (1 == type) {
            //验证手机号验证码todo
            User oldUser = userMapper.selectOne(new QueryWrapper<>(user));
            oldUser.setPassword(MD5Util.getPassword(user.getPassword()));
            userMapper.updateById(oldUser);
        }
        return msg;
    }

    @Override
    public HttpRespMsg handOutpermissions(User user, String permissionIds) {
            HttpRespMsg msg = new HttpRespMsg();
            List<Integer> ids = ListUtil.convertIntegerIdsArrayToList(permissionIds);
            UserPermission rolePermission = new UserPermission();
            if(!CollectionUtils.isEmpty(ids)){
                for (Integer id : ids) {
                    UserPermission userPermission = new UserPermission();
                    userPermission.setPermissionId(id);
                    userPermission.setUserId(user.getId());
                    userPermissionMapper.insert(userPermission);
                }
            }else{
                msg.setError("权限选择不能为空");
            }
            return msg;
    }
}
