package com.example.system.service.impl;

import cn.hutool.core.io.FileUtil;
import com.example.system.common.AiPost;
import com.example.system.common.Chart;
import com.example.system.common.R;
import com.example.system.mapper.ChartMapper;
import com.example.system.pojo.GenChartByAiRequest;
import com.example.system.pojo.BiResponse;
import com.example.system.service.ChartService;
import com.example.system.utils.ExcelUtils;
import com.example.system.utils.StringUtils;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class ChartServiceImpl implements ChartService {

    @Autowired
    private AiPost aiPost;

    @Autowired
    private ChartMapper chartMapper;

    @Override
    public R<BiResponse> genChartByAi(MultipartFile multipartFile, GenChartByAiRequest genChartByAiRequest) {
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        System.out.println(name);
        System.out.println(goal);
        System.out.println(chartType);


        // 文件校验
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        final long ONE_MB = 1024 * 1024L;
        if (size > ONE_MB) {
            return R.error("文件超过1MB，请上传小于1MB的文件");
        }

        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList = Arrays.asList("xlsx", "xls");
        if (!validFileSuffixList.contains(suffix)) {
            return R.error("仅支持xlsx、xls格式的Excel文件");
        }

        // 构建AI输入提示
        final String prompt = "你是一个数据分析师和前端开发专家，按照以下固定格式分析数据：\n" +
                "分析需求：\n{数据分析的需求或者目标}\n" +
                "原始数据：\n{csv格式的原始数据，用,作为分隔符}\n" +
                "请按以下格式生成内容（不要输出任何多余的开头、结尾、注释）\n" +
                "【【【【【\n" +
                "{前端 Echarts V5 的 option 配置对象js代码，合理地将数据进行可视化}\n" +
                "【【【【【\n" +
                "{明确的数据分析结论，越详细越好}\n";

        StringBuilder userInput = new StringBuilder();
        userInput.append(prompt);
        userInput.append("你是一个数据分析师，接下来我会给你分析目标和原始数据，请告诉我分析结论。").append("\n");

        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += "，请使用" + chartType;
        }

        userInput.append("分析目标：").append(userGoal).append("\n");
        userInput.append("分析需求：").append(userGoal).append("\n");
        userInput.append("原始数据: ").append("\n");

        // 将Excel转为CSV
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        userInput.append(csvData).append("\n");

        String result;
        try {
            // 调用AI服务获取分析结果
            result = aiPost.sendMessageAndGetResponse(userInput.toString(), 1024);
            System.out.println("AI返回内容：\n" + result);
        } catch (Exception e) {
            return R.error("AI分析失败：" + e.getMessage());
        }

        // 解析AI返回内容
        String[] splits = result.split("【【【【【");
        if (splits.length < 3) {
            return R.error("AI生成格式错误，请确认返回内容完整");
        }

        // 提取 option JSON
        String optionBlock = splits[1].trim();
        Pattern jsonPattern = Pattern.compile("\\{.*\\}", Pattern.DOTALL);
        Matcher jsonMatcher = jsonPattern.matcher(optionBlock);
        String genChart;

        if (jsonMatcher.find()) {
            genChart = jsonMatcher.group(0).trim();
        } else {
            return R.error("AI返回的图表配置无法识别");
        }

        // 提取分析结论
        String genResult = splits[2].trim();

        // 解析 Echarts 配置
        Gson gson = new Gson();
        Object objectChart;
        try {
            objectChart = gson.fromJson(genChart, Object.class);
        } catch (Exception e) {
            return R.error("图表配置JSON格式错误：" + e.getMessage());
        }

        // 保存图表数据
        Chart chart = new Chart();
        chart.setId(UUID.randomUUID().toString().replace("-", ""));
        chart.setName(StringUtils.isBlank(name) ? "未命名图表" : name);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setAdminId(genChartByAiRequest.getAdminId());
        chart.setCreateTime(System.currentTimeMillis());
        chart.setUpdateTime(System.currentTimeMillis());

        // 保存到数据库
        try {
            saveChart(chart);
        } catch (Exception e) {
            return R.error("图表保存失败：" + e.getMessage());
        }

        // 构造响应
        BiResponse biResponse = new BiResponse();
        biResponse.setGenChart(genChart);
        biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());

        R<BiResponse> resultData = new R<>();
        resultData.add("genChart", objectChart);
        resultData.setData(biResponse);
        resultData.setMsg("图表生成成功");
        resultData.setStatus(200);

        return resultData;
    }

    @Override
    public Chart getChartById(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        return chartMapper.findById(id);
    }

    @Override
    public boolean saveChart(Chart chart) {
        if (chart == null) {
            return false;
        }

        // 如果ID为空，生成UUID
        if (StringUtils.isBlank(chart.getId())) {
            chart.setId(UUID.randomUUID().toString().replace("-", ""));
        }

        // 设置创建和更新时间
        long currentTime = System.currentTimeMillis();
        if (chart.getCreateTime() == null) {
            chart.setCreateTime(currentTime);
        }
        chart.setUpdateTime(currentTime);

        try {
            int result = chartMapper.saveChart(chart);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateChart(Chart chart) {
        if (chart == null || StringUtils.isBlank(chart.getId())) {
            return false;
        }

        // 设置更新时间
        chart.setUpdateTime(System.currentTimeMillis());

        try {
            int result = chartMapper.updateChart(chart);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteChart(String id) {
        if (StringUtils.isBlank(id)) {
            return false;
        }

        try {
            int result = chartMapper.deleteById(id);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}