package com.izouma.dingdong.web;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.dingdong.domain.Verified;
import com.izouma.dingdong.service.VerifiedService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.VerifiedRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.utils.excel.ExcelUtils;
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;

@RestController
@RequestMapping("/verified")
@AllArgsConstructor
public class VerifiedController extends BaseController {
    private VerifiedService verifiedService;
    private VerifiedRepo verifiedRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Verified save(@RequestBody Verified record) {
        if (record.getId() != null) {
            Verified orig = verifiedRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            if (!orig.getCanEdit()) {
                throw new BusinessException("无法修改");
            }
            ObjUtils.merge(orig, record);
            return verifiedRepo.save(orig);
        }
        Verified verified = verifiedRepo.findByUserId(record.getUserId());
        if (ObjectUtil.isNotNull(verified)) {
            throw new BusinessException("此用户实名信息已存在");
        }

        return verifiedRepo.save(record);
    }


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

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

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

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

    @GetMapping("/my")
    public Verified my(Long userId) {
        return verifiedRepo.findByUserId(userId);
    }
}

