<template>
  <div class="global-variable">
    <div class="condition">
      <el-form
        :inline="true"
        ref="ruleForm"
        :model="formInline"
        class="demo-form-inline"
        :rules="rules"
      >
        <el-form-item label="风场名称:" prop="fieldName">
          <el-input
            size="small"
            v-model="formInline.fieldName"
            placeholder="请输入风场名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" size="small"
            >查询</el-button
          >
          <el-button @click="reset('ruleForm')" size="small">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="list-page">
      <el-table
        v-loading="loading"
        class="center-align-table"
        :data="tableData"
        border
        :cell-style="rowStyle"
      >
        <el-table-column
          align="center"
          fixed
          prop="fieldName"
          label="风场名称"
          min-width="200"
        >
        </el-table-column>
        <el-table-column
          align="center"
          label="批次名称"
          prop="batchName"
          min-width="200"
        >
        </el-table-column>
        <el-table-column
          prop="loginName"
          align="center"
          label="进度"
          min-width="150"
        >
          <template slot-scope="scope">
            <el-progress
              v-if="scope.row.analysisState == 20"
              :text-inside="true"
              :stroke-width="20"
              :percentage="scope.row.analysisProgress"
              :class="{
                'indeterminate-progress': scope.row.analysisProgress < 100,
                'animated-progress': true,
              }"
            ></el-progress>
            <span v-else>/</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="loginName"
          align="center"
          label="分析状态"
          min-width="150"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.analysisState == -1">未分析</span>
            <span
              v-else-if="
                scope.row.analysisState == 20 && scope.row.errState == 0
              "
              style="color: #f90"
              >分析中</span
            >
            <span v-else-if="scope.row.errState == 1" style="color: #f00"
              >分析异常</span
            >
            <span
              v-else-if="scope.row.analysisState == 30"
              style="color: #4caf50"
              >分析完成</span
            >
            <span
              v-else-if="scope.row.analysisState == 10"
              style="color: #4caf50"
              >排队中</span
            >
            <span v-else>/</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="errState"
          align="center"
          label="异常状态"
          min-width="120"
        >
          <template slot-scope="scope">
            <span>
              {{
                scope.row.errState == 0 && scope.row.analysisState !== -1
                  ? "未异常"
                  : scope.row.errState === 1
                  ? "异常"
                  : "/"
              }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="roleName"
          align="center"
          label="异常信息"
          min-width="120"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.errState == 1"
              @click="abnormalDialog(scope.row, '异常详情')"
              type="text"
              size="small"
              >异常详情</el-button
            >
            <span v-else>/</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="roleName"
          align="center"
          label="分析记录"
          min-width="120"
        >
          <template slot-scope="scope">
            <!-- 分析完成 -->
            <el-button
              v-if="scope.row.analysisState == 30 && scope.row.errState !== 1"
              @click="handleAssetssDetail(scope.row, '1')"
              type="text"
              size="small"
              >分析详情</el-button
            >
            <!-- 分析中 -->
            <el-button
              v-else-if="
                scope.row.analysisState == 20 && scope.row.errState == 0
              "
              @click="handleAssetssDetail(scope.row, '0')"
              type="text"
              size="small"
              >分析详情</el-button
            >

            <span v-else>/</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="reportVos"
          align="center"
          label="报告"
          min-width="120"
        >
          <template slot-scope="scope">
            <el-dropdown v-if="scope.row.reportVos.length > 0" trigger="click">
              <el-button type="text" size="small" class="el-dropdown-link">
                查看报告
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-for="val in scope.row.reportVos"
                  class="reportItemVal"
                >
                  <div class="reportLeft">
                    <span>{{ val.reportName }}</span>
                  </div>
                  <div class="reportRight">
                    <el-button
                      type="text"
                      size="small"
                      @click="detailReportAssetss(val)"
                    >
                      查看
                    </el-button>
                    <el-button
                      type="text"
                      size="small"
                      @click="downLoadeAssetss(val)"
                    >
                      下载
                    </el-button>
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <span v-else>/</span>
            <!-- <el-button type="text" size="small">
              {{
                scope.row.errState == 0 && scope.row.analysisState !== -1
                  ? "查看报告"
                  : "/"
              }}
            </el-button> -->
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
          min-width="230"
        >
        </el-table-column>

        <el-table-column
          prop="transition"
          align="center"
          fixed="right"
          label="操作"
          min-width="300"
        >
          <template slot-scope="scope">
            <el-button
              @click="abnormalDialog(scope.row, '上传报告')"
              type="text"
              size="small"
              >上传报告</el-button
            >
            <el-button
              @click="handleAssetss(scope.row)"
              type="text"
              size="small"
              >分析</el-button
            >
            <el-button
              @click="abnormalDialog(scope.row, '异常描述')"
              type="text"
              size="small"
              >异常描述</el-button
            >
            <el-button
              @click="HandleOnOffAuto(scope.row)"
              type="text"
              size="small"
              >{{
                scope.row.onOffCall === 0 ? "开启自动分析" : "关闭自动分析"
              }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="formInline.pageNum"
          layout="total, prev, pager, next"
          :page-size="formInline.pageSize"
          :total="formInline.totalSize"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 弹出层 -->
    <!-- 异常信息 /异常描述 /上传报告-->
    <my-dialog
      :visible="dialogVisible"
      :title="title"
      :rowInfo="rowInfo"
      @confirm="handleConfirm"
      @getTableList="fetchData"
    >
      <div slot="tableEl">
        <el-empty description="暂无数据"></el-empty>
      </div>
    </my-dialog>
    <!-- 查看报告详情 -->
    <el-dialog
      title="PDF 预览"
      :visible.sync="dialogReportVisible"
      width="80%"
      class="pdfDialog"
    >
      <div class="pdf-container" ref="viewer">
        <iframe :src="pdfUrl" width="100%" height="100%"></iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MyDialog from "./components/dialogCom.vue";
import { downloadPDF } from "@/utils/common";
import { getAnalysisResultList, onOffAutoAnalysis } from "@/api/performance";
export default {
  components: {
    MyDialog,
  },
  data() {
    return {
      intervalId: null,
      startTime: null,
      maxPollingTime: 5 * 60 * 1000, //轮询最大时间
      dialogVisible: false,
      loadingView: false,
      loading: false, //数据加载中
      errorInfo: "",
      rules: {
        fieldName: { trigger: "blur" },
      },
      roleList: [],
      formInline: {
        fieldName: undefined,
        pageNum: 1,
        pageSize: 10,
        totalSize: 0,
      },
      tableData: [],
      rowInfo: {},
      title: "",
      viewerInstance: null, // PDF 文件 URL
      dialogReportVisible: false,
      pdfUrl: "",
    };
  },
  created() {
    this.getTableList();
  },
  methods: {
    //查看pdf 文件
    detailReportAssetss(row) {
      console.log(row.reportAddr);
      this.dialogReportVisible = true;
      this.pdfUrl = row.reportAddr;
    },

    //下载pdf 文件
    downLoadeAssetss(row) {
      downloadPDF(row.reportAddr, row.reportName);
    },

    async HandleOnOffAuto(row) {
      try {
        const form = new FormData();
        form.append("batchCode", row.batchCode);
        form.append("onOffCall", row.onOffCall === 0 ? 1 : 0);
        const res = await onOffAutoAnalysis(form);
        if (res.code === 200) {
          this.getTableList();
          this.$message({
            type: "success",
            message: `${row.onOffCall === 0 ? "开启" : "关闭"}成功`,
          });
        }
      } catch (err) {
        console.error(err);
      }
    },
    //分析
    handleAssetss(row) {
      this.$router.push({
        path: "/home/performance/editAssets",
        query: {
          batchCode: row.batchCode,
          analysisTypeCode: row.analysisTypeCode,
          fieldEngineCode: row.fieldCode,
        },
      });
    },
    //分析详情
    handleAssetssDetail(row, state) {
      const navigateToDetails = () => {
        this.$router.push({
          path: "/home/performance/assetssDetail",
          query: {
            batchCode: row.batchCode,
            // analysisTypeCode: row.analysisTypeCode,
            fieldCode: row.fieldCode,
          },
        });
      };
      if (state === "0") {
        // 分析状态为分析中
        this.$confirm(
          "当前查看的分析记录为历史分析结果，最新分析记录还未分析完成不展示！"
        )
          .then(() => {
            navigateToDetails();
          })
          .catch(() => {});
      } else {
        navigateToDetails();
      }
    },
    abnormalDialog(row, title) {
      this.dialogVisible = true;
      if (title === "异常详情") {
        this.errorInfo = row.errInfo;
        this.rowInfo = {};
      } else if (title === "异常描述") {
        this.errorInfo = "";
        this.rowInfo = { ...row };
      } else if (title === "上传报告") {
        this.errorInfo = "";
        this.rowInfo = {};
        this.rowInfo.batchCode = row.batchCode;
      }
      this.title = title;
    },
    handleConfirm() {
      this.dialogVisible = false;
    },
    //分页数据切换
    handleCurrentChange(val) {
      this.formInline.pageNum = val;
      this.getTableList();
    },
    async getTableList() {
      try {
        this.loading = true;
        const result = await getAnalysisResultList({
          ...this.formInline,
          totalSize: undefined,
        });
        this.tableData = result.data.list;
        this.formInline.totalSize = result.data.totalSize;
        this.loading = false;
      } catch (error) {
        this.$message({
          type: "error",
          message: "请检查是否连接网络",
        });
      }
    },
    rowStyle() {
      return "text-align:center";
    },
    // 查询
    onSubmit() {
      this.getTableList();
    },
    // 重置
    reset(formName) {
      this.$refs[formName].resetFields();
      this.getTableList();
    },
    async fetchData() {
      try {
        console.log("更新 表格");
        const result = await getAnalysisResultList({
          ...this.formInline,
          totalSize: undefined,
        });
        this.tableData = result.data.list;
        this.formInline.totalSize = result.data.totalSize;
      } catch (error) {
        this.$message({
          type: "error",
          message: "请检查是否连接网络",
        });
      }
    },
    stopPolling() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
        this.intervalId = null;
      }
    },
    startPolling() {
      this.startTime = new Date().getTime();
      this.intervalId = setInterval(() => {
        const currentTime = new Date().getTime();
        if (currentTime - this.startTime >= this.maxPollingTime) {
          this.stopPolling();
        } else {
          this.fetchData();
        }
      }, 10000); // 每10秒调用一次
    },
  },
  mounted() {
    this.startPolling();
  },
  beforeDestroy() {
    this.stopPolling();
  },
};
</script>

