package com.platform.service.impl;

import com.platform.service.WechatService;
import com.platform.utils.FileUtils;
import com.platform.utils.WxOpUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.File;

@Service
public class WechatServiceImpl implements WechatService {
    @Override
    public String generateMicroAppCode(String scene, String page) {
        String tempFolder = "/statics/tmp/images/";
        String path = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest().getServletContext().getRealPath("") + tempFolder;
        // 删除前一天的图片
        File file = new File(path);
        long timeMillis = System.currentTimeMillis();
        if (file.exists()) {
            String[] list = file.list((dir, name) -> {
                String fileName = name.split("\\.")[0];
                return fileName.matches("\\d+") && Long.parseLong(fileName) < timeMillis - 3600 * 24 *1000;
            });
            for (String fileName : list) {
                FileUtils.deleteFile(path.concat(fileName));
            }
        }
        String fileName = timeMillis + ".png";
        WxOpUtils.generateMicroAppCode(scene, page, path, fileName);
        return tempFolder.concat(fileName);
    }
}
