package com.yeejoin.amos.boot.module.elevator.biz.service.impl;

import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.elevator.api.dto.VoiceRecordFileDto;
import com.yeejoin.amos.boot.module.elevator.api.entity.TemplateExport;
import com.yeejoin.amos.boot.module.elevator.api.mapper.TemplateExportMapper;
import com.yeejoin.amos.boot.module.elevator.api.service.ITemplateExportService;
import com.yeejoin.amos.boot.module.elevator.api.dto.TemplateExportDto;
import com.yeejoin.amos.boot.module.elevator.flc.api.feign.PrivilegeFeginService;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 模板表服务实现类
 *
 * @author system_generator
 * @date 2021-10-25
 */
@Slf4j
@Service
public class TemplateExportServiceImpl extends BaseService<TemplateExportDto, TemplateExport, TemplateExportMapper> implements ITemplateExportService {
    /**
     * 分页查询
     */
    public Page<TemplateExportDto> queryForTemplateExportPage(Page<TemplateExportDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<TemplateExportDto> queryForTemplateExportList() {
        return this.queryForList("", false);
    }


    @Autowired
    PrivilegeFeginService privilegeFeginService;

    /**
     * 将excel和录音文件打包zip返回
     *
     * @param response    响应体
     * @param excelBytes  excel文件
     * @param recordFiles 录音文件
     */
    public void packZip(HttpServletResponse response, String fileName, byte[] excelBytes, String fileType, List<JSONObject> recordFiles) {
        // 打包zip
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             ZipOutputStream zip = new ZipOutputStream(outputStream)) {
            // 写入excel
            zip.putNextEntry(new ZipEntry(fileName + "." + ("1039".equals(fileType) ? ExcelTypeEnum.XLS : ExcelTypeEnum.XLSX)));
            IOUtils.write(excelBytes, zip);
            zip.closeEntry();
            // 写入录音
            for (JSONObject recordFile : recordFiles) {
                try {
                    String workNum = recordFile.getString("workNum");
                    byte[] fileByte = (byte[]) recordFile.get("fileByte");
                    zip.putNextEntry(new ZipEntry("工单号【" + workNum + "】录音.MP3"));
                    IOUtils.write(fileByte, zip);
                    zip.closeEntry();
                } catch (IOException e) {
                    log.error("打包zip失败：" + e.getMessage());
                    throw new BadRequest("打包zip失败");
                }
            }
            // 所有条目写入完成后关闭 ZipOutputStream
            zip.finish();
            // 设置响应头并将压缩文件写入 HttpServletResponse
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/zip");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".zip", "UTF-8"));
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            IOUtils.write(outputStream.toByteArray(), response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出异常：", e);
        }
    }

    public JSONObject downloadRecordFile(VoiceRecordFileDto s) {
        try {
            Response fileResponse = privilegeFeginService.downloadFileByStream(s.getFilePath());

            if (fileResponse.status() != 200) {
                log.error("下载失败，状态码：{}, filePath: {}", fileResponse.status(), s.getFilePath());
                return null;
            }

            try (InputStream inputStream = fileResponse.body().asInputStream()) {
                byte[] data = StreamUtils.copyToByteArray(inputStream);

                return new JSONObject()
                        .fluentPut("workNum", s.getWorkNum())
                        .fluentPut("fileByte", data);
            }
        } catch (Exception e) {
            log.error("下载异常，filePath: {}", s.getFilePath(), e);
            return null;
        }
    }

}