package cn.com.ctop.job.bytedance.handler;

import cn.com.ctop.common.module.entity.UReportSubscriber;
import cn.com.ctop.common.module.message.handle.impl.EmailSendMsgHandle;
import cn.com.ctop.common.module.service.ICtopCorpWexinUserService;
import cn.com.ctop.common.module.service.IUReportExportService;
import cn.com.ctop.common.module.service.IUReportService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

@Component
public class SendDailyUReportJob {

    @Autowired
    IUReportExportService uReportExportService;
    @Autowired
    EmailSendMsgHandle emailSendMsgHandle;
    @Autowired
    IUReportService uReportService;
    @Autowired
    ICtopCorpWexinUserService corpUserService;

    /**
     * 检查任务执行结果
     */
    @XxlJob("sendDailyUReportJob")
    public void execute() throws Exception {
        uReportService.uReportList().forEach(uReport->{
             List<UReportSubscriber> uReportSubscriber = uReportService.getUReportSubscriberByFileId(uReport.getString("id"));
             if(!uReportSubscriber.isEmpty()){
                 String title=uReport.getString("name").replace(".ureport.xml","");
                 String content="您订阅的日报在附件中请注意查收》》》";
                 //下载文件到本地
                 uReportExportService.exportExcel(uReport.getString("name"));
                 uReportSubscriber.forEach(sender->{
                     String receiver=corpUserService.getEmailByUserId(sender.getSender());
                     emailSendMsgHandle.SendAttachment(receiver,title,content,
                             new File("/data/file/report"+ File.separator + "uReport"+File.separator+uReport.getString("name")
                                     .replace("ureport.xml","")+"xlsx"));
                 });
             }
        });
        //发完全部订阅，删除文件
        File file =new File("/data/file/report"+ File.separator + "uReport");
        File[] files=file.listFiles();
        if(files!=null&&files.length>0){
            for (File f: files){
                f.delete();
            }
        }
    }
}
