<template>
  <div class="list-wrap">
    <div class="section-head">Test</div>
    <div class="list-box">
      <div class="filter-wrap">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <!--<el-form-item label="Activity reference time">
            <el-date-picker v-model="queryParams.acquisition_start_begin" type="datetime" placeholder="选择日期时间" class="dark-date-picker" popper-class="dark-date-picker"></el-date-picker>
          </el-form-item>
          <el-form-item label="Concentration reference time">
            <el-date-picker v-model="queryParams.acquisition_start_end" type="datetime" placeholder="选择日期时间" class="dark-date-picker" popper-class="dark-date-picker"></el-date-picker>
          </el-form-item>-->

          <el-form-item label="Dataset">
            <el-select v-model="datasetId" placeholder="请选择" class="dark-select" popper-class="dark-select-popper"
              style="width: 120px" @change="getCaseData">
              <el-option v-for="item in datasetIdOptions" :key="item.id" :label="item.id" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="Case">
            <el-select v-model="queryParams.case_no" :disabled="!datasetId" placeholder="请选择" class="dark-select"
              popper-class="dark-select-popper" style="width: 180px" @change="caseChange">
              <el-option v-for="item in caseOptions" :key="item.case_no" :label="item.case_no" :value="item.case_no">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="Classify">
            <el-select v-model="modelTypes" multiple placeholder="请选择" class="dark-select"
              popper-class="dark-select-popper" style="width: 400px" @change="modelTypeChange">
              <el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="">
            <el-upload ref="upload" v-model:file-list="fileList" class="upload-demo" :auto-upload="false" :limit="1"
              :multiple="false" :show-file-list="false" :on-change="handleChange"
              style="height: 32px; margin-left: 12px;">
              <el-button type="primary" icon="upload"
                style="background-color: #7393b7; border-color: #7393b7; border-radius: 0;">Upload</el-button>
            </el-upload>
            <el-button type="primary" icon="search"
              style="background-color: #7393b7; border-color: #7393b7; border-radius: 0; margin-left: 12px;"
              @click="onSearch">Select</el-button>
            <el-button type="primary" icon="document"
              style="background-color: #7393b7; border-color: #7393b7; border-radius: 0; margin-left: 12px;"
              @click="onDownload">Download</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="chart-wrap">
        <div ref="chartDom" style="width: 100%; height: 100%"></div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      datasetId: '',
      datasetIdOptions: [],
      queryParams: {
        page: 1,
        size: 10,
        case_no: '',
        model_types: '',
        file: '',
      },
      selectOptions: [
        {
          value: 'CNN',
          label: 'CNN',
        },
        {
          value: 'BDT',
          label: 'BDT',
        },
        {
          value: 'SVM',
          label: 'SVM',
        },
        {
          value: 'MLP',
          label: 'MLP',
        },
        {
          value: 'RF',
          label: 'RF',
        },
      ],
      caseOptions: [],
      fileList: [],
      modelTypes: [],
      currentFile: null,
      myChart: null,
      chartData: {
        datasetSource: []
      },
      outPath: '',
      output_path: ''
    }
  },
  created() {
    // color: ['#0A4072', '#683F14', '#0F605A', '#0F5A7A', '#5C5F25']
    // this.onSearch()
    this.getDataset()
  },
  mounted() {
    this.chart()
  },
  methods: {
    onSearch() {
      this.loading = true
      const formData = new FormData()
      formData.append("file", this.currentFile)
      formData.append("case_no", this.queryParams.case_no)
      formData.append("model_types", this.queryParams.model_types)
      // this.$axios.post(window.CONFIG.baseUrl + '/train-oneday/predict', formData, { headers: { "Content-Type": "multipart/form-data" } }).then((res) => {
      this.$axios.post(window.CONFIG.baseUrl + '/train-oneday/predict_with_label', formData, { headers: { "Content-Type": "multipart/form-data" } }).then((res) => {
        console.log('Predict_output_path', res.output_path)
        this.output_path = res?.output_path
        this.chartData.dataset = res.echart_data
        this.myChart.setOption({
          dataset: {
            source: res.echart_data
          },
        })
      }).finally(() => {
        this.loading = false
      })
    },
    getDataset() {
      this.$axios.get(window.CONFIG.baseUrl + '/train-oneday/query_train_datasets', { params: { page: 1, size: 100 } }).then((res) => {
        this.datasetIdOptions = res.data.items
      })
    },
    async getCaseData(datasetId) {
      const res = await this.$axios.get(window.CONFIG.baseUrl + '/train-oneday/query_train_cases', { params: { dataset_id: datasetId, model_type: '', case_no: '', page: 1, size: 100 } })
      this.caseOptions = this.removeDuplicatesByMap(res.data.items)
    },
    removeDuplicatesByMap(arr) {
      const map = new Map()
      arr.forEach(item => {
        if (!map.has(item.case_no)) {
          map.set(item.case_no, item)
        }
      })
      return Array.from(map.values())
    },
    caseChange(id) {
      const arr = this.caseOptions.filter(item => item.case_no === id)
      if (arr.length) {
        this.outPath = arr[0].out_path
      }
    },
    // 文件选择变化
    handleChange(file, fileList) {
      if (file) {
        this.currentFile = file.raw || file
      } else {
        this.currentFile = null
      }
    },
    modelTypeChange(data) {
      this.queryParams.model_types = data.join(',')
    },
    onDownload() {
      const arr = this.queryParams.model_types.split(',')
      arr.forEach(item => {
        // const url = this.outPath + '\\' + this.queryParams.case_no + '_' + item + '_ROC.json'
        // const path = url.replace(/\\/g, '/')
        const path = this.output_path
        // this.$axios.get(window.CONFIG.baseUrl + '/download', { params: { path: path }})
        this.downloadFile(path, this.queryParams.case_no + '_' + item + '_ROC.json')
      })
    },
    chart() {
      this.myChart = this.$echarts.init(this.$refs.chartDom)
      const option = {
        grid: {
          left: 40,
          right: 20,
          bottom: 10,
          top: 20,
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          axisLine: {
            lineStyle: {
              color: '#273F4B',
              width: 1,
            },
          },
          axisTick: {
            lineStyle: {
              color: '#152029',
              width: 1,
            },
          },
          axisLabel: {
            color: '#a2b4c9',
            // rotate: 0
          },
          splitLine: {
            lineStyle: {
              color: '#152029',
              type: 'dashed',
            },
          },
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: true,
            lineStyle: {
              color: '#273F4B',
            },
          },
          axisLabel: {
            color: '#a2b4c9',
          },
          splitLine: {
            lineStyle: {
              color: '#152029',
              type: 'dashed',
            },
          },
          // axisTick: {
          //   show: true,
          //   lineStyle: {
          //     color: '#f00'
          //   }
          // }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        color: ['#0A4072', '#683F14', '#0F605A', '#0F5A7A', '#5C5F25'],
        dataset: {
          source: this.chartData.datasetSource
        },
        series: [{ type: 'bar' }, { type: 'bar' }, { type: 'bar' }]
      }
      this.myChart.setOption(option)
    },
    downloadFile(url, filename) {
      const link = document.createElement('a')
      link.href = url
      link.download = filename
      link.style.display = 'none'

      document.body.appendChild(link)
      link.click()

      document.body.removeChild(link)
    },
  },
}
</script>

<style scoped lang="scss">
.list-wrap {
  height: 100%;
  overflow: hidden;
  color: #fff;
  display: flex;
  flex-direction: column;

  .section-head {
    height: 32px;
    padding: 0 13px;
    background-color: #1c2630;
    border-left: 4px solid #be8728;
    font-family: MICROGRAMMADMEDEXT;
    font-size: 20px;
    font-weight: bold;
  }

  .list-box {
    flex: 1;
    display: flex;
    flex-direction: column;

    .filter-wrap {
      height: 50px;
      margin-top: 16px;

      ::v-deep .el-form-item__label {
        font-size: 16px;
        color: #a7bacf;
      }
    }

    .chart-wrap {
      flex: 1;
    }
  }
}
</style>
