package com.izouma.dingdong.web.backstage;

import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.backstage.CooperateApply;
import com.izouma.dingdong.service.backstage.CooperateApplyService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.backstage.CooperateApplyRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.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("/cooperateApply")
@AllArgsConstructor
public class CooperateApplyController extends BaseController {
    private CooperateApplyService cooperateApplyService;
    private CooperateApplyRepo cooperateApplyRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<CooperateApply> all(PageQuery pageQuery) {
        return cooperateApplyRepo.findAll(toSpecification(pageQuery,CooperateApply.class), toPageRequest(pageQuery));
    }

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

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

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

    @GetMapping("/contact")
    @ApiOperation("确认已联系")
    public void contact(Long id){
        CooperateApply apply = cooperateApplyRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        apply.setIsPass(true);
        cooperateApplyRepo.save(apply);
    }
}