<style lang="scss" scoped>
@keyframes striped-flow {
  from {
    background-position: 0 100px;
  }
  to {
    background-position: 1.25em 1.25em;
  }
}
.general {
  display: flex;
  flex-wrap: wrap;

  .condition {
    width: 50%;
    display: flex;

    p {
      width: 100px;
      text-align: right;
      line-height: 40px;
    }

    span {
      line-height: 40px;

      padding-left: 20px;
    }

    .el-select {
      width: 100%;
      margin-bottom: 20px;
    }

    .el-input {
      margin-bottom: 20px;
    }
  }
}

.attachment {
  display: flex;
  padding-top: 10px;

  p {
    margin-right: 20px;
    color: #409eff;
  }
}

.addition {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}
.demo-ruleForm {
  .el-form-item {
    margin-bottom: 25px;
  }
}
::v-deep .animated-progress .el-progress-bar__outer {
  height: 15px; /* Adjust height as needed */
  background-color: rgb(235, 238, 245);
  background-image: linear-gradient(
    45deg,
    rgba(0, 0, 0, 0.1) 25%,
    transparent 25%,
    transparent 50%,
    rgba(0, 0, 0, 0.1) 50%,
    rgba(0, 0, 0, 0.1) 75%,
    transparent 75%,
    transparent
  );
  background-size: 1.25em 1.25em;
  animation: striped-flow 3s linear infinite;
}
.reportItemVal {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .reportLeft {
    margin-right: 50px;
  }
}
::v-deep .pdfDialog .el-dialog {
  height: 90% !important;
  margin: 0 auto !important;
  .el-dialog__body {
    height: 100% !important;
    .pdf-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 90% !important;
    }
  }
}

canvas {
  border: 1px solid #dcdfe6;
}
</style>
