package cn.cslg.pas.service;

import cn.cslg.pas.domain.AdminUser;
import cn.cslg.pas.mapper.AdminUserMapper;
import cn.cslg.pas.common.utils.Response;
import cn.cslg.pas.common.utils.StringUtils;
import cn.cslg.pas.common.model.vo.AdminUserVO;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 管理员表 服务类
 * </p>
 *
 * @author 王岩
 * @since 2022-03-25
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class AdminUserService extends ServiceImpl<AdminUserMapper, AdminUser> {

    public AdminUser getAdminUserByUsername(String username) {
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUser::getUsername, username);
        return this.getOne(queryWrapper);
    }

    public IPage<AdminUser> getPageList(AdminUserVO params) {
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(params.getName())) {
            queryWrapper.like(AdminUser::getName, params.getName());
        }
        if (StringUtils.isNotEmpty(params.getUsername())) {
            queryWrapper.like(AdminUser::getUsername, params.getUsername());
        }
        IPage<AdminUser> pageList = this.page(new Page<>(params.getCurrent(), params.getSize()), queryWrapper);
        pageList.getRecords().forEach(item -> {
            item.setPassword(null);
        });
        return pageList;
    }

    public String add(AdminUser adminUser) {
        AdminUser temp = this.getAdminUserByUsername(adminUser.getUsername());
        if (temp != null) {
            return Response.error("用户名已存在");
        }
        adminUser.setPassword(SecureUtil.md5("123456"));
        adminUser.setCreateTime(new Date());
        adminUser.insert();
        return Response.success(adminUser.getId());
    }

    public String edit(AdminUser adminUser) {
        AdminUser temp = this.getAdminUserByUsername(adminUser.getUsername());
        if (temp != null && !temp.getId().equals(adminUser.getId())) {
            return Response.error("用户名已存在");
        }
        adminUser.updateById();
        return Response.success();
    }

    public String delete(Integer id) {
        this.removeById(id);
        return Response.success();
    }

    public void resetPassword(Integer id) {
        AdminUser adminUser = this.getById(id);
        adminUser.setPassword(SecureUtil.md5("123456"));
        adminUser.updateById();
    }
}
