package com.izouma.nineth.web;

import com.izouma.nineth.domain.CompanyCollection;
import com.izouma.nineth.dto.oasis.OasisDistrictCollectionDTO;
import com.izouma.nineth.dto.oasis.OasisDistrictDTO;
import com.izouma.nineth.enums.CollectionStatus;
import com.izouma.nineth.service.CompanyCollectionService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.CompanyCollectionRepo;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
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.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/companyCollection")
@AllArgsConstructor
public class CompanyCollectionController extends BaseController {
    private CompanyCollectionService companyCollectionService;
    private CompanyCollectionRepo    companyCollectionRepo;

    @PreAuthorize("hasAnyRole('ADMIN','COMPANY')")
    @PostMapping("/save")
    public CompanyCollection save(@RequestBody CompanyCollection record) {
        if (record.getId() != null) {
            CompanyCollection orig = companyCollectionRepo.findById(record.getId())
                    .orElseThrow(new BusinessException("无记录"));
            if (CollectionStatus.SUCCESS.equals(orig.getStatus())) {
                throw new BusinessException("已通过申请，不可编辑");
            }

            ObjUtils.merge(orig, record);
            return companyCollectionRepo.save(orig);
        }
        record.setUserId(SecurityUtils.getAuthenticatedUser().getId());
        return companyCollectionRepo.save(record);
    }

    //oasis创建保存地块接口
    @PreAuthorize("hasAnyRole('ADMIN','COMPANY')")
    @PostMapping("/saveDistrict")
    public CompanyCollection saveDistrict(@RequestBody OasisDistrictDTO oasisDistrictDTO) {
        CompanyCollection record = new CompanyCollection();
        BeanUtils.copyProperties(oasisDistrictDTO, record);
        record.setStatus(CollectionStatus.PENDING);
        record.setCategory("地块");
        record.setUserId(7958191L);
        record.setMinter("oasis地块测试");
        if (record.getId() != null) {
            CompanyCollection orig = companyCollectionRepo.findById(record.getId())
                    .orElseThrow(new BusinessException("无记录"));
            if (CollectionStatus.SUCCESS.equals(orig.getStatus())) {
                throw new BusinessException("已通过申请，不可编辑");
            }

            ObjUtils.merge(orig, record);
            return companyCollectionRepo.save(orig);
        }
        record.setUserId(SecurityUtils.getAuthenticatedUser().getId());
        return companyCollectionRepo.save(record);
    }

    //oasis创建保存地块接口
    @PreAuthorize("hasAnyRole('ADMIN','COMPANY')")
    @PostMapping("/multiDistrict")
    public List<CompanyCollection> multiDistrict(@RequestBody List<OasisDistrictDTO> oasisDistrictDTOs) {
        List<CompanyCollection> companyCollections = new ArrayList<>();
        oasisDistrictDTOs.forEach(oasisDistrictDTO -> {
            CompanyCollection record = new CompanyCollection();
            BeanUtils.copyProperties(oasisDistrictDTO, record);
            record.setStatus(CollectionStatus.PENDING);
            record.setCategory("地块");
            record.setUserId(7958191L);
            record.setMinter("oasis地块测试");
            if (record.getId() != null) {
                CompanyCollection orig = companyCollectionRepo.findById(record.getId())
                        .orElseThrow(new BusinessException("无记录"));
                if (CollectionStatus.SUCCESS.equals(orig.getStatus())) {
                    throw new BusinessException("已通过申请，不可编辑");
                }

                ObjUtils.merge(orig, record);
                companyCollections.add(orig);
            }
            record.setUserId(SecurityUtils.getAuthenticatedUser().getId());
            companyCollections.add(record);
        });
        return companyCollectionRepo.saveAll(companyCollections);
    }

    //oasis创建地块接口
    @PreAuthorize("hasAnyRole('ADMIN','COMPANY')")
    @PostMapping("/oasisSearch")
    public List<OasisDistrictCollectionDTO> oasisSearch(@RequestBody List<Long> oasisIds) {
        return companyCollectionService.oasisSearch(oasisIds);
    }


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

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

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

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

    @PostMapping("/pass")
    public void pass(@RequestParam Long id) {
        companyCollectionService.audit(id, CollectionStatus.SUCCESS, null);
    }

    @PostMapping("/deny")
    public void deny(@RequestParam Long id, String reason) {
        companyCollectionService.audit(id, CollectionStatus.FAIL, reason);
    }

}

