<template>
  <div class="beta-gamma-analysis">
    <a-spin :spinning="isLoading">
      <!-- 二级交互栏 -->
      <div class="spectrum-analysis-sub-operators">
        <pop-over-with-icon placement="bottomLeft">
          Detailed-Information
          <beta-gamma-detailed-infomation slot="content" :data="spectrumData" />
        </pop-over-with-icon>
        <custom-select
          v-model="spectraType"
          :options="SampleType"
          @change="changeChartByType"
          style="width: 246px"
          class="sample-select"
        ></custom-select>
        <div class="spectrum-analysis-sub-operators-roi" v-for="(_, index) in 4" :key="index">
          <div class="spectrum-analysis-sub-operators-roi-name" :style="{ color: ROIColors[index] }">
            ROI{{ index + 1 }}
          </div>
          <a-input-group>
            <a-input
              type="number"
              v-model="roiParamList[index][0]"
              class="spectrum-analysis-sub-operators-roi-input"
              placeholder="Beta1"
            />
            <a-input class="spectrum-analysis-sub-operators-roi-split site-input-split" placeholder="," disabled />
            <a-input
              type="number"
              v-model="roiParamList[index][1]"
              class="spectrum-analysis-sub-operators-roi-input site-input-right"
              placeholder="Beta2"
            />
          </a-input-group>
        </div>
        <div class="spectrum-analysis-sub-operators-button" @click="reDrawRectOri">Update</div>
      </div>
      <!-- 二级交互栏结束 -->

      <!-- 主体部分 -->
      <div class="beta-gamma-analysis-main">
        <!-- 左侧图表部分 -->
        <div class="beta-gamma-analysis-main-left">
          <beta-gamma-chart-container>
            <template slot="title"> Beta-Gamma Spectrum: {{ currSpectrum }} </template>
            <beta-gamma-spectrum
              ref="betaChartRef"
              :betaEnergyData="betaEnergyData"
              :gammaEnergyData="gammaEnergyData"
              :histogramDataList="histogramDataList"
              :boundary="boundaryList"
              :isLoading.sync="isLoading"
              @refreshRoi="refreshRoi"
              @boundaryChange="handleBoundaryChange"
            />
          </beta-gamma-chart-container>
        </div>
        <!-- 左侧图表结束 -->
        <!-- 右侧开始 -->
        <div class="beta-gamma-analysis-main-right">
          <beta-gamma-chart-container>
            <template slot="title"> ROI LIMITS </template>
            <roi-limits
              ref="RoiChartRef"
              :ROILists="ROILists"
              :ROIAnalyzeLists="ROIAnalyzeLists"
              :gammaEnergyData="gammaEnergyData"
            />
          </beta-gamma-chart-container>
          <!-- 底部显示 -->
          <div class="beta-gamma-analysis-main-bottom">
            <div class="beta-gamma-analysis-main-bottom-left">
              <beta-gamma-chart-container>
                <template slot="title"> Result display </template>
                <result-display-beta :data="resultDisplay" @sendFlag="handleGetFlag"></result-display-beta>
              </beta-gamma-chart-container>
            </div>
          </div>
          <!-- 底部显示结束 -->
        </div>
        <!-- 右侧结束 -->
      </div>
      <!-- 主体部分结束 -->
    </a-spin>
  </div>
</template>

<script>
import PopOverWithIcon from './components/SubOperators/PopOverWithIcon.vue'
import BetaGammaDetailedInfomation from './components/SubOperators/BetaGammaDetailedInfomation.vue'
import BetaGammaQcFlags from './components/SubOperators/BetaGammaQcFlags.vue'
import CustomSelect from '@/components/CustomSelect/index.vue'
import BetaGammaChartContainer from './components/BetaGammaChartContainer.vue'
import ResultDisplayBeta from './components/ResultDisplay-Beta.vue'
import BetaGammaSpectrum from './components/BetaGammaSpectrum.vue'
import RoiLimits from './components/RoiLimits/RoiLimits.vue'
import RoiParam from './components/RoiParam.vue'
import axios from 'axios'
import store from '@/store/'
import { getAction, postAction, deleteAction } from '../../api/manage'
import { addSampleData, getSampleData, updateSampleData } from '@/utils/SampleStore'
import { cloneDeep } from 'lodash'

const SampleType = [
  {
    label: 'Sample Data',
    value: 'sample',
  },
  {
    label: 'DetBg Data',
    value: 'detBg',
  },
]

const InitialRoiParamList = new Array(4).fill([0, 0])

const ROIColors = ['#16d5e6', '#34a1ff', '#66e411', '#fdaa1a']

