package com.gitee.sop.admin.controller.sys;

import com.gitee.sop.admin.common.dto.StatusUpdateDTO;
import com.gitee.sop.admin.common.exception.BizException;
import com.gitee.sop.admin.common.req.StatusUpdateParam;
import com.gitee.sop.admin.common.resp.Result;
import com.gitee.sop.admin.common.util.CopyUtil;
import com.gitee.sop.admin.dao.entity.SysDept;
import com.gitee.sop.admin.service.sys.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
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;
import java.util.Objects;

/**
 * @author 六如
 */
@RestController
@RequestMapping("sys/dept")
public class SysDeptController {

    @Autowired
    private SysDeptService sysDeptService;

    /**
     * listAll
     *
     * @return 返回分页结果
     */
    @GetMapping("/listAll")
    public Result<List<SysDept>> listAll() {
        List<SysDept> sysDepts = sysDeptService.listAll();
        return Result.ok(sysDepts);
    }

    /**
     * 新增记录
     *
     * @param sysDept 表单参数
     * @return 返回添加后的主键值
     */
    @PostMapping("/add")
    public Result<Long> add(@Validated @RequestBody SysDept sysDept) {
        Long id = sysDeptService.addDept(sysDept);
        // 返回添加后的主键值
        return Result.ok(id);
    }

    /**
     * 修改记录
     *
     * @param sysDept 表单数据
     * @return 返回影响行数
     */
    @PostMapping("/update")
    public Result<Integer> update(@Validated @RequestBody SysDept sysDept) {
        if (Objects.equals(sysDept.getParentId(), sysDept.getId())) {
            throw new BizException("父级不能选自己");
        }
        return Result.ok(sysDeptService.update(sysDept));
    }


    /**
     * 修改状态
     *
     * @param param 表单数据
     * @return 返回影响行数
     */
    @PostMapping("/updateStatus")
    public Result<Integer> updateStatus(@Validated @RequestBody StatusUpdateParam param) {
        StatusUpdateDTO statusUpdateDTO = CopyUtil.copyBean(param, StatusUpdateDTO::new);
        return Result.ok(sysDeptService.updateStatus(statusUpdateDTO));
    }

}
