package com.izouma.wenlvju.web;

import com.izouma.wenlvju.domain.Message;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.MessageRepo;
import com.izouma.wenlvju.service.MessageService;
import com.izouma.wenlvju.service.sms.NjwlSmsService;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
@RequestMapping("/message")
@AllArgsConstructor
public class MessageController extends BaseController {
    private MessageService messageService;
    private MessageRepo    messageRepo;
    private NjwlSmsService njwlSmsService;

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

    @GetMapping("/send/{id}")
    public void send(@PathVariable Long id) {
        Message message = messageRepo.findById(id).orElseThrow(new BusinessException("无短信内容"));
        String result = njwlSmsService.sendSms(String.join(",", message.getPhone()), message.getContent());
        message.setResponseBody(result);
        messageRepo.save(message);
    }


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

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

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

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

    @GetMapping(value = "/excelTemp", produces = "application/vnd.ms-excel;charset=utf-8")
    public void excelTemp(HttpServletResponse response) throws IOException {
        messageService.excelTemp(response);
    }

    @PostMapping("/upload")
    public List<String> uploadFile(@RequestParam("file") MultipartFile file) {
        return messageService.upload(file);
    }
}

