package com.izouma.zhirongip.web.demand;

import cn.hutool.core.convert.Convert;
import com.izouma.zhirongip.domain.Setting;
import com.izouma.zhirongip.domain.demand.Funding;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.SettingRepo;
import com.izouma.zhirongip.repo.demand.FundingRepo;
import com.izouma.zhirongip.service.demand.FundingService;
import com.izouma.zhirongip.utils.ObjUtils;
import com.izouma.zhirongip.utils.SecurityUtils;
import com.izouma.zhirongip.utils.excel.ExcelUtils;
import com.izouma.zhirongip.web.BaseController;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/funding")
@AllArgsConstructor
public class FundingController extends BaseController {
    private final FundingService fundingService;
    private final FundingRepo    fundingRepo;
    private final SettingRepo    settingRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<Funding> all(@RequestBody PageQuery pageQuery) {
        Map<String, Object> query = pageQuery.getQuery();
        Object fieldObj = query.get("purpose");
        Long field = Convert.convert(Long.class, fieldObj);
        query.remove("purpose");
        return fundingService.all(pageQuery, field);
    }

    @GetMapping("/get/{id}")
    public Funding get(@PathVariable Long id) {
        Funding record = fundingRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        Map<Long, String> settingMap = settingRepo.findAllById(record.getPurpose())
                .stream()
                .collect(Collectors.toMap(Setting::getId, Setting::getName));
        record.setPurposeName(record.getPurpose().stream().map(settingMap::get).collect(Collectors.toList()));
        return record;
    }

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

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

