<template>
  <div class="home">
    <div class="second">
      <div class="topPanel">
        <!-- 原始数据 -->
        <div class="tPanel">
          <el-table size="mini" :data="originalList">
            <el-table-column prop="dataName" label="数据" align="center">
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
            </el-table-column>
          </el-table>
        </div>
        <!-- 补全 -->
        <div class="tPanel">
          <el-table size="mini" :data="completionList">
            <el-table-column prop="dataName" label="数据" align="center">
              <template slot-scope="scope">
                <span class="file" @click="handleFile(scope.row.dataPath, scope.row.dataType)">{{ scope.row.dataName
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
            </el-table-column>
          </el-table>
        </div>
        <!-- 特征提取 -->
        <div class="tPanel">
          <el-table size="mini" :data="featureExtractionList">
            <el-table-column prop="dataName" label="数据" align="center">
              <template slot-scope="scope">
                <span class="file" @click="handleFile(scope.row.dataPath, scope.row.dataType)">{{ scope.row.dataName
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
            </el-table-column>
          </el-table>
        </div>
        <!-- 故障预测 -->
        <div class="tPanel">
          <el-table size="mini" :data="faultPredictionList">
            <el-table-column prop="dataName" label="数据" align="center">
              <template slot-scope="scope">
                <span class="file" @click="imgShow(scope.row.dataPath,scope.row.dataType)">{{ scope.row.dataName
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="step">
        <div class="yuan">
          <div class="img yuanBg odd">
            <div class="tag">原始数据</div>
          </div>
        </div>
        <div class="one">
          <div class="img oneBg even" @click="handleProcess(0)">
            <div class="tag">去噪</div>
          </div>
        </div>
        <div class="two">
          <div class="img twoBg odd" @click="handleProcess(1)">
            <div class="tag">补全</div>
          </div>
        </div>
        <div class="three">
          <div class="img threeBg even" @click="handleProcess(2)">
            <div class="tag">扩充</div>
          </div>
        </div>
        <div class="four">
          <div class="img fourBg odd" @click="handleProcess(3)">
            <div class="tag">特征提取</div>
          </div>
        </div>
        <div class="five">
          <div class="img fiveBg even" @click="handleProcess(4)">
            <div class="tag">退化评估</div>
          </div>
        </div>
        <div class="six">
          <div class="img sixBg odd noAfter" style="content: none;" @click="handleProcess(5)">
            <div class="tag">故障预测</div>
          </div>
        </div>
      </div>
      <div class="bottomPanel">
        <!-- 去噪 -->
        <div class="bPanel">
          <el-table size="mini" :data="denoisingList">
            <el-table-column prop="dataName" label="数据" align="center">
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
            </el-table-column>
          </el-table>
        </div>
        <!-- 扩充 -->
        <div class="bPanel">
          <el-table size="mini" :data="expansionList">
            <el-table-column prop="dataName" label="数据" align="center">
              <template slot-scope="scope">
                <span class="file" @click="handleFile(scope.row.dataPath, scope.row.dataType)">{{ scope.row.dataName
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
            </el-table-column>
          </el-table>
        </div>
        <!-- 退化评估 -->
        <div class="bPanel">
          <el-table size="mini" :data="assessmentList">
            <el-table-column prop="dataName" label="数据" align="center">
              <template slot-scope="scope">
                <span class="file" @click="handleFile(scope.row.dataPath, scope.row.dataType)">{{ scope.row.dataName
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
            </el-table-column>
          </el-table>
        </div>
        <div>
        </div>
      </div>
    </div>
    <div class="first">
      <h4 style="margin:13px 0px 0px 20px;color: #fff;">算法统计</h4>
      <div class="chart">
        <RingChart />
        <BarChart width="700px" />
      </div>
    </div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数据" prop="processType">
          <el-select v-model="form.data" placeholder="请选择执行的数据">
            <el-option v-for="(item, index) in optionalData" :key="index" :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="算法" prop="processType">
          <el-select v-model="form.aglo" placeholder="请选择执行的算法">
            <el-option v-for="(item, index) in optionalAglo" :key="index" :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitHandle()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="数据展示" :visible.sync="fileShowVisible" width="80%" :close-on-click-modal="false">
      <el-button v-if="fileType !== '4'&& fileType!=='5'" style="margin-left:50px;" type="text" @click="changeShow">{{ isTableShow ?
            '表格展示'
            :
            '曲线展示'
        }}</el-button>
      <div v-if="isTableShow && fileType!=='5'">
        <el-table :data="completionData" size="mini" style="width: 100%;height: 500px;overflow:scroll;">
          <el-table-column v-for="(item, index) in completionHeadData" :key="index" align="center" :prop="'val' + index"
            :label="item">
          </el-table-column>
        </el-table>
      </div>
      <div v-if="!isTableShow && fileType!=='5'" ref="completionChartRef" style="width: 100%; height: 400px;"></div>
      <ImagePreview v-if="fileType==='5'" :src="imgPreviewUrl"></ImagePreview>
    </el-dialog>
  </div>
</template>

<script>
import CountTo from 'vue-count-to'
import RingChart from '@/views/homePage/ringChart'
import BarChart from '@/views/dashboard/BarChart'
import { getAlgConfigByType } from "@/api/system/algConfig";
import { getDataProcessByType, addProcess } from "@/api/system/process";
import { getDataByType } from "@/api/system/data";
import * as echarts from 'echarts';
export default {
  name: 'Index',
  components: {
    CountTo,
    RingChart,
    BarChart,
  },
  data() {
    return {
      loading: true,
      rules: {},
      title: '选择数据',
      baseUrl: process.env.VUE_APP_BASE_API,
      dialogVisible: false,
      fileShowVisible: false,
      originalList: [],
      denoisingList: [],
      completionList: [],
      expansionList: [],
      featureExtractionList: [],
      assessmentList: [],
      faultPredictionList: [],
      optionalData: [],
      optionalAglo: [],
      form: {
        data: null,
        aglo: null
      },
      // 对话框展示数据内容
      completionData: [],
      completionHeadData: [],
      isTableShow: false,
      filePath: null,
      fileType: null,
      chart: null,
      imgPreviewUrl:null
    }
  },
  created() {
    this.getTableData()
  },
  methods: {
    getTableData() {
      getDataByType(1).then(res => {
        this.completionList = res.data
      })
      getDataByType(2).then(res => {
        this.expansionList = res.data
      })
      getDataByType(3).then(res => {
        this.featureExtractionList = res.data
      })
      getDataByType(4).then(res => {
        this.assessmentList = res.data
      })
      getDataByType(5).then(res => {
        this.faultPredictionList = res.data
      })
    },
    goTarget(href) {
      window.open(href, '_blank')
    },
    handleSetLineChartData(type) {
      this.$emit('handleSetLineChartData', type)
    },
    handleProcess(type) {
      this.dialogVisible = true;
      getDataProcessByType(type).then(res => {
        this.optionalData = res.data;
      });
      getAlgConfigByType(type).then(res => {
        this.optionalAglo = res.data;
      });
    },
    submitHandle() {
      addProcess(this.form).then(response => {
        this.$modal.msgSuccess("开始执行");
        this.dialogVisible = false;
        this.getTableData()
      });
    },
    handleFile(dataPath, dataType) {
      if (this.chart) {
        this.chart.dispose();
        this.chart = null
      }
      this.filePath = dataPath
      this.fileType = dataType
      const url = `${process.env.VUE_APP_BASE_API}${dataPath}`;
      this.fetchLogFile(url)
        .then((text) => {
          const color = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
          switch (dataType) {
            case '1':
              const returnData = this.handleFileData(text)
              const contentData = returnData.contentData
              const headData = returnData.headData
              this.fileShowVisible = true
              this.$nextTick(() => {
                this.chart = echarts.init(this.$refs.completionChartRef);
                // series数据
                const series = contentData.map((lineData, index) => ({
                  name: `${headData[index]}`,
                  type: 'line',
                  data: lineData,
                  stack: 'Total',
                  connectNulls: true, // 连接相邻的非空数据点
                  markPoint: {
                    data: lineData.map((value, idx) => ({
                      value: value === 0 ? '缺失' : null,
                      xAxis: idx,
                      // yAxis: lineData[idx-1],
                      yAxis: value,
                      itemStyle: { color: color[index] } // 高亮显示缺失值
                    })).filter(point => point.value)
                  }
                }));
                const option = {
                  tooltip: {
                    trigger: 'axis'
                  },
                  legend: {
                    data: headData,
                    textStyle: {//图例文字的样式
                      color: '#fff'
                    }
                  },
                  color: color,
                  xAxis: {
                    type: 'category',
                    data: contentData[0].map((_, index) => index), // 生成x轴下标
                    name: 'Index'
                  },
                  yAxis: {
                    type: 'value',
                    name: 'Value'
                  },
                  dataZoom: [
                    {
                      type: 'slider',
                      start: 0,
                      end: 100
                    },
                    {
                      type: 'inside',
                      start: 0,
                      end: 100
                    }
                  ],
                  series: series
                };
                this.chart.setOption(option);
              })
              break;
            case '2':
              const data = text.split("\r\n").filter(line => line.trim() !== '').map(row => row.split(','));
              data[0].shift();
              const completionHead = data[0];
              const completionContent = Array.from({ length: completionHead.length }, () => []);
              const timeData = []
              for (let i = 1; i < data.length; i++) {
                data[i].forEach((value, index) => {
                  if (index === 0) {
                    timeData.push(value)
                  } else {
                    completionContent[index - 1].push(Number(value));
                  }
                });
              }
              this.fileShowVisible = true
              this.$nextTick(() => {
                this.chart = echarts.init(this.$refs.completionChartRef);
                // series数据
                const series = completionContent.map((lineData, index) => ({
                  name: `${completionHead[index]}`,
                  type: 'line',
                  data: lineData,
                  stack: 'Total',
                  connectNulls: true, // 连接相邻的非空数据点
                }));
                const option = {
                  tooltip: {
                    trigger: 'axis'
                  },
                  legend: {
                    data: headData,
                    textStyle: {//图例文字的样式
                      color: '#fff'
                    }
                  },
                  color: color,
                  xAxis: {
                    type: 'category',
                    data: timeData,
                    name: 'time'
                  },
                  yAxis: {
                    type: 'value',
                    name: 'Value'
                  },
                  dataZoom: [
                    {
                      type: 'slider',
                      start: 0,
                      end: 100
                    },
                    {
                      type: 'inside',
                      start: 0,
                      end: 100
                    }
                  ],
                  series: series
                };
                this.chart.setOption(option);
              })
              break;
            case '3':
              const ExtractionData = text.split("\r\n").filter(line => line.trim() !== '').map(row => row.split(','));
              ExtractionData[0].shift();
              const ExtractionHead = ExtractionData[0];
              const ExtractionContent = Array.from({ length: ExtractionHead.length }, () => []);
              const ExtractionTime = []
              for (let i = 1; i < ExtractionData.length; i++) {
                ExtractionData[i].forEach((value, index) => {
                  if (index === 0) {
                    ExtractionTime.push(value)
                  } else {
                    ExtractionContent[index - 1].push(Number(value));
                  }
                });
              }
              this.fileShowVisible = true
              this.$nextTick(() => {
                this.chart = echarts.init(this.$refs.completionChartRef);
                // series数据
                const series = ExtractionContent.map((lineData, index) => ({
                  name: `${ExtractionHead[index]}`,
                  type: 'line',
                  data: lineData,
                  stack: 'Total',
                  connectNulls: true, // 连接相邻的非空数据点
                }));
                const option = {
                  tooltip: {
                    trigger: 'axis'
                  },
                  legend: {
                    data: headData,
                    textStyle: {//图例文字的样式
                      color: '#fff'
                    }
                  },
                  color: color,
                  xAxis: {
                    type: 'category',
                    data: ExtractionTime,
                    name: 'time'
                  },
                  yAxis: {
                    type: 'value',
                    name: 'Value'
                  },
                  dataZoom: [
                    {
                      type: 'slider',
                      start: 0,
                      end: 100
                    },
                    {
                      type: 'inside',
                      start: 0,
                      end: 100
                    }
                  ],
                  series: series
                };
                this.chart.setOption(option);
              })
              break;
            case '4':
              const assessmentData = this.handleFileData(text)
              const assessmentcontent = assessmentData.contentData
              const assessmenthead = assessmentData.headData
              this.fileShowVisible = true
              this.$nextTick(() => {
                this.chart = echarts.init(this.$refs.completionChartRef);
                // series数据
                const series = assessmentcontent.map((lineData, index) => ({
                  name: `${assessmenthead[index]}`,
                  type: 'line',
                  data: lineData,
                  stack: 'Total',
                  connectNulls: true, // 连接相邻的非空数据点
                }));
                const option = {
                  tooltip: {
                    trigger: 'axis'
                  },
                  legend: {
                    data: assessmenthead,
                    textStyle: {//图例文字的样式
                      color: '#fff'
                    }
                  },
                  color: color,
                  xAxis: {
                    type: 'category',
                    data: assessmentcontent[0].map((_, index) => index), // 生成x轴下标
                    name: 'Index'
                  },
                  yAxis: {
                    type: 'value',
                    name: 'Value'
                  },
                  series: series
                };
                this.chart.setOption(option);
              })
              break;
            default:
              break;
          }
        })
        .catch((error) => {
          console.error("Failed to fetch the log file:", error);
          this.$modal.msgSuccess("文件读取错误");
        });
    },
    // 读取文件内容
    async fetchLogFile(url) {
      try {
        const response = await fetch(url, { method: "GET" });
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return await response.text();
      } catch (error) {
        throw error;
      }
    },
    // 对数据的处理
    handleFileData(fileData) {
      // 每行数据转换成数组、过滤出存在的空白行、将没行数据按照,号分割
      const data = fileData.split("\r\n").filter(line => line.trim() !== '').map(row => row.split(','));
      const headData = data[0];
      const contentData = Array.from({ length: headData.length }, () => []);
      for (let i = 1; i < data.length; i++) {  // 从 1 开始，跳过表头
        data[i].forEach((value, index) => {
          contentData[index].push(Number(value));
        });
      }
      return { contentData, headData }
    },
    // 切换表格/曲线展示
    changeShow() {
      this.isTableShow = !this.isTableShow
      if (!this.isTableShow) {
        this.handleFile(this.filePath, this.fileType)
      } else {
        this.tableShow(this.filePath, this.fileType)
      }
    },
    tableShow(path, type) {
      const url = `${process.env.VUE_APP_BASE_API}${path}`;
      this.fetchLogFile(url)
        .then((text) => {
          const data = text.split("\r\n").filter(line => line.trim() !== '').map(row => row.split(','));
          this.completionHeadData = data.shift();
          this.completionData = data.map(row => {
            const rowData = {};
            for (let i = 0; i < this.completionHeadData.length; i++) {
              rowData[`val${i}`] = (row[i]) === 0 ? null : (row[i]);
            }
            return rowData;
          })
        })
    },
    imgShow(url,dataType){
      this.fileType = dataType
      this.imgPreviewUrl = url
      this.fileShowVisible = true
    }
  }
}
</script>

<style scoped lang="scss">
.home {
  width: 100%;
  /* 设置宽度为100%，以充满父 div 的宽度 */
  min-height: calc(100vh - 84px);
  /* 设置高度为100%，以充满父 div 的高度 */
  // background-color: #f4f4f4;
  overflow: hidden;
}

.first {
  width: 97%;
  height: 210px;
  margin: 20px;
  // background-color: white;
  border-radius: 15px;
  overflow: hidden;
  // box-shadow: 0 0 10px rgba(63, 155, 255, 0.5);
  // background: url("../assets/images/msgBg3.png") no-repeat center / contain;
}

.chart {
  display: flex;
  justify-content: space-around;
  margin-left: 30px;
}

.second {
  width: 97%;
  height: 440px;
  margin: 50px 20px;
  // overflow: hidden;
  display: flex;
  flex-direction: column;

  .step {
    width: 100%;
    height: 120px;
    display: flex;
    justify-content: space-around;

    .yuan,
    .one,
    .two,
    .three,
    .four,
    .five,
    .six,
    .final {
      width: 12%;
      height: 100%;
      text-align: center;
    }

    .item {
      margin-top: 10px;
      margin-right: 40px;
    }

    .img {
      width: 40%;
      height: 95%;
      margin: 0 auto;
      position: relative;
    }

    .img::after {
      content: "";
      position: absolute;
      top: 50%;
      transform: translateX(26%);
      width: 200%;
      height: 1px;
      // background-color: #546882;
      background-color: #00aaff;
      box-shadow: 0 5px 15px rgba(0, 170, 255, 0.5);
    }

    .noAfter::after {
      content: none;
    }

    .odd::before {
      content: "";
      position: absolute;
      transform: translateY(-50%);
      width: 1px;
      height: 50%;
      // background-color: #546882;
      background-color: #00aaff;
      box-shadow: 0 5px 15px rgba(0, 170, 255, 0.5);
    }

    .even::before {
      content: "";
      position: absolute;
      bottom: 0;
      transform: translateY(50%);
      width: 1px;
      height: 50%;
      // background-color: #546882;00aaff
      background-color: #00aaff;
      box-shadow: 0 5px 15px rgba(0, 170, 255, 0.5);
    }

    .yuanBg {
      background: url("../assets/images/yuan.png") no-repeat center / contain;
    }

    .oneBg {
      background: url("../assets/images/one.png") no-repeat center / contain;
    }

    .twoBg {
      background: url("../assets/images/two.png") no-repeat center / contain;
    }

    .threeBg {
      background: url("../assets/images/three.png") no-repeat center / contain;
    }

    .fourBg {
      background: url("../assets/images/four.png") no-repeat center / contain;
    }

    .fiveBg {
      background: url("../assets/images/five.png") no-repeat center / contain;
    }

    .sixBg {
      background: url("../assets/images/six.png") no-repeat center / contain;
    }

    .tag {
      color: #fff;
      background: linear-gradient(to right, rgba(8, 200, 236, 0), rgba(8, 200, 236, 0.8), rgba(8, 200, 236, 0.8), rgba(8, 200, 236, 0));
      position: absolute;
      top: -15px;
      left: 100%;
    }
  }

  .topPanel {
    width: 100%;
    height: 37%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 1.5%;
  }

  .bottomPanel {
    width: 100%;
    height: 37%;
    display: flex;
    justify-content: space-around;
    margin-left: 6%;
    margin-top: 1%;
  }

  .tPanel,
  .bPanel {
    // position: relative;
    width: 18%;
    height: 95%;
    overflow: auto;
    // background: url("../assets/images/msgBg3.png") no-repeat center / contain;
    // background: rgba(0, 0, 0, 0.15);
    border: 2px solid transparent;
    background-clip: padding-box;
    box-shadow: 0 0 10px rgba(63, 155, 255, 0.5);
    border-radius: 5%;
  }

}

.file {
  cursor: pointer;
}

.file:hover {
  color: #00aaff;
}

.square {
  width: 90px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  border-radius: 12px;
  font-size: 14px;
  border: 2px solid grey;
}

.diamond {
  height: 100px;
  width: 100px;
  transform: rotateZ(45deg) skew(-20deg, -20deg);
  position: relative;
  border: 2px solid grey;

  .diamond-p {
    position: absolute;
    width: 140px;
    top: 14%;
    left: -17%;
    transform: skew(20deg, 20deg) rotateZ(-45deg);
  }
}

::-webkit-scrollbar {
  display: none;
}

::v-deep .el-table__empty-block {
  background-color: #0b333f !important;
  border: #0b333f;
}
</style>
