package com.izouma.jiashanxia.web;

import com.izouma.jiashanxia.domain.Company;
import com.izouma.jiashanxia.domain.User;
import com.izouma.jiashanxia.service.CompanyService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.CompanyRepo;
import com.izouma.jiashanxia.utils.SecurityUtils;
import com.izouma.jiashanxia.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/company")
@AllArgsConstructor
public class CompanyController extends BaseController {
    private CompanyService companyService;
    private CompanyRepo    companyRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Company save(@RequestBody Company record) {
        return companyService.save(record);
    }

    @PreAuthorize("hasAnyRole('ADMIN','CREATOR')")
    @PostMapping("/all")
    public Page<Company> all(@RequestBody PageQuery pageQuery) {
        return companyService.all(pageQuery, SecurityUtils.getAuthenticatedUser());
    }

    @GetMapping("/get/{id}")
    public Company get(@PathVariable Long id) {
        return companyRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        companyRepo.softDelete(id);
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<Company> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }

    @GetMapping("/allList")
    public List<Company> allList() {
        return companyRepo.findAll();
    }

    @PostMapping("/employee")
    @ApiOperation("根据用户id员工列表")
    public List<User> employee(Long userId) {
        return companyService.employee(userId);
    }

    @PostMapping("/addEmp")
    @ApiOperation("添加员工")
    public void addEmp(@RequestParam Long userId, @RequestParam Long companyId) {
        companyService.addUser(userId, companyId);
    }

    @PostMapping("/removeEmp")
    @ApiOperation("添加员工")
    public void removeEmp(@RequestParam Long userId, @RequestParam Long companyId) {
        companyService.removeUser(userId, companyId);
    }
}

