<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="84px">
      <el-form-item label="算法类型" prop="type">
        <el-select :disabled="isDisabled" v-model="queryParams.type" placeholder="请选择算法类型" clearable filterable @change="changeQueryType()">
          <el-option v-for="dict in dict.type.algorithm_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="算法子类型" prop="subTypeId">
        <el-select :disabled="isDisabled" v-model="queryParams.subTypeId" placeholder="请选择算法子类型" clearable filterable @change="getList()">
          <el-option v-for="item in algoTypeList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="非理想数据" prop="type">
        <el-select :disabled="isDisabled" v-model="nonIdeal" placeholder="请选择非理想数据" clearable filterable @change="viewResult">
          <el-option v-for="item in nonIdealData" :key="item.id" :label="item.name" :value="item.id">
            {{ item.name }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="isDisabled" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查看</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="chart">
      <div ref="chart1" class="chart1"></div>
      <div ref="chart2" class="chart2"></div>
    </div>
  </div>
</template>

<script>
import { listSubType, getSubType } from "@/api/conf/subType";
import { listAlgorithm, getAlgorithmDto } from '@/api/algoManager/algorithm'
import { parseCSV } from '@/utils/cvstoarrory'
import { listInputFile } from '@/api/algoManager/file'
import { getAlgoSubOption } from '@/api/algoManager/algorithm'
import * as echarts from 'echarts/core'
import { TitleComponent, GridComponent } from 'echarts/components'
import { ScatterChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([
  TitleComponent,
  GridComponent,
  ScatterChart,
  CanvasRenderer,
  UniversalTransition,
])

export default {
  name: 'Contrast',
  dicts: ['algorithm_type', 'data_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件表格数据
      fileList: [],
      // 输入文件表格数据
      nonIdealData: [],
      // 选择的非理想数据
      nonIdeal: null,
      // 非理想数据的输入输出
      ioSubList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        type: null,
        subTypeId: null,
        dictType: 'process_type',
        dataType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      optionData: [{ value: '4', label: '理想数据' }],
      typeMap: new Map(),
      // 算法特定类列表
      algoTypeList: [],
      // 算法子类列表
      algorithmSubList: [],
      // 原始数据
      rawData: [],
      chart1: null,
      option1: null,
      // 理想数据
      idealData: [],
      chart2: null,
      option2: null,
      // 是否禁用选择框
      isDisabled:false
    }
  },
  mounted() {
  },
  created() {
    this.getAlgoSubOption()
    // 获取跳转过来的参数
    this.getParam()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    // 获取跳转参数
    getParam(){
      let param=this.$route.params.nonIdealID
      if(param !== undefined){
        // 根据nonIdealID获取算法类型
        getAlgorithmDto(param).then(response => {
          this.ioSubList = response.data.ioSubList
          // 绑定算法类型的值
          this.queryParams.type=response.data.type
          // 绑定非理想数据的值
          this.nonIdeal=response.data.name
          let subTypeId=response.data.subTypeId
          let data={
            pageNum: 1,
            pageSize: 100,
            type:this.queryParams.type
          }
          // 获取算法子类型的名称
          listSubType(data).then(response => {
            const filteredData = response.rows.filter(item => item.id === subTypeId);
            this.queryParams.subTypeId=filteredData[0].name
            this.handleQuery()
          });
          this.isDisabled=true
        })
      }
    },
    /** 查看非理想 */
    getList() {
      this.loading = true
      this.nonIdeal = null
      listAlgorithm(this.queryParams).then(response => {
        this.nonIdealData = response.rows.filter(item => item.status === '2')
        this.total = response.total
        this.loading = false
      })
    },
    // 查询算法子类列表
    getAlgoSubOption() {
      getAlgoSubOption().then(resp => {
        this.algorithmSubList = resp.data
        this.createTypeMap()
        console.info(resp)
      })
    },
    // 查看非理想数据
    viewResult(value) {
      if (!value) {
        this.$message.error('请选择要对比的数据')
      } else {
        console.log(value)
        getAlgorithmDto(value).then(response => {
          this.ioSubList = response.data.ioSubList
          console.log(this.ioSubList)
        })
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.nonIdeal = null
      this.nonIdealData = []
      this.algoTypeList = []
      this.isDisabled=false
      if (this.chart1) {
        this.chart1.dispose()
        this.chart1 = null
      }
      if (this.chart2) {
        this.chart2.dispose()
        this.chart2 = null
      }
    },
    /** 查看按钮操作 */
    handleQuery() {
      if (this.chart1) {
        this.chart1.dispose()
        this.chart1 = null
      }
      if (this.chart2) {
        this.chart2.dispose()
        this.chart2 = null
      }
      if (this.ioSubList){
        let firstInput = this.ioSubList.find(item => item.type === "1" && item.path.includes(".csv"));
        let firstOut = this.ioSubList.find(item => item.type === "2" && item.path.includes(".csv"));
        if (firstInput) {
          this.handleCSV(firstInput.path, firstInput.type)
        }
        if(firstOut){
          this.handleCSV(firstOut.path, firstOut.type)
        }
      }
    },
    /** 创建连接算法大类型和算法子类列表的map */
    createTypeMap() {
      this.typeMap = new Map()
      for (const algorithmSub of this.algorithmSubList) {
        if (this.typeMap.has(algorithmSub.type)) {
          this.typeMap.get(algorithmSub.type).push({
            id: algorithmSub.id,
            name: algorithmSub.name,
          })
        } else {
          this.typeMap.set(algorithmSub.type, [
            {
              id: algorithmSub.id,
              name: algorithmSub.name,
            },
          ])
        }
      }
    },
    changeQueryType() {
      this.queryParams.subTypeId = null
      this.nonIdeal = null
      if (this.queryParams.type === '2') {
        this.queryParams.dictType = 'extract_type'
      } else if (
        this.queryParams.type === '1' ||
        this.queryParams.type === '4'
      ) {
        this.queryParams.dictType = 'predict_type'
      } else {
        this.queryParams.dictType = 'process_type'
      }
      console.log(this.queryParams.dictType)
      this.algoTypeList = this.typeMap.get(this.queryParams.type)
    },
    // echarts
    showECharts1() {
      var chartDom = this.$refs.chart1
      this.chart1 = echarts.init(chartDom)
      // var option
      this.option1 = {
        title: {
          show: true,
          text: '非理想数据',
          x: 'center',
          top: 10,
        },
        xAxis: {},
        yAxis: {},
        series: [
          {
            symbolSize: 5,
            data: this.rawData,
            type: 'scatter',
          },
        ],
      }
      this.option1 && this.chart1.setOption(this.option1)
    },
    showECharts2() {
      var chartDom = this.$refs.chart2
      this.chart2 = echarts.init(chartDom)
      this.option2 = {
        title: {
          text: '理想数据',
          left: 'center',
          top: 10,
        },
        xAxis: {},
        yAxis: {},
        series: [
          {
            symbolSize: 5,
            data: this.idealData,
            type: 'scatter',
          },
        ],
      }
      this.option2 && this.chart2.setOption(this.option2)
    },
    // 解析CSV测试方法
    async handleCSV(path, type) {
      if (type === '1') {
        const url = process.env.VUE_APP_BASE_API + path
        let parsedData = await parseCSV(url)
        this.rawData = parsedData.map((item, index) => {
          for (const key in item) {
            if (item.hasOwnProperty(key)) {
              return [index, item[key]]
            }
          }
        })
        console.log(this.rawData)
        this.showECharts1()
      } else {
        const url = process.env.VUE_APP_BASE_API + path
        let parsedData = await parseCSV(url)
        parsedData.forEach((obj, index) => {
          for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
              this.idealData.push([index, obj[key]])
            }
          }
        })
        // }
        console.log(this.idealData)
        this.showECharts2()
      }
    },
  },
}
</script>

<style scoped>
.chart1 {
  width: 100%;
  height: 300px;
}
.chart2 {
  width: 100%;
  height: 500px;
}
</style>