package com.ruoyi.web.util;

import com.google.common.collect.Maps;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MentalHealthExporter {

    public static void export(HttpServletResponse response, Long examineeId, Map<String, Integer> categoryScoreMap) {
        if (response == null) {
            response.setStatus(404);
            return;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String realFileName = examineeId + "_" + sdf.format(new Date()) + ".docx";

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            String text = IOUtils.toString(MentalHealthExporter.class.getResourceAsStream("/templates/mht_report.xml"), "utf8");
            Map<String, String> valueMap = Maps.newHashMap();
            String newText = replaceChooseValue(text, categoryScoreMap, valueMap);
            String finalText = replaceVarValue(newText, valueMap);
            // OutputStream os = new FileOutputStream("D:\\data\\wish_output.xls");
            PrintWriter pw = new PrintWriter(response.getOutputStream());
            pw.write(finalText);
            pw.flush();
        } catch (UnsupportedEncodingException e) {
            response.setStatus(404);
        } catch (IOException e) {
            response.setStatus(404);
        }
        return;
    }

    public static void test(Long examineeId, Map<String, Integer> categoryScoreMap) throws IOException {
        String text = IOUtils.toString(MentalHealthExporter.class.getResourceAsStream("/templates/mht_report.xml"), "utf8");
        Map<String, String> valueMap = Maps.newHashMap();
        String newText = replaceChooseValue(text, categoryScoreMap, valueMap);
        return;
    }


    private static String replaceChooseValue(String text, Map<String, Integer> categoryScoreMap, Map<String, String> valueMap) {
        StringBuffer sb = new StringBuffer();
        boolean needXml = true;
        boolean needPart = true;
        String processingTag = "";
        String[] partList = text.split("<!-- | -->");
        for (String s : partList) {
            if (s.contains("<")) { // xml
                if (needXml && needPart) {
                    sb.append(s);
                }
                continue;
            }
            String[] datas = s.split("=");
            if (datas.length == 1) {
                if (datas[0].equals(processingTag)) {
                    needXml = true;
                } else {
                    needXml = !"效度量表".equals(datas[0]);
                    processingTag = datas[0];
                }
                needPart = true;
                continue;
            }
            Integer score = categoryScoreMap.get(datas[0]);
            if (null == score) {
                needPart = false;
                continue;
            }
            String[] scores = datas[1].split("-", -1);
            needPart = (StringUtils.isBlank(scores[0]) || NumberUtils.toInt(scores[0]) <= score) && (StringUtils.isBlank(scores[1]) || score <= NumberUtils.toInt(scores[1]));
            if (needPart) {
                valueMap.put(datas[0], StringUtils.isBlank(scores[0]) ? "006400" : (StringUtils.isBlank(scores[1]) ? "FF0000" : "000000"));
            }
            continue;
        }
        return sb.toString();
    }

    private static String replaceVarValue(String text, Map<String, String> valueMap) {
        String pattern = "(\\$\\{(.+?)\\})";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(text);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String key = m.group(1);
            String vk = key.substring(2, key.length() - 1);
            String value = valueMap.get(vk);
            m.appendReplacement(sb, null == value ? "" : value);
        }
        m.appendTail(sb);
        return sb.toString();
    }
}
