package com.jkcredit.invoice.hub.service.permission;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jkcredit.invoice.hub.mapper.PermissionMapper;
import com.jkcredit.invoice.hub.model.dto.permission.PermissionDto;
import com.jkcredit.invoice.hub.model.po.permission.PermissionPo;
import com.jkcredit.invoice.hub.model.vo.permission.PermissionVo;
import com.jkcredit.invoice.hub.service.base.BaseService;
import com.jkcredit.invoice.hub.spi.lang.exception.ServiceException;
import com.jkcredit.invoice.hub.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @description:
 * @author: xusonglin
 * @create: 2020/1/6 14:46
 * @version: V1.0
 **/
@Slf4j
@Service
@Transactional(readOnly = true)
public class PermissionServiceImpl extends BaseService implements PermissionService {
    @Resource
    PermissionMapper permissionMapper;

    @Override
    public List<PermissionPo> getPermissionByUserId(Long userId) {
        return permissionMapper.getPermissionByUserId(userId);
    }

    @Override
    public IPage<PermissionVo> getPermissions(Page page, PermissionDto permissionDto) {
        IPage<PermissionPo> permissionPoIPage = permissionMapper.getPermissions(page, permissionDto);
        return permissionPoIPage.convert(this::convert);
    }

    private PermissionVo convert(PermissionPo po) {
        PermissionVo vo = new PermissionVo();
        BeanUtils.copyProperties(po, vo);
        return vo;
    }

    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public void savePermission(PermissionDto permissionDto) {
        validate(permissionDto);
        PermissionPo permissionPo = new PermissionPo();
        BeanUtil.copyProperties(permissionPo, permissionDto);
        permissionPo.setCreateTime(new Date());

        try {
            permissionMapper.insert(permissionPo);
        } catch (Exception e) {
            log.error("新增权限失败，失败原因：{}", e.getMessage());
            throw new ServiceException("新增权限失败");
        }
    }

    @Override
    public List<PermissionVo> getPermissions() {
        List<PermissionPo> permissionPoList = permissionMapper.selectList(null);
        List<PermissionVo> permissionVoList = new ArrayList<>();
        for (PermissionPo permissionPo : permissionPoList) {
            permissionVoList.add(convert(permissionPo));
        }
        return permissionVoList;
    }
}
