package com.example.myapplication.Tool;

import android.content.Context;
import android.util.Log;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ReportGenerator {


    private static final String TAG = "ReportGenerator";
    private static final String TEMPLATE_DIR = "templates";
    private final Context context;

    public ReportGenerator(Context context) {
        this.context = context;
        initPython();
        prepareTemplates();
    }

    private void initPython() {
        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(context));
        }
    }

    private void prepareTemplates() {
        File templateDir = new File(context.getFilesDir(), TEMPLATE_DIR);
        if (!templateDir.exists() || isTemplateUpdateNeeded(templateDir)) {
            copyAssetsTemplates(templateDir);
        }
    }

    private boolean isTemplateUpdateNeeded(File templateDir) {
        return templateDir.listFiles() == null || templateDir.listFiles().length == 0;
    }

    private void copyAssetsTemplates(File targetDir) {
        try {
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }

            String[] files = context.getAssets().list(TEMPLATE_DIR);
            if (files != null) {
                for (String filename : files) {
                    File outFile = new File(targetDir, filename);
                    try (InputStream in = context.getAssets().open(TEMPLATE_DIR + "/" + filename);
                         OutputStream out = new FileOutputStream(outFile)) {
                        byte[] buffer = new byte[1024];
                        int read;
                        while ((read = in.read(buffer)) != -1) {
                            out.write(buffer, 0, read);
                        }
                    }
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Failed to copy templates", e);
        }
    }

    public String generateReport() {
        try {
            // 创建模拟数据
            JSONObject jsonData1 = createMockJsonData1();
            JSONObject jsonData2 = createMockJsonData2();

            Python py = Python.getInstance();

          py.getModule("report_generate_server.Generate_Report")
                    .callAttr("main",
                            jsonData1.toString(),
                            jsonData2.toString());
            return jsonData2.getString("shengcheng_dir");
        } catch (Exception e) {
            Log.e(TAG, "Report generation failed", e);
            return "Error: " + e.toString();
        }
    }

    private JSONObject createMockJsonData1() throws JSONException {
        JSONObject jsonData1 = new JSONObject();

        // 项目基本信息
        JSONObject jizuData = new JSONObject();
        jizuData.put("turbineName", "风力发电机001");

        JSONObject projectData = new JSONObject();
        projectData.put("fengmian_dir", "storage/emulated/0/DCIM/Camera/IMG_20250721_173921.jpg");
        projectData.put("farmName", "华北风电场");
        projectData.put("inspectionUnit", "华北检测公司");
        projectData.put("inspectionContact", "李检测员");
        projectData.put("inspectionPhone", "13800138000");
        projectData.put("farmAddress", "河北省张家口市");
        projectData.put("client", "国家电网");
        projectData.put("clientContact", "王经理");
        projectData.put("clientPhone", "13900139000");
        projectData.put("scale", "50MW");
        projectData.put("turbineModel", "GW-1500");
        projectData.put("projectName", "华北风电场年度检测");
        projectData.put("startDate", "2025-07-01");
        projectData.put("endDate", "2025-07-31");

        JSONObject shigongData = new JSONObject();
        shigongData.put("startTime", "2025-07-21 08:00");
        shigongData.put("endTime", "2025-07-21 17:00");
        shigongData.put("weatherCode", "晴");
        shigongData.put("windSpeed", "5.2m/s");
        shigongData.put("imageCount", "120");
        shigongData.put("temperature", "28℃");

        jsonData1.put("jizu_data", jizuData);
        jsonData1.put("project_data", projectData);
        jsonData1.put("shigong_data", shigongData);
        jsonData1.put("partManufacturer", "金风科技");

        // Y叶片数据
        String imagePath = "storage/emulated/0/DCIM/Camera/IMG_20250721_173921.jpg";

        JSONObject y1 = new JSONObject();
        y1.put("Code", "1");
        JSONObject y1List = new JSONObject();
        y1List.put("叶片前缘", imagePath);
        y1List.put("叶片后缘", imagePath);
        y1List.put("叶片表面", imagePath);
        y1.put("list_dict", y1List);

        JSONObject y2 = new JSONObject();
        y2.put("Code", "2");
        JSONObject y2List = new JSONObject();
        y2List.put("叶片前缘", imagePath);
        y2List.put("叶片后缘", imagePath);
        y2List.put("叶片表面", imagePath);
        y2.put("list_dict", y2List);

        JSONObject y3 = new JSONObject();
        y3.put("Code", "3");
        JSONObject y3List = new JSONObject();
        y3List.put("叶片前缘", imagePath);
        y3List.put("叶片后缘", imagePath);
        y3List.put("叶片表面", imagePath);
        y3.put("list_dict", y3List);

        jsonData1.put("Y1", y1);
        jsonData1.put("Y2", y2);
        jsonData1.put("Y3", y3);

        return jsonData1;
    }

    private JSONObject createMockJsonData2() throws JSONException {
        JSONObject jsonData2 = new JSONObject();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault());
        String templatePath = new File(context.getFilesDir(), TEMPLATE_DIR).getAbsolutePath();
        String outputPath = context.getExternalFilesDir(null).getAbsolutePath();
        jsonData2.put("shengcheng_dir", outputPath);
        jsonData2.put("muban_dir", templatePath);
        jsonData2.put("if_waibu", false);
        jsonData2.put("if_neibu", true);
        jsonData2.put("if_fanglei", true);
        jsonData2.put("userName", "admin");
        jsonData2.put("baogaoCheck", "未审核");
        jsonData2.put("key_words", "缺,损,裂,脱,污");
        jsonData2.put("shigong_fangan", "标准检测方案");
        jsonData2.put("jiancha_renyuan", "张三,李四");
        jsonData2.put("baogao_zongjie", "本次检测共发现3处缺陷，需要及时处理");
        jsonData2.put("total_pic_num", "120");

        return jsonData2;
    }
}