<template>
  <a-layout class="intelligent_analysis">
    <a-row :gutter="24">
      <a-col :span="12">
        <a-card title="智能分析">
          <a-form
            ref="form"
            :model="form"
            :rules="rules"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
          >
            <a-form-item label="分析目标" name="goal">
              <a-textarea
                v-model:value="form.goal"
                :rows="4"
                placeholder="请输入分析目标，例如：分析学生成绩分布情况、分析不同学院参赛人数占比等"
              />
            </a-form-item>
            <a-form-item label="图表名称" name="name">
              <a-input v-model:value="form.name" placeholder="请输入图表名称" />
            </a-form-item>
            <a-form-item label="图表类型" name="chartType">
              <a-select
                v-model:value="form.chartType"
                placeholder="请选择图表类型"
              >
                <a-select-option value="折线图">折线图</a-select-option>
                <a-select-option value="柱状图">柱状图</a-select-option>
                <a-select-option value="堆叠图">堆叠图</a-select-option>
                <a-select-option value="饼图">饼图</a-select-option>
                <a-select-option value="雷达图">雷达图</a-select-option>
              </a-select>
            </a-form-item>
            <!-- 修改上传组件部分 -->
            <a-form-item
              label="原始数据"
              name="file"
              :rules="[{ required: true, message: '请上传Excel文件' }]"
            >
              <a-upload
                :file-list="fileList"
                :before-upload="beforeUpload"
                @remove="handleRemove"
                :multiple="false"
                accept=".xls,.xlsx"
                :maxCount="1"
                list-type="text"
              >
                <a-button type="primary" :disabled="fileList.length >= 1">
                  <upload-outlined /> 上传Excel文件
                </a-button>
                <div class="ant-upload-hint">
                  只能上传xls/xlsx文件，且不超过1MB
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 18, offset: 6 }">
              <a-button
                type="primary"
                @click="onSubmit"
                :loading="submitting"
                :disabled="submitting || fileList.length === 0"
              >
                提交
              </a-button>
              <a-button
                style="margin-left: 10px"
                @click="resetForm"
                :disabled="submitting"
              >
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card title="分析结论" :loading="submitting">
          <div v-if="chart.genResult" style="white-space: pre-wrap">
            {{ chart.genResult }}
          </div>
          <div v-else>
            <div v-if="!submitting">请先在左侧进行提交</div>
          </div>
        </a-card>
        <a-divider />
        <a-card title="可视化图表" :loading="submitting">
          <div v-if="chart.genChart">
            <div
              ref="chartContainer"
              style="width: 100%; height: 50vh"
              class="chartContainer"
            ></div>
          </div>
          <div v-else>
            <div v-if="!submitting">请先在左侧进行提交</div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 示例抽屉 -->
    <a-drawer
      title="分析目标示例"
      :visible="showExamplesDrawer"
      @close="showExamplesDrawer = false"
      placement="right"
      width="400"
    >
      <a-list item-layout="vertical">
        <a-list-item
          v-for="(example, index) in examples"
          :key="index"
          @click="useExample(example)"
        >
          <a-card hoverable>{{ example }}</a-card>
        </a-list-item>
      </a-list>
    </a-drawer>
  </a-layout>
</template>

<script>
import { UploadOutlined } from "@ant-design/icons-vue";
import { AnyncChart } from "@/api/index";
import * as echarts from "echarts";

