<template>
  <div class="gamma-analysis">
    <a-spin :spinning="isLoading">
      <!-- 二级交互栏 -->
      <div class="spectrum-analysis-sub-operators">
        <pop-over-with-icon placement="bottomLeft">
          Detailed-Information
          <detailed-infomation slot="content" :data="detailedInfomation" />
        </pop-over-with-icon>
        <pop-over-with-icon placement="bottomLeft">
          QC Flags
          <qc-flags slot="content" :data="qcFlags" />
        </pop-over-with-icon>
        <pop-over-with-icon>
          Graph Assistance
          <graph-assistance slot="content" @change="handleGraphAssistanceChange" />
        </pop-over-with-icon>
        <pop-over-with-icon>
          Nuclide Library
          <nuclear-library slot="content" />
        </pop-over-with-icon>
        <div class="peak-info">
          <button-with-switch-icon @change="handlePeakInfoChange">
            Peak Information
          </button-with-switch-icon>
        </div>
      </div>
      <!-- 二级交互栏结束 -->
      <!-- 主体部分 -->
      <div class="gamma-analysis-main">
        <div class="gamma-analysis-chart">
          <custom-chart ref="chartRef" :option="option" @zr:click="handleChartClick" style="height: 100%" />

          <div class="gamma-analysis-thumbnail">
            <custom-chart ref="thumbnailChartRef" :option="thumbnailOption" style="height: 100%" />
          </div>
        </div>
      </div>
      <!-- 主体部分结束 -->
    </a-spin>
  </div>
</template>

<script>
import CustomChart from '@/components/CustomChart/index.vue'
import PopOverWithIcon from './components/SubOperators/PopOverWithIcon.vue'
import DetailedInfomation from './components/SubOperators/DetailedInfomation.vue'
import QcFlags from './components/SubOperators/QcFlags.vue'
import GraphAssistance from './components/SubOperators/GraphAssistance.vue'
import NuclearLibrary from './components/SubOperators/NuclearLibrary.vue'
import ButtonWithSwitchIcon from './components/SubOperators/ButtonWithSwitchIcon.vue'
import { getAction } from '@/api/manage'
import Response from './response.json'
import { getXAxisAndYAxisByPosition } from '@/utils/chartHelper'

// 初始配置
const initialOption = {
  grid: {
    top: 40,
    left: 60,
    right: 50,
    containLabel: true
  },
  title: {
    text: '',
    left: 'center',
    bottom: 10,
    textStyle: {
      color: '#8FD4F8',
      rich: {
        a: {
          padding: [0, 20, 0, 0],
          fontSize: 16
        }
      }
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      lineStyle: {
        color: '#099D24',
        width: 2
      }
    },
    formatter: params => {
      const [channel] = params[0].value
      return `<div class="channel">Channel: ${channel}</div>
              <div class="energy">Energy: ${(0).toFixed(2)}</div>`
    },
    className: 'figure-chart-option-tooltip'
  },
  xAxis: {
    name: 'Channel',
    nameTextStyle: {
      color: '#8FD4F8',
      fontSize: 16,
      align: 'right',
      verticalAlign: 'top',
      padding: [30, 0, 0, 0]
    },
    axisLine: {
      lineStyle: {
        color: '#ade6ee'
      }
    },
    splitLine: {
      show: false
    },
    axisLabel: {
      textStyle: {
        color: '#ade6ee'
      }
    },
    boundaryGap: false
  },
  yAxis: {
    name: 'Counts',
    nameTextStyle: {
      color: '#8FD4F8',
      fontSize: 16
    },
    axisLine: {
      show: true,
      lineStyle: {
        color: '#ade6ee'
      }
    },
    splitLine: {
      show: true,
      lineStyle: {
        color: 'rgba(173, 230, 238, .2)'
      }
    },
    axisLabel: {
      textStyle: {
        color: '#ade6ee'
      }
    }
  },
  series: []
}

// 缩略图配置
const thumbnailOption = {
  grid: {
    top: 0,
    left: 5,
    right: 5,
    bottom: 0
  },
  xAxis: {
    type: 'category',
    axisLine: {
      show: false
    },
    splitLine: {
      show: false
    },
    axisLabel: {
      show: false
    }
  },
  yAxis: {
    axisLine: {
      show: false
    },
    splitLine: {
      show: false
    },
    axisLabel: {
      show: false
    }
  },
  series: []
}

