package com.ads.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ads.business.dao.UserDao;
import com.ads.business.entity.User;
import com.ads.business.service.AdmUserService;
import com.ads.business.service.UserService;
import com.ads.business.service.data.UserOutData;
import com.ads.business.service.model.request.AdmUserListRequest;
import com.ads.business.service.model.request.EditUserRequest;
import com.ads.business.service.model.request.ResetPasswordRequest;
import com.ads.business.service.model.response.AdmUserListResponse;
import com.ads.common.data.JsonResult;
import com.ads.common.exception.BusinessException;
import com.ads.common.util.OnlineUserUtils;
import com.ads.common.util.PageUtils;
import com.ads.common.util.UtilMessage;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Return
 * @Author hou
 * @Date 2021/10/25 9:33
 * @Destription
 */

@Service
@Slf4j
public class AdmUserServiceImpl extends ServiceImpl<UserDao, User> implements AdmUserService {

    @Resource
    private UserService userService;

    @Override
    public JsonResult list(AdmUserListRequest request) {
        log.info("后台用户列表 request:{}", JSON.toJSONString(request));
        Long currPage = request.getPage() == null ? 1 : request.getPage().longValue();
        Long pageSize = request.getPageSize() == null ? 10 : request.getPageSize().longValue();
        Page<AdmUserListResponse> page = new Page<>(currPage, pageSize);
        QueryWrapper<AdmUserListResponse> wrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(request.getAccount())) {
            wrapper.like("hu.account", request.getAccount());
        }
        if (StringUtils.isNotBlank(request.getName())) {
            wrapper.like("hu.name", request.getName());
        }
        wrapper.orderByDesc("hu.create_time");
        return JsonResult.success(new PageUtils(this.baseMapper.findPage(page, wrapper)), UtilMessage.GET_MESSAGE_SUCCESS);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult add(EditUserRequest request) {
        log.info("新增后台用户 request:{}", JSON.toJSONString(request));
        User userServiceOne = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getAccount, request.getAccount()));
        if (ObjectUtil.isNotNull(userServiceOne)) {
            throw new BusinessException(UtilMessage.USER_ACCOUNT_EXIST);
        }
        if (StringUtils.isBlank(request.getPassword())) {
            throw new BusinessException("新增用户密码不能为空");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePassword = passwordEncoder.encode(request.getPassword());
        User user = new User();
        user.setAccount(request.getAccount());
        user.setName(request.getName());
        user.setPassword(encodePassword);
        user.setStatus(request.getStatus());
        user.setCreateUser(Long.valueOf(OnlineUserUtils.get().getUserId()));
        user.setCreateTime(new Date());
        user.setUpdateUser(Long.valueOf(OnlineUserUtils.get().getUserId()));
        user.setUpdateTime(new Date());
        userService.save(user);
        return JsonResult.success(null, UtilMessage.SAVE_MESSAGE_SUCCESS);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult update(EditUserRequest request) {
        log.info("修改后台用户 request:{}", JSON.toJSONString(request));
        User user = userService.getById(request.getUserId());
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException(UtilMessage.USER_EMPTY);
        }
        List<User> list = userService.list(Wrappers.lambdaQuery(User.class)
                .eq(User::getAccount, request.getAccount())
                .ne(User::getUserId, request.getUserId()));
        if (CollectionUtils.isNotEmpty(list)) {
            throw new BusinessException(UtilMessage.USER_ACCOUNT_EXIST);
        }
        user.setAccount(request.getAccount());
        user.setName(request.getName());
        user.setStatus(request.getStatus());
        user.setUpdateUser(Long.valueOf(OnlineUserUtils.get().getUserId()));
        user.setUpdateTime(new Date());
        userService.updateById(user);
        return JsonResult.success(null, UtilMessage.SAVE_MESSAGE_SUCCESS);
    }

    /**
     * 获取用户详情
     *
     * @param userId 用户ID
     * @return 返回结果信息
     */
    @Override
    public JsonResult detail(Long userId) {
        if (ObjectUtil.isNull(userId)) {
            throw new BusinessException(UtilMessage.USER_EMPTY);
        }
        UserOutData user = baseMapper.getById(userId);

        if (ObjectUtil.isEmpty(user)) {
            throw new BusinessException(UtilMessage.USER_EMPTY);
        }
        return JsonResult.success(user);
    }

    /**
     * 状态开关
     *
     * @param id     用户ID
     * @param status 用户状态
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult updateSwitch(Long id, Integer status) {
        User userdb = this.getById(id);
        if (ObjectUtil.isEmpty(userdb)) {
            throw new BusinessException(UtilMessage.USER_EMPTY);
        }
        if (userdb.getStatus().equals(status) && status == 1) {
            throw new BusinessException("用户已启用，请勿重复操作！");
        }
        if (userdb.getStatus().equals(status) && status == 0) {
            throw new BusinessException("用户已禁用，请勿重复操作！");
        }
        User user = new User();
        user.setUserId(id);
        user.setStatus(status);
        this.updateById(user);
        String msg;
        if (status == 1) {
            msg = UtilMessage.ENABLE_MESSAGE_SUCCESS;
        } else {
            msg = UtilMessage.DISABLE_MESSAGE_SUCCESS;
        }
        return JsonResult.success(null, msg);
    }

    /**
     * 重置密码
     *
     * @param request 重置密码入参
     * @return JsonResult
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult resetPassword(ResetPasswordRequest request) {
        User userdb = this.getById(request.getId());
        if (ObjectUtil.isEmpty(userdb)) {
            throw new BusinessException(UtilMessage.USER_EMPTY);
        }
//        if (userdb.getPassword().equals(request.getPassword())) {
//            throw new BusinessException("重置密码与原密码一致，请重新输入！");
//        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePassword = passwordEncoder.encode(request.getPassword());
        User user = new User();
        user.setUserId(request.getId());
        user.setPassword(encodePassword);
        this.updateById(user);

        return JsonResult.success(null, UtilMessage.PASSWORD_MESSAGE_SUCCESS);
    }
}
