<!--
 * @Author: your name
 * @Date: 2024-05-27 09:25:45
 * @LastEditTime: 2024-08-05 09:52:56
 * @LastEditors: bogon
 * @Description: In User Settings Edit
 * @FilePath: /performance-test/src/views/performance/assetssDetail.vue
-->
<template>
  <div class="global-variable" v-loading="loading">
    <el-row type="flex" justify="space-between">
      <el-col :span="8">
        <el-button
          type="text"
          style="font-size: 20px"
          icon="el-icon-arrow-left"
          @click="() => $router.push('/home/performance/assetssMag')"
        >
          返回
        </el-button>
      </el-col>
      <el-col :span="8">
        <h2 style="text-align: center">分析历史记录总览</h2>
      </el-col>
      <el-col :span="8">
        <div style="text-align: end; font-size: 16px">
          分析时间：{{
            generalFiles.length > 0 ? generalFiles[0].createTime : "/"
          }}
        </div>
      </el-col>
    </el-row>
    <el-card class="box-card analysisType">
      <el-form
        :model="formInfo"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        inline
        class="demo-ruleForm"
      >
        <el-row type="flex" justify="space-between">
          <el-col :span="8">
            <el-form-item label="分析类型" prop="analysisTypeCode">
              <el-select v-model="formInfo.analysisTypeCode" size="small">
                <el-option
                  v-for="item in analysisTypeList"
                  :key="item.analysisTypeCode"
                  :label="item.analysisTypeName"
                  :value="item.analysisTypeCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机组名称" prop="fieldEngineCode">
              <el-select v-model="formInfo.fieldEngineCode" size="small">
                <el-option
                  v-for="item in windEngineGroupList"
                  :key="item.engineCode"
                  :label="item.engineName"
                  :value="item.engineCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              class="searchFrom"
              style="display: flex; justify-content: end"
            >
              <el-button type="primary" @click="onSubmit" size="small"
                >查询</el-button
              >
              <el-button @click="reset('ruleForm')" size="small"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-empty :image-size="200" v-if="flage"></el-empty>
    <div v-else>
      <el-table
        v-if="
          this.formInfo.analysisTypeCode === 'yaw_error' &&
          this.csvData.length > 0
        "
        :data="csvData"
        border
        style="width: 100%"
        align="center"
      >
        <el-table-column prop="engine_name" label="风机名称"> </el-table-column>
        <el-table-column prop="yaw_error1" label="误差值"> </el-table-column>
      </el-table>
      <div v-else>
        <el-card class="box-card analysisType" v-if="generalFiles.length > 0">
        <div slot="header" class="clearfix">
          <span style="font-weight: 700; font-size: 16px">
            分析总图{{ fileCheckResult1 }}
          </span>
        </div>
        <el-row class="assetssConent">
          <!-- :span="getSpan(index, 'generalFiles')" -->
          <!-- v-loading="
              loadings[index + generalFiles.length] &&
              getFileType(file.fileAddr) === 'html'
            " -->
          <el-col
            v-for="(file, index) in generalFiles"
            :key="index"
            :span="24"
            class="col_content"
            :style="{
              display: getFileType(file.fileAddr) === 'html' ? 'block' : 'none',
            }"
          >
            <iframe
              v-if="getFileType(file.fileAddr) === 'html'"
              :src="file.fileAddr"
              :ref="'iframe' + index"
              frameborder="0"
              @load="iframeLoad(index + generalFiles.length)"
              width="100%"
              height="100%"
            ></iframe>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="box-card analysisType" v-if="diagramRelations.length > 0">
        <div slot="header" class="clearfix">
          <span style="font-weight: 700; font-size: 16px">
            分析分图 {{ fileCheckResult1 }}
          </span>
        </div>
        <el-row class="assetssConent">
          <el-col
            v-for="(file, index) in diagramRelations"
            :key="index"
            :span="24"
            :style="{
              display: getFileType(file.fileAddr) === 'html' ? 'block' : 'none',
            }"
            class="col_content"
          >
            <iframe
              v-if="getFileType(file.fileAddr) === 'html'"
              :src="file.fileAddr"
              :ref="'iframe' + index + diagramRelations.length"
              frameborder="0"
              width="100%"
              height="100%"
              @load="iframeLoad(index + diagramRelations.length)"
            ></iframe>
          </el-col>
        </el-row>
      </el-card>
      </div>
      <el-card
        class="box-card"
        v-for="o in commentDescriptionVos"
        :key="o.commentTypeName"
      >
        <div slot="header" class="clearfix">
          <span style="font-weight: 700; font-size: 16px">{{
            o.commentTypeName
          }}</span>
        </div>
        <div class="text item">
          <div v-html="o.comment"></div>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import {
  analysisDetail,
  queryAnalysisedType,
  queryAnalysisedEngine,
  queryAnalysisTypeConfig,
} from "@/api/performance";
import Papa from "papaparse";
import axios from "axios";