export default {
  props: {
    sample: {
      type: Object
    }
  },
  components: {
    CustomChart,
    PopOverWithIcon,
    DetailedInfomation,
    QcFlags,
    GraphAssistance,
    NuclearLibrary,
    ButtonWithSwitchIcon
  },
  data() {
    return {
      isLoading: false,
      option: initialOption,
      thumbnailOption,

      detailedInfomation: [],
      qcFlags: [],
      graphAssistance: {},

      channelPeakGroup: [],
      energyPeakGroup: []
    }
  },
  created() {
    this.option.title.text = '{a|Channel:0} {a|Energy:0} {a|Counts:0} {a|Detectability:0}'
  },
  methods: {
    async getSampleDetail() {
      const { dbName, sampleId } = this.sample
      try {
        this.isLoading = true
        this.option.series = []

        // const { success, result, message } = await getAction('/gamma/gammaByDB', {
        //   dbName,
        //   sampleId
        // })
        const { success, result, message } = Response
        if (success) {
          this.isLoading = false

          const {
            dead_time,
            live_time,
            real_time,
            start_time,

            DetailedInformation,
            QCFlag,

            allData,

            shadowChannelChart,
            shadowEnergyChart,

            shapeChannelData,
            shapeEnergyData
          } = result

          console.log('%c [  ]-258', 'font-size:13px; background:pink; color:#bf2c9f;', result)

          this.detailedInfomation = DetailedInformation
          this.qcFlags = QCFlag

          const channelPeakGroup = allData.filter(item => item.name == 'Peak' && item.group == 'channel')
          const energyPeakGroup = allData.filter(item => item.name == 'Peak' && item.group == 'energy')

          // 保存Peak Line
          this.channelPeakGroup = channelPeakGroup
          this.energyPeakGroup = energyPeakGroup

          // 保存 Spectrum Line
          this.shadowChannelChart = shadowChannelChart
          this.shadowEnergyChart = shadowEnergyChart

          // 保存 基线控制点
          this.shapeChannelData = shapeChannelData
          this.shapeEnergyData = shapeEnergyData

          // 推入Spectrum Line
          this.option.series.push({
            name: 'Spectrum',
            type: 'line',
            data: shadowChannelChart.pointlist.map(({ x, y }) => [x, y]),
            itemStyle: {
              color: `rgb(${shadowChannelChart.color})`
            },
            lineStyle: {
              width: 1
            },
            symbol: 'none',
            symbolSize: 1,
            emphasis: {
              disabled: true
            },
            markLine: {
              silent: true,
              symbol: 'none',
              label: {
                show: false
              },
              lineStyle: {
                color: 'red',
                width: 2
              },
              data: [{ xAxis: -1 }]
            },
            zlevel: 0
          })

          this.thumbnailOption.series.push({
            name: 'Spectrum',
            type: 'line',
            data: shadowChannelChart.pointlist.map(({ x, y }) => [x, y]),
            itemStyle: {
              color: `rgb(${shadowChannelChart.color})`
            },
            lineStyle: {
              width: 1
            },
            symbol: 'none',
            symbolSize: 1,
            emphasis: {
              disabled: true
            },
            markLine: {
              silent: true,
              symbol: 'none',
              label: {
                show: false
              },
              lineStyle: {
                color: 'red',
                width: 2
              },
              data: [{ xAxis: -1 }]
            },
            zlevel: 0
          })

          // 推入Scac
          this.option.series.push({
            name: 'Scac',
            type: 'line',
            data: [].map(({ x, y }) => [x, y]),
            itemStyle: {
              color: `rgb(${shadowChannelChart.color})`
            },
            lineStyle: {
              width: 1
            },
            symbol: 'none',
            emphasis: {
              disabled: true
            }
          })

          // 推入基线控制点
          this.option.series.push({
            name: 'BaseLine_Ctrl_Point',
            type: 'scatter',
            data: shapeChannelData.map(({ size, color, point: { x, y } }) => {
              return {
                value: [x, y],
                itemStyle: {
                  color: 'transparent',
                  borderColor: color,
                  borderWidth: size / 2
                }
              }
            }),
            emphasis: {
              disabled: true
            },
            z: 3
          })

          // 推入Peak Line
          channelPeakGroup.forEach((item, index) => {
            this.option.series.push({
              name: `Peak_${index}`,
              type: 'line',
              data: item.pointlist.map(({ x, y }) => [x, y]),
              itemStyle: {
                color: `rgb(${item.color})`
              },
              lineStyle: {
                width: 1
              },
              symbol: 'none'
            })
          })
        } else {
          this.$message.error(message)
        }
      } catch (error) {
        console.error(error)
      }
    },

    // Graph Assistance 操作
    handleGraphAssistanceChange({ type, label, value }) {
      // 类型变化
      if (type == 'labelChange') {
        switch (label) {
          case 'Linear':
            break
          case 'Log10':
            break
          case 'Channel':
            this.option.xAxis.name = label
            break
          case 'Energy':
            this.option.xAxis.name = label
            break
          case 'Lines':
            this.option.series[0].type = 'line'
            this.option.series[0].symbol = 'none'
            break
          case 'Scatter':
            this.option.series[0].type = 'scatter'
            this.option.series[0].symbol = 'circle'
            break
        }
      }
      // 值变化
      else if (type == 'valueChange') {
        console.log('%c [  ]-315', 'font-size:13px; background:pink; color:#bf2c9f;', label, value)
        this.graphAssistance[label] = value

        switch (label) {
          case 'Cursor':
            // 显示红色竖线
            if (value) {
              this.option.series[0].markLine.lineStyle.width = 2
            } else {
              this.option.series[0].markLine.lineStyle.width = 0
            }
            break
        }
      }
    },

    // 点击图表，设置红线
    handleChartClick(param) {
      const { offsetX, offsetY } = param
      const point = getXAxisAndYAxisByPosition(this.$refs.chartRef.getChartInstance(), offsetX, offsetY)
      if (point) {
        const xAxis = parseInt(point[0].toFixed())
        this.option.series[0].markLine.data[0].xAxis = xAxis
      }
    },

    resize() {
      this.$refs.chartRef.resize()
      this.$refs.thumbnailChartRef.resize()
    },

    // peak info 点击左右方向
    handlePeakInfoChange(direction) {
      this.moveMarkLine(direction)
    },

    /**
     * 向某一个方向移动标记线
     * @param { 'left'| 'right' } direction
     */
    moveMarkLine(direction) {
      const prevAxis = this.option.series[0].markLine.data[0].xAxis

      // 获取每一段 Channel 中的最大值
      const maxXAxises = this.channelPeakGroup.map(item => {
        const allY = item.pointlist.map(item => item.y)
        const max = item.pointlist.find(point => point.y == Math.max(...allY))
        return max.x
      })
      if (direction == 'right') {
        // 找到第一个比prevAxis大的xAxis
        const find = maxXAxises.find(xAxis => xAxis > prevAxis)
        if (find) {
          this.option.series[0].markLine.data[0].xAxis = find
        }
      } else if (direction == 'left') {
        // 找到第一个比prevAxis小的xAxis
        const find = maxXAxises.reverse().find(xAxis => xAxis < prevAxis)
        if (find) {
          this.option.series[0].markLine.data[0].xAxis = find
        }
      }
    }
  },
  watch: {
    sample: {
      handler() {
        this.getSampleDetail()
      },
      immediate: true
    }
  }
}
</script>

<style lang="less" scoped>
.gamma-analysis {
  height: 100%;

  .ant-spin-nested-loading {
    height: 100%;

    ::v-deep {
      .ant-spin-container {
        height: 100%;
      }
    }
  }

  &-main {
    height: calc(100% - 51px);
    display: flex;
    overflow: auto hidden;
    position: relative;
  }

  &-chart {
    width: 100%;
    height: 100%;
    position: relative;
  }

  &-thumbnail {
    position: absolute;
    top: 50px;
    right: 10px;
    width: 500px;
    height: 20%;
    background-color: #153e44;
  }
}
</style>
