package cn.wise.sc.energy.power.plant.business.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.wise.sc.energy.power.plant.business.domain.Role;
import cn.wise.sc.energy.power.plant.business.repository.RoleRepository;
import cn.wise.sc.energy.power.plant.business.utils.BeanUtilsExt;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author neo.shu
 * @since 2020/10/16 17:53
 */
@CrossOrigin
@RestController
@RequestMapping("role/")
@Slf4j
public class RoleController {

    @Autowired
    RoleRepository roleRepository;

    @ApiOperation("获取角色列表")
    @PostMapping("/list")
    public BaseResponse<List<Role>> interaction() {
        //不能新增超级管理员
        List<Role> list = roleRepository.findAllByRoleIdNotIn(CollectionUtil.newArrayList(1));
        List<Role> lists = roleRepository.findAll();
        return BaseResponse.okData(lists);

    }

    @ApiOperation("创建或更新角色")
    @PostMapping("/newOrUpdate")
    @Transactional(propagation = Propagation.REQUIRED)
    public BaseResponse<Boolean> add(@RequestBody Role info) {
        Role role;
        if (info.getRoleId() == null) {
            info.setRoleId(null);
            role = roleRepository.save(info);
        } else {
            role = roleRepository.getOne(info.getRoleId());
            BeanUtils.copyProperties(info, role, BeanUtilsExt.getNullPropertyNames(info));
            role = roleRepository.save(role);
        }
        if (role.getId() != null) {
            return BaseResponse.okData(true);
        } else {
            return BaseResponse.okData(false);
        }
    }
}