export default {
  data() {
    return {
      loadings: [],
      loading: false,
      fileCheckResult: null,
      fileCheckResult1: null,
      analysisTypeList: [],
      windEngineGroupList: [],
      generalFiles: [],
      diagramRelations: [],
      commentDescriptionVos: [],
      formInfo: {
        fieldEngineCode: null,
        analysisTypeCode: null,
      },
      csvData: [], // 解析后的数据
      csvHeaders: [], // CSV 表头
      rules: {},
      flage: false,
    };
  },
  created() {
    //获取分析 分析类型、机组编号 列表
    this.getWindCodeList();
  },
  mounted() {
    // this.initializeLoading();
    this.chartsTypeConfig();
  },
  methods: {
    async chartsTypeConfig() {
      const result = await queryAnalysisTypeConfig();
      console.log(result.data, "result");
    },
    iframeLoad(index) {
      this.$set(this.loadings, index, false);
    },
    initializeLoading() {
      // 计算总的文件数量，包括分析总图和分析分图
      const totalFiles =
        this.generalFiles.length + this.diagramRelations.length;
      // 初始化 loadings 数组，全部设置为 true，表示加载状态
      this.loadings = new Array(totalFiles).fill(true);
    },
    // 查询
    onSubmit() {
      this.getDetailInfo();
    },
    // 重置
    reset(formName) {
      this.$refs[formName].resetFields();

      this.getWindCodeList();
    },
    async getDetailInfo() {
      const formData = new FormData();
      formData.append("batchCode", this.$route.query.batchCode);
      formData.append("analysisTypeCode", this.formInfo.analysisTypeCode);
      formData.append("fieldEngineCode", this.formInfo.fieldEngineCode);
      this.loading = true;
      //获取详情信息
      try {
        const response = await analysisDetail(formData);
        if (response.data.length === 0 || response.data === null) {
          this.flage = true;
        } else {
          this.flage = false;
        }
        this.generalFiles = [];
        this.generalFiles =
          (response.data &&
            response.data.length > 0 &&
            response.data[0].generalFiles) ||
          [];
        this.diagramRelations = [];
        this.diagramRelations =
          (response.data &&
            response.data.length > 0 &&
            response.data[0].diagramRelations) ||
          [];
        console.log(this.diagramRelations, "this.diagramRelations");
        this.commentDescriptionVos =
          (response.data &&
            response.data.length > 0 &&
            response.data[0].commentDescriptionVos) ||
          [];
          if (this.formInfo.analysisTypeCode === "yaw_error") {
          this.getCsvData(response.data[0].generalFiles[0].fileAddr);
        }
        this.initializeLoading();
        this.loading = false;
      } catch (error) {
        console.error(error);
        this.loading = false;
      }
    },
    getCsvData(url) {
      // 使用 axios 获取 CSV 文件
      axios
        .get(url, { responseType: "blob" }) // 确保数据以 blob 格式返回
        .then((response) => {
          const reader = new FileReader();
          reader.onload = (e) => {
            const csvText = e.target.result;
            Papa.parse(csvText, {
              header: true, // 使用 CSV 第一行作为键
              complete: (result) => {
                this.csvHeaders = Object.keys(result.data[0]);
                this.csvData = result.data.filter(
                  (row) => Object.keys(row).length
                ); // 过滤空行
              },
              error: (error) => {
                console.error("CSV 解析错误：", error);
              },
            });
          };
          reader.readAsText(response.data); // 读取 blob 数据
        })
        .catch((error) => {
          console.error("无法获取 CSV 文件：", error);
        });
    },
    async getWindCodeList() {
      this.loading = true;
      try {
        const resAnalysisedType = await queryAnalysisedType({
          batchCode: this.$route.query.batchCode,
        });
        if (resAnalysisedType.data && resAnalysisedType.data.length > 0) {
          const resEngineList = await queryAnalysisedEngine({
            batchCode: this.$route.query.batchCode,
            analysisTypeCode: resAnalysisedType.data[0].analysisTypeCode,
          });
          this.analysisTypeList = resAnalysisedType.data;
          this.windEngineGroupList = resEngineList.data;
          this.formInfo.fieldEngineCode =
            resEngineList.data !== null && resEngineList.data.length > 0
              ? resEngineList.data[0].engineCode
              : null;
          this.formInfo.analysisTypeCode =
            resAnalysisedType.data.length > 0
              ? resAnalysisedType.data[0].analysisTypeCode
              : "";
          this.loading = false;
        }
        this.getDetailInfo();
      } catch (error) {
        this.loading = false;
        console.error(error);
      }
    },
    // getSpan(index, type) {
    //   let isLastElement = false;
    //   if (type === "generalFiles") {
    //     isLastElement = index === this.generalFiles.length - 1;
    //   } else if (type === "diagramRelations") {
    //     isLastElement = index === this.diagramRelations.length - 1;
    //   }
    //   const isOddPosition = (index + 1) % 2 !== 0;
    //   if (isLastElement && isOddPosition) {
    //     return 24;
    //   }
    //   return 12;
    // },
    getFileType(url) {
      // 使用 URL 对象解析 URL
      // 获取路径名部分
      let pathname = url.split("/").pop();
      // 截取路径名，去除加密乱码字符部分
      const index = pathname.indexOf(".html");
      if (index !== -1) {
        pathname = pathname.slice(0, index + 5); // '.html' 的长度是 5
      } else {
        pathname = pathname.slice(0, pathname.indexOf(".png") + 4); // '.png' 的长度是 4
      }
      // 正则表达式匹配图片扩展名
      const imageExtensions = /\.(png|jpg|jpeg|gif|bmp|svg)$/i;
      // 正则表达式匹配 HTML 扩展名
      const htmlExtensions = /\.html?$/i;

      if (imageExtensions.test(pathname)) {
        return "image";
      } else if (htmlExtensions.test(pathname)) {
        return "html";
      } else {
        return "unknown";
      }
    },
  },
};
</script>
<style scoped lang="scss">
.box-card {
  margin-top: 20px;
}
.imageDetail {
  padding: 80px 100px;
}
.analysisType {
  .assetssConent {
    height: 550px !important;
    .el-col-12 {
      height: 100%;
    }
    .el-col-24 {
      height: 100%;
    }
    iframe {
      width: 100%;
      height: 100%;
    }
    img {
      width: 100%;
      height: auto;
      margin: 0 auto;
    }
  }
}
::v-deep .gjp .el-skeleton {
  width: 90% !important;
  height: 90% !important;
  margin: 0 auto !important;
}
</style>
