package com.izouma.wenlvju.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.izouma.wenlvju.domain.Message;
import com.izouma.wenlvju.dto.MessageUpload;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.MessageRepo;
import com.izouma.wenlvju.utils.JpaUtils;
import com.izouma.wenlvju.utils.excel.UploadDataListener;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class MessageService {

    private MessageRepo messageRepo;

    public Page<Message> all(PageQuery pageQuery) {
        return messageRepo.findAll(JpaUtils.toSpecification(pageQuery, Message.class), JpaUtils.toPageRequest(pageQuery));
    }

    public void excelTemp(HttpServletResponse response) throws IOException {
        // 设置response的Header
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + "Phone.xlsx");

        InputStream is = getClass().getResourceAsStream("/templates/Phone.xlsx");
        byte[] buffer = new byte[1024];
        int len;

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        while ((len = is.read(buffer)) > -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.flush();

        ServletOutputStream sos = response.getOutputStream();
        sos.write(outputStream.toByteArray());

        sos.flush();
        outputStream.close();
    }

    @Transactional(rollbackOn = Exception.class)
    public List<String> upload(MultipartFile file) {
        try {
            InputStream fis = file.getInputStream();
            UploadDataListener<MessageUpload> listener = new UploadDataListener<>();
            List<MessageUpload> phones = EasyExcel.read(fis, MessageUpload.class, listener)
                    .sheet()
                    .doReadSync();
            return phones.stream().map(MessageUpload::getPhone).distinct().collect(Collectors.toList());
        } catch (ExcelAnalysisException e) {
            e.printStackTrace();
            if (e.getCause() instanceof ExcelDataConvertException) {
                ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) e.getCause();
                String cellMsg = "";
                String errorMsg = String.format("excel表格:第%s行,第%s列,数据值为:%s,该数据值不符合要求,请检验后重新导入!请检查其他的记录是否有同类型的错误!", excelDataConvertException.getRowIndex() + 1, excelDataConvertException.getColumnIndex(), cellMsg);
                log.error(errorMsg);
                throw new BusinessException(errorMsg);
            }

        } catch (IOException e) {
            log.error("上传失败", e);
            throw new BusinessException("上传失败", e.getMessage());
        }
        return null;
    }
}
