package com.izouma.jiashanxia.web;

import com.izouma.jiashanxia.domain.Address;
import com.izouma.jiashanxia.service.AddressService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.AddressRepo;
import com.izouma.jiashanxia.utils.ObjUtils;
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("/address")
@AllArgsConstructor
public class AddressController extends BaseController {
    private final AddressService addressService;
    private final AddressRepo    addressRepo;

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


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

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

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

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

