package com.xydl.cac.service.impl;

import com.xydl.cac.config.BizConfig;
import com.xydl.cac.entity.Admin;
import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.repository.AdminRepository;
import com.xydl.cac.service.AdminService;
import com.xydl.cac.util.Md5;
import com.xydl.cac.util.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

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

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class AdminServiceImpl implements AdminService {

    @Resource
    AdminRepository repository;
    @Resource
    BizConfig bizConfig;

    @Override
    public List<Admin> listAll() {
        return repository.findAll();
    }

    @Override
    public Admin add(Admin item) throws Exception {
        item.setId(null);
        List<Admin> list = repository.findByName(item.getName());
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException("该名称已存在");
        }
        String salt = UUID.randomUUID().toString().replace("-", "");
        String password = Md5.getMD5Code(salt + item.getPassword());
        item.setPassword(password);
        return repository.save(item);
    }

    @Override
    public void updatePasswd(Admin item) throws Exception {
        String salt = UUID.randomUUID().toString().replace("-", "");
        String password = Md5.getMD5Code(salt + item.getPassword());
        item.setPassword(password);
        repository.save(item);
    }

    @Override
    public void delete(Integer id) {
        repository.deleteById(id);
    }

    @Override
    public Admin loginold(String name, String password) throws Exception {
        List<Admin> list = repository.findByName(name);
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("用户或密码不正确");
        }
        Admin admin = list.get(0);
        String newPwd = RsaUtils.decryptByPrivateKey(bizConfig.getRsakey(), password);
        String userPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!admin.getPassword().equals(userPassword)) {
            throw new BusinessException("用户或密码不正确");
        }
        return admin;
    }

    @Override
    public Admin login(Admin user) throws Exception {
        List<Admin> list = repository.findByName(user.getName());
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("用户或密码不正确");
        }
        Admin admin = list.get(0);
        String userPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        if (!admin.getPassword().equals(userPassword)) {
            throw new BusinessException("用户或密码不正确");
        }
        return admin;
    }

}