export default {
  components: {
    UploadOutlined,
  },
  data() {
    return {
      form: {
        goal: "",
        name: "",
        chartType: "",
        adminId: undefined,
      },
      file: null,
      rules: {
        goal: [
          { required: true, message: "请输入分析目标", trigger: "blur" },
          {
            min: 5,
            max: 100,
            message: "长度在 5 到 100 个字符",
            trigger: "blur",
          },
        ],
        name: [{ required: true, message: "请输入图表名称", trigger: "blur" }],
        chartType: [
          { required: true, message: "请选择图表类型", trigger: "change" },
        ],
      },
      chart: {
        genChart: "",
        genResult: "",
        chartId: "",
      },
      resultChart: {},
      fileList: [],
      submitting: false,
      examples: [
        "分析学生成绩分布情况",
        "分析不同学院参赛人数占比",
        "分析近五年竞赛获奖数量趋势",
        "分析男女生参与各类竞赛的比例",
        "分析各专业学生参与度对比",
      ],
      chartTypes: [
        { label: "折线图", value: "折线图" },
        { label: "柱状图", value: "柱状图" },
        { label: "饼图", value: "饼图" },
        { label: "雷达图", value: "雷达图" },
      ],
      showExamplesDrawer: false,
    };
  },
  computed: {
    randomExample() {
      if (this.examples.length === 0) return "请输入分析目标";
      const randomIndex = Math.floor(Math.random() * this.examples.length);
      return this.examples[randomIndex];
    },
  },
  created() {
    this.fetchExamples();
    this.fetchChartTypes();
    // 设置默认管理员ID
    this.form.adminId = window.sessionStorage.getItem("adminId") || "1";
  },
  methods: {
    // 获取示例目标
    fetchExamples() {
      // 如果有API可以获取示例，在这里调用
      console.log("获取示例目标");
    },

    // 获取图表类型
    fetchChartTypes() {
      // 如果有API可以获取图表类型，在这里调用
      console.log("获取图表类型");
    },

    // 使用示例
    useExample(example) {
      this.form.goal = example;
      this.showExamplesDrawer = false;
    },

    // 上传前检查
    beforeUpload(file) {
      console.log("上传文件:", file);
      const acceptTypeList = [
        "application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      ];
      const acceptSize = 1 * 1024 * 1024;

      // 检查文件类型，包括文件扩展名
      const fileName = file.name || "";
      const fileExt = fileName
        .substring(fileName.lastIndexOf("."))
        .toLowerCase();
      const isValidExt = [".xls", ".xlsx"].includes(fileExt);

      if (acceptTypeList.indexOf(file.type) === -1 && !isValidExt) {
        this.$message.error("只允许xls或者xlsx格式的文件上传");
        return false;
      }

      if (file.size > acceptSize) {
        this.$message.error("只允许文件大小在1MB之内的Excel文件");
        return false;
      }

      // 保存文件对象
      this.file = file;

      // 更新文件列表，确保文件显示在上传组件中
      this.fileList = [
        {
          uid: file.uid || "-1",
          name: file.name,
          status: "done",
          size: file.size,
          type: file.type,
          url: URL.createObjectURL(file),
        },
      ];

      // 返回false阻止自动上传
      return false;
    },

    // 移除文件
    handleRemove() {
      this.fileList = [];
      this.file = null;
    },

    // 提交表单
    async onSubmit() {
      console.log("提交按钮点击");

      try {
        // // 表单验证
        // await this.$refs.form.validate();

        // 检查文件是否上传
        if (!this.file) {
          this.$message.error("请上传Excel文件");
          return;
        }

        // 防止重复提交
        if (this.submitting) {
          return;
        }

        this.submitting = true;

        // 构建表单数据
        const formData = new FormData();
        formData.append("file", this.file);
        formData.append("name", this.form.name);
        formData.append("goal", this.form.goal);
        formData.append("chartType", this.form.chartType);
        formData.append("adminId", this.form.adminId);

        this.$message.info("接口调用花费时间在30秒左右，AI模型暂时不稳定");

        try {
          // 调用API
          const res = await AnyncChart(formData);

          console.log("API返回结果:", res);

          if (res.code !== 200 && res.status !== 200) {
            throw new Error(res.msg || "分析失败");
          }

          // 处理返回数据
          const responseData = res.data?.data || res.data || {};
          const additionalData = res.data?.additionalData || {};

          this.chart.genResult = responseData.genResult;

          // 处理图表数据，支持字符串或对象格式
          if (typeof responseData.genChart === "string") {
            try {
              this.chart.genChart = responseData.genChart;
              try {
                this.resultChart = JSON.parse(responseData.genChart);
              } catch (e) {
                this.resultChart = eval('(' + responseData.genChart + ')');
              }
            } catch (e) {
              console.error("图表数据解析错误:", e);
              this.$message.error("图表数据格式错误");
              if (additionalData.genChart) {
                this.resultChart = additionalData.genChart;
              }
            }
          } else if (responseData.genChart) {
            this.chart.genChart = JSON.stringify(responseData.genChart);
            this.resultChart = responseData.genChart;
          } else if (additionalData.genChart) {
            this.chart.genChart = JSON.stringify(additionalData.genChart);
            this.resultChart = additionalData.genChart;
          } else {
            this.resultChart = null;
          }

          // 渲染图表
          this.createChart();
          this.$message.success("分析完成");
        } catch (error) {
          console.error("API调用错误:", error);
          this.$message.error(error.message || "分析失败");
        } finally {
          this.submitting = false;
        }
      } catch (error) {
        console.log("表单验证失败:", error);
        this.$message.error("请完成表单必填项");
      }
    },

    // 渲染图表
    createChart() {
      if (!this.resultChart) {
        this.$message.error("图表数据为空");
        return;
      }

      this.$nextTick(() => {
        if (!this.$refs.chartContainer) {
          console.error("图表容器不存在");
          return;
        }

        // 销毁旧图表（如果存在）
        if (this.chart.instance) {
          this.chart.instance.dispose();
        }

        // 初始化图表
        const chartDom = this.$refs.chartContainer;
        const myChart = echarts.init(chartDom);

        try {
          // 设置图表配置
          myChart.setOption(this.resultChart);

          // 保存图表实例
          this.chart.instance = myChart;

          // 窗口大小变化时重绘图表
          window.addEventListener("resize", () => {
            myChart.resize();
          });
        } catch (e) {
          console.error("图表渲染错误:", e);
          this.$message.error("图表渲染失败");
        }
      });
    },

    // 重置表单
    resetForm() {
      this.$refs.form.resetFields();
      this.fileList = [];
      this.file = null;
      this.chart = {
        genChart: "",
        genResult: "",
        chartId: "",
        instance: null,
      };
      this.resultChart = {};
    },
  },
  // 组件销毁时清理资源
  beforeUnmount() {
    if (this.chart.instance) {
      this.chart.instance.dispose();
    }
  },
};
</script>

<style scoped>
.intelligent_analysis {
  padding: 24px;
  background-color: #fff;
}

.chartContainer {
  margin-top: 16px;
  height: 50vh;
  width: 100%;
}

.ant-upload-hint {
  margin-top: 8px;
  color: rgba(0, 0, 0, 0.45);
}

.example-item {
  margin-bottom: 16px;
  cursor: pointer;
}

.example-item:hover {
  opacity: 0.8;
}

.ant-btn {
  margin-right: 8px;
}
</style>
