package com.izouma.dingdong.web.user;

import com.izouma.dingdong.dto.AddressDTO;
import com.izouma.dingdong.utils.SecurityUtils;
import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.user.Address;
import com.izouma.dingdong.service.user.AddressService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.user.AddressRepo;
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("/address")
@AllArgsConstructor
public class AddressController extends BaseController {
    private AddressService addressService;
    private 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.updateIsDefault(record.getId(), record.getUserId());
        }
        return record;
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<Address> all(PageQuery pageQuery) {
        return addressRepo.findAll(toSpecification(pageQuery, Address.class), toPageRequest(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.deleteById(id);
    }

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

    @GetMapping("/my")
    @ApiOperation("用户地址列表")
    public List<Address> my() {
        return addressRepo.findAllByUserIdAndEnabledTrue(SecurityUtils.getAuthenticatedUser().getId());
    }

    @GetMapping("/myDTO")
    @ApiOperation("带地址的用户地址列表")
    public List<AddressDTO> myDTO(Double longitude, Double latitude) {
        Long id = SecurityUtils.getAuthenticatedUser().getId();
        return addressService.sortAddress(id, longitude, latitude);
    }
}

