package com.izouma.jmrh.web;

import com.izouma.jmrh.dto.*;
import com.izouma.jmrh.annotations.OperLog;
import com.izouma.jmrh.domain.BaseEntity;
import com.izouma.jmrh.domain.ResourceSupplyAndDemand;
import com.izouma.jmrh.enums.AuditStatus;
import com.izouma.jmrh.enums.DockingRole;
import com.izouma.jmrh.enums.ResSnDType;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.ResourceSupplyAndDemandRepo;
import com.izouma.jmrh.service.ResourceSupplyAndDemandService;
import com.izouma.jmrh.utils.SecurityUtils;
import com.izouma.jmrh.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/resourceSupplyAndDemand")
@AllArgsConstructor
public class ResourceSupplyAndDemandController extends BaseController {
    private ResourceSupplyAndDemandService resourceSupplyAndDemandService;
    private ResourceSupplyAndDemandRepo    resourceSupplyAndDemandRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    @OperLog(value = "供需管理-编辑", type = "编辑")
    public R save(@RequestBody ResSnDAndPropertyDTO record) {
        return resourceSupplyAndDemandService.save(record);
    }

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

    @PostMapping("/allDTO")
    @ApiOperation("前端列表查询")
    public Page<SndDTO> allDTO(@RequestBody PageQuery pageQuery) {
        return resourceSupplyAndDemandService
                .allDTO(Optional.ofNullable(SecurityUtils.getAuthenticatedUser()).map(BaseEntity::getId)
                        .orElse(null), pageQuery);
    }

    @GetMapping("/get/{id}")
    public SndDTO get(@PathVariable Long id) {
        return resourceSupplyAndDemandService
                .get(id, Optional.ofNullable(SecurityUtils.getAuthenticatedUser()).map(BaseEntity::getId)
                        .orElse(null));
    }

    @PostMapping("/del/{id}")
    @OperLog(value = "供需管理-删除", type = "删除")
    public void del(@PathVariable Long id) {
        resourceSupplyAndDemandRepo.deleteById(id);
    }



    @PostMapping("/back/{id}")
    @OperLog(value = "供需管理-删除", type = "删除")
    public void back(@PathVariable Long id) {
        resourceSupplyAndDemandRepo.back(id);
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<SndExcelDTO> data = all(pageQuery).getContent().stream().map(snd -> {
            SndExcelDTO dto = new SndExcelDTO();
            BeanUtils.copyProperties(snd, dto);
            return dto;
        }).collect(Collectors.toList());
        ExcelUtils.export(response, data);
    }

    @GetMapping("/myCollect")
    @ApiOperation("我收藏的")
    public Page<SndDTO> myCollect(@RequestParam(required = false) List<ResSnDType> types, Pageable pageable) {
        if (types == null) {
            types = new ArrayList<>();
        }
        return resourceSupplyAndDemandService.myCollect(SecurityUtils.getAuthenticatedUser().getId(), types, pageable);
    }

    @GetMapping("/my")
    @ApiOperation("我发布的")
    public Page<SndDTO> my(@RequestParam(required = false) List<ResSnDType> types, Pageable pageable) {
        return resourceSupplyAndDemandService.my(SecurityUtils.getAuthenticatedUser().getId(), types, pageable);
    }

    @GetMapping("/myDocking")
    @ApiOperation("我对接的")
    public Page<SndDTO> myDocking(@RequestParam(required = false) DockingRole role, List<ResSnDType> types, Pageable pageable) {
        if (role == null) {
            role = DockingRole.DOCKING;
        }
        return resourceSupplyAndDemandService
                .myDocking(SecurityUtils.getAuthenticatedUser().getId(), role, types, pageable);
    }

    @PostMapping("/audit")
    @OperLog(value = "供需管理-审核", type = "审核")
    public void audit(@RequestParam Long id, @RequestParam boolean pass) {
        ResourceSupplyAndDemand snd = resourceSupplyAndDemandRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        snd.setStatus(pass ? AuditStatus.PASS : AuditStatus.DENY);
        snd.setAuditTime(LocalDateTime.now());
        resourceSupplyAndDemandRepo.save(snd);
    }
}