export default {
  components: {
    PopOverWithIcon,
    BetaGammaDetailedInfomation,
    BetaGammaQcFlags,
    CustomSelect,
    BetaGammaChartContainer,
    ResultDisplayBeta,
    BetaGammaSpectrum,
    RoiLimits,
    RoiParam,
  },
  props: {
    sample: {
      type: Object,
    },
  },
  data() {
    this.SampleType = SampleType
    this.ROIColors = ROIColors

    return {
      currSpectrum: 'Sample',
      isLoading: false,
      spectrumData: {}, // Detailed Infomation 信息
      spectraType: 'sample',
      histogramDataList: [],
      gammaEnergyData: [],
      betaEnergyData: [],
      ROILists: [],
      ROIAnalyzeLists: [],
      roiParamList: cloneDeep(InitialRoiParamList),
      boundaryList: [],
      sampleDetail: {},
      resultDisplay: [],
      timerStamp: Date.now(),
    }
  },
  watch: {
    sample: {
      async handler(newVal, oldVal) {
        const sampleData = getSampleData(newVal.inputFileName)
        if (sampleData) {
          const { data, from } = sampleData
          this.sampleDetail = data
          this.changeChartByType('sample')
          if (from == 'db') {
            this.sampleDetail = data
            this.emitGetFiles(data)
          }
          // this.ROIAnalyzeLists = data.ROIAnalyzeLists
        } else {
          if (newVal.sampleId) {
            this.getSampleDetail()
          } else {
            this.getSelfStationSampleDetail()
          }
        }
        await this.$nextTick()
        this.$refs.betaChartRef.handleUnzoom()
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    async getAnalyzeCurrentSpectrum() {
      try {
        const { inputFileName, detFileName } = this.sample
        const userId = store.getters.userInfo.id
        this.isLoading = true
        const { success, result, message } = await postAction(
          `/selfStation/Reprocessing?fileName=${inputFileName}&processKey=${userId}_${this.timerStamp}`
        )
        console.log(userId, success, result, message)
        if (success) {
          const _result = []
          _result.push(result.ROI1)
          _result.push(result.ROI2)
          _result.push(result.ROI3)
          _result.push(result.ROI4)
          this.ROIAnalyzeLists = _result
          updateSampleData({
            inputFileName,
            key: 'ROIAnalyzeLists',
            data: _result,
          })
        }
        let XeData = [
          {
            sampleId: null,
            idAnalysis: null,
            nuclideName: 'Xe131m',
            conc: -0.049,
            concErr: 0.04272,
            mdc: 0.14539,
            lc: 0.06362626536110005,
            nidFlag: 0,
            moddate: null,
            color: 'red',
          },
          {
            sampleId: null,
            idAnalysis: null,
            nuclideName: 'Xe133',
            conc: 0.07727,
            concErr: 0.0631,
            mdc: 0.23981,
            lc: 0.09916332268275692,
            nidFlag: 0,
            moddate: null,
            color: '#ffcc30',
          },
          {
            sampleId: null,
            idAnalysis: null,
            nuclideName: 'Xe133m',
            conc: -0.07186,
            concErr: 0.03596,
            mdc: 0.11014,
            lc: 0.044521536189968125,
            nidFlag: 0,
            moddate: null,
            color: 'red',
          },
          {
            sampleId: null,
            idAnalysis: null,
            nuclideName: 'Xe135',
            conc: 0.26636,
            concErr: 0.23193,
            mdc: 0.77578,
            lc: 0.3655879636569543,
            nidFlag: 0,
            moddate: null,
            color: '#ffcc30',
          },
        ]
        this.resultDisplay = XeData
        // this.$emit('reAnalyCurr', true, XeData)
      } catch (error) {
        console.error(error)
      } finally {
        this.isLoading = false
      }
    },
    getAnalyzeAllSpectrum() {
      let XeData = [
        {
          sampleId: null,
          idAnalysis: null,
          nuclideName: 'Xe131m',
          conc: -0.049,
          concErr: 0.04272,
          mdc: 0.14539,
          lc: 0.06362626536110005,
          nidFlag: 0,
          moddate: null,
          color: 'red',
        },
        {
          sampleId: null,
          idAnalysis: null,
          nuclideName: 'Xe133',
          conc: 0.07727,
          concErr: 0.0631,
          mdc: 0.23981,
          lc: 0.09916332268275692,
          nidFlag: 0,
          moddate: null,
          color: '#ffcc30',
        },
        {
          sampleId: null,
          idAnalysis: null,
          nuclideName: 'Xe133m',
          conc: -0.07186,
          concErr: 0.03596,
          mdc: 0.11014,
          lc: 0.044521536189968125,
          nidFlag: 0,
          moddate: null,
          color: 'red',
        },
        {
          sampleId: null,
          idAnalysis: null,
          nuclideName: 'Xe135',
          conc: 0.26636,
          concErr: 0.23193,
          mdc: 0.77578,
          lc: 0.3655879636569543,
          nidFlag: 0,
          moddate: null,
          color: '#ffcc30',
        },
      ]
      this.resultDisplay = XeData
      // this.$emit('reAnalyCurr', true, XeData)
    },
    refreshRoi(data) {
      console.log('%c [ 刷新 ]-303', 'font-size:13px; background:pink; color:#bf2c9f;', data)
    },
    reDrawRectOri() {
      // 更新
    },
    // async handleDetalSelfStationCache() {
    //   const { inputFileName } = this.sample
    //   let params = {
    //     sampleFileName: inputFileName,
    //   }
    //   try {
    //     const { success, result, message } = await deleteAction('/selfStation/deleteSelfStationCache', params)
    //   } catch (error) {
    //     console.error(error)
    //   }
    // },
    async getSelfStationSampleDetail() {
      this.spectraType = this.SampleType[0].value
      const { inputFileName, detFileName, qcFileName } = this.sample
      let params = {
        sampleFileName: inputFileName,
        detFileName: detFileName,
        qcFileName: qcFileName,
        // sampleFileName: 'ABC01_001-20240108_1405_S_FULL_40186.0.PHD',
        // detFileName: detFileName || 'ABC01_001-20240108_1327_D_FULL_381505.PHD',
      }
      try {
        this.isLoading = true
        this.cancelLastRequest()
        const cancelToken = this.createCancelToken()
        const { success, result, message } = await getAction('/selfStation/loadFromFile', params, cancelToken)
        if (success) {
          addSampleData({
            inputFileName,
            data: result,
            from: 'file',
          })
          this.sampleDetail = result
          this.changeChartByType('sample')
          this.isLoading = false
        } else {
          this.$message.error(message)
        }
      } catch (error) {
        console.error(error)
      }
    },
    changeChartByType(val) {
      if (val == 'sample') this.currSpectrum = 'Sample'
      if (val == 'detBg') this.currSpectrum = 'Det'
      this.roiParamList = cloneDeep(InitialRoiParamList)
      this.boundaryList = []
      this.ROILists = []
      const {
        spectrumData,
        betaEnergyData,
        gammaEnergyData,
        histogramDataList,
        ROIOneList,
        ROITwoList,
        ROIThreeList,
        ROIFourList,
        ROIOneStart,
        ROIOneStop,
        ROITwoStart,
        ROITwoStop,
        ROIThreeStart,
        ROIThreeStop,
        ROIFourStart,
        ROIFourStop,
      } = this.sampleDetail[this.spectraType]
      this.spectrumData = spectrumData
      this.histogramDataList = histogramDataList
      this.gammaEnergyData = gammaEnergyData
      this.betaEnergyData = betaEnergyData
      this.ROILists = [ROIOneList, ROITwoList, ROIThreeList, ROIFourList]

      this.boundaryList = [
        [ROIOneStart, ROIOneStop],
        [ROITwoStart, ROITwoStop],
        [ROIThreeStart, ROIThreeStop],
        [ROIFourStart, ROIFourStop],
      ]

      this.roiParamList = cloneDeep(this.boundaryList)
    },
    cancelLastRequest() {
      if (this._cancelToken && typeof this._cancelToken == 'function') {
        this._cancelToken()
      }
    },

    createCancelToken() {
      const cancelToken = new axios.CancelToken((c) => {
        this._cancelToken = c
      })
      return cancelToken
    },
    handleGetFlag(val, obj) {
      this.resultDisplay.forEach((item) => {
        if (item.nuclideName === obj.nuclideName) {
          item.nidFlag = val ? 1 : 0
        }
      })
    },

    resize() {},

    // 矩形框范围改变
    handleBoundaryChange(evt) {
      const { index, start, end } = evt
      this.$set(this.boundaryList, index, [start, end])
      this.$set(this.roiParamList, index, [start, end])
    },
  },
  destroyed() {
    this.cancelLastRequest()
  },
}
</script>

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

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

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

  .sample-select {
    ::v-deep {
      .ant-select-selection {
        background-color: transparent !important;
        color: #ade6ee;
      }
    }
  }

  &-main {
    height: calc(100% - 65px);
    display: flex;
    gap: 30px;
    overflow: auto hidden;

    &-left {
      flex: 768;
    }

    &-right {
      flex: 1068;
      .betagamma-chart {
        height: calc(100% - 200px);
      }
    }

    &-bottom {
      height: 194px;
      overflow: auto hidden;

      &-left {
        flex: 1;
      }

      &-right {
        flex: 1;
      }
    }
  }
}

// 二级操作栏开始
.spectrum-analysis-sub-operators {
  flex-shrink: 0;
  margin-bottom: 19px;
  display: flex;
  gap: 11px;
  flex-wrap: nowrap;
  overflow: auto;
  height: 46px;
  align-items: center;

  .pop-over-with-icon {
    height: 32px;
    flex-shrink: 0;

    &:nth-child(1) {
      width: 224px;
    }

    &:nth-child(3) {
      width: 125px;
    }
  }

  &-roi {
    display: flex;

    &-name {
      padding: 5px 10px;
    }

    ::v-deep {
      .ant-input-group {
        display: flex;
      }
    }

    &-input {
      width: 80px;
      text-align: center;
    }

    &-input:not(.site-input-right) {
      border-right: 0;
    }

    &-input.site-input-right {
      border-left: 0;
    }

    &-split {
      width: 5px;
      padding: 0;
      border-left: 0;
      border-right: 0;
      pointer-events: none;
      background-color: #03353f;
    }
  }
  &-button {
    text-align: center;
    height: 32px;
    line-height: 32px;
    min-width: 94px;
    padding: 0 10px;
    font-size: 16px;
    margin-left: 16px;
    background-color: #406979;
    cursor: pointer;
  }
}

// 二级操作栏结束
</style>