package com.zksy.system.basicData.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.utils.DateUtils;
import com.zksy.common.utils.DeleteTableUtils;
import com.zksy.system.basicData.domain.OwLeavingMessage;
import com.zksy.system.basicData.mapper.OwLeavingMessageMapper;
import com.zksy.system.basicData.service.OwLeavingMessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import static com.zksy.system.utils.PdfUtil.fillPdf;

/**
 * 官网留言Service业务层处理
 *
 * @author sy
 * @date 2024-06-27
 */
@Service
public class OwLeavingMessageServiceImpl extends ServiceImpl<OwLeavingMessageMapper, OwLeavingMessage> implements OwLeavingMessageService {
    @Resource
    private OwLeavingMessageMapper mapper;

    @Override
    @Transactional
    public AjaxResult deleteAll() {
        DeleteTableUtils<OwLeavingMessage> utils = new DeleteTableUtils<>();
        utils.del(OwLeavingMessage::getId,mapper);
        return AjaxResult.success("全部删除成功");
    }

    public void generateVoucher(HttpServletResponse response,String name, Long id) throws Exception {
        InputStream inputStream = new ClassPathResource("/template/留言模板.pdf").getInputStream();
        Map<String, String> data = new HashMap<>();
        OwLeavingMessage owLeavingMessage = mapper.selectById(id);

        data.put("type", name);
        data.put("createTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, owLeavingMessage.getCreateTime()));
        data.put("name", owLeavingMessage.getName());
        data.put("phone", owLeavingMessage.getPhone());
        if(StringUtils.isNotEmpty(owLeavingMessage.getEnterpriseName())) {
            data.put("enterpriseName", owLeavingMessage.getEnterpriseName());
        }
        if(StringUtils.isNotEmpty(owLeavingMessage.getUnifiedSocialCreditCode())) {
            data.put("unifiedSocialCreditCode", owLeavingMessage.getUnifiedSocialCreditCode());
        }
        data.put("content",owLeavingMessage.getContent());

        byte[] filledPdfBytes = fillPdf(inputStream, null, data);
        // 设置HTTP响应头
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=liuyan.pdf");

        // 将字节数组写入到HTTP响应输出流中
        OutputStream outStream = response.getOutputStream();
        outStream.write(filledPdfBytes);
        outStream.flush();
        outStream.close();
    }
}
