package com.izouma.jiashanxia.web;

import com.izouma.jiashanxia.domain.CommissionRecord;
import com.izouma.jiashanxia.dto.CommissionRecordDTO;
import com.izouma.jiashanxia.service.CommissionRecordService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.CommissionRecordRepo;
import com.izouma.jiashanxia.utils.ObjUtils;
import com.izouma.jiashanxia.utils.SecurityUtils;
import com.izouma.jiashanxia.utils.excel.ExcelUtils;
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("/commissionRecord")
@AllArgsConstructor
public class CommissionRecordController extends BaseController {
    private CommissionRecordService commissionRecordService;
    private CommissionRecordRepo    commissionRecordRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public CommissionRecord save(@RequestBody CommissionRecord record) {
        if (record.getId() != null) {
            CommissionRecord orig = commissionRecordRepo.findById(record.getId())
                    .orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return commissionRecordRepo.save(orig);
        }
        return commissionRecordRepo.save(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<CommissionRecord> all(@RequestBody PageQuery pageQuery) {
        return commissionRecordService.all(pageQuery);
    }

    @PreAuthorize("hasAnyRole('ADMIN','CREATOR')")
    @PostMapping("/backAll")
    public Page<CommissionRecord> backAll(@RequestBody PageQuery pageQuery) {
        return commissionRecordService.backAll2(pageQuery);
    }

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

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

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

    @GetMapping("/my")
    public List<CommissionRecordDTO> my() {
        return commissionRecordService.my(SecurityUtils.getAuthenticatedUser().getId());
    }
}

