package com.simuwang.manage.api.email;

import com.simuwang.base.common.support.MybatisPage;
import com.simuwang.base.common.util.EncodeUtil;
import com.simuwang.base.pojo.dto.query.EmailFileQuery;
import com.simuwang.base.pojo.dto.query.EmailParseQuery;
import com.simuwang.base.pojo.vo.*;
import com.simuwang.daq.service.EmailParseApiService;
import com.simuwang.manage.service.ParseEmailService;
import com.smppw.common.pojo.ResultVo;
import com.smppw.common.pojo.enums.TimeRange;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 解析详情管理
 * Author:   chenjianhua
 * Date:     2024/9/10 11:21
 * Description: ${DESCRIPTION}
 */
@RestController
@RequestMapping("/v1/parse")
public class ParseEmailController{
    private static final Logger logger = LoggerFactory.getLogger(ParseEmailController.class);

    @Autowired
    private ParseEmailService parseEmailService;

    @Autowired
    private EmailParseApiService emailParseApiService;
    /**
     * 保存邮件类型识别配置
     * @param emailTypeRuleVO
     * @return
     */
    @PostMapping("/save-email-type")
    public boolean saveEmailType(@RequestBody EmailTypeRuleVO emailTypeRuleVO){
        parseEmailService.saveEmailType(emailTypeRuleVO);
        return true;
    }

    /**
     * 查询邮件类型识别配置
     * @param
     * @return
     */
    @GetMapping("/search-email-type")
    public ResultVo searchEmailType(){
        EmailTypeRuleVO emailTypeRuleVO = parseEmailService.searchEmailType();
        return ResultVo.ok(emailTypeRuleVO);
    }

    /**
     * 邮箱配置页面展示查询
     * @param emailParseQuery
     * @return
     */
    @GetMapping("/search-email-list")
    public MybatisPage<EmailParseInfoVO> searchEmailList(EmailParseQuery emailParseQuery){
        MybatisPage<EmailParseInfoVO> result = parseEmailService.searchEmailList(emailParseQuery);
        return result;
    }

    /**
     * 详情查询
     * @param emailFileQuery
     * @return
     */
    @GetMapping("/detail")
    public MybatisPage<EmailParseDetailVO> searchEmailDetail(EmailFileQuery emailFileQuery){
        MybatisPage<EmailParseDetailVO> result = parseEmailService.searchEmailDetailById(emailFileQuery);
        return result;
    }

    /**
     * 解析邮件数据统计
     * @param timeRange Last1Week-近一周,Last1Month-近一个月，Last3Months-近三月，LastHalfYear-近半年，Last1Year-近一年,FromSetup-全部，Custom-自定义
     * @return
     */
    @GetMapping("/search-email-count")
    public ResultVo searchEmailCount(@RequestParam("timeRange") TimeRange timeRange,@RequestParam(value = "startDate",required = false)String startDate,@RequestParam(value = "endDate",required = false)String endDate){
        Map<String,Integer> result = parseEmailService.searchEmailCount(timeRange,startDate,endDate);
        return ResultVo.ok(result);
    }

    /**
     * 根据fileId下载邮件附件
     * @param fileId
     * @return
     */
    @PostMapping("/download-email-file")
    public void downloadEmailFile(@RequestParam("fileId") Integer fileId, HttpServletResponse response, HttpServletRequest request){
        try {
            EmailFileInfoVO emailFileInfoVO = parseEmailService.getEmailFileById(fileId);
            FileInputStream fileInputStream = new FileInputStream(emailFileInfoVO.getFilePath());
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + EncodeUtil.encodeUTF8(emailFileInfoVO.getFileName()));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            while(fileInputStream.read(b) > 0){
                outputStream.write(b);
            }
            fileInputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 根据邮件ID重新解析
     * @param idListVO
     * @return
     */
    @PostMapping("/reparse")
    public ResultVo reparse(@RequestBody IdListVO idListVO){
        for(Integer emailid : idListVO.getIdList()){
            emailParseApiService.reparseEmail(emailid);
        }
        return ResultVo.ok(true);
    }
}
