<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="handleUpdate">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"
              :isLoading.sync="isLoading"
              @boundaryChange="handleBoundaryChange"
              @open-modal="handleOpenModal"
            />
          </beta-gamma-chart-container>
        </div>
        <!-- 左侧图表结束 -->
        <!-- 右侧开始 -->
        <div class="beta-gamma-analysis-main-right">
          <beta-gamma-chart-container>
            <template slot="title"> Beta-Gated-Gamma-Spectrum </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>

    <!-- Gamma 按钮的弹窗 -->
    <gamma-modal ref="gammaModalRef" />
    <!-- Gamma 按钮的弹窗结束 -->
    <!-- Beta 按钮的弹窗 -->
    <beta-modal ref="betaModalRef" />
    <!-- Beta 按钮的弹窗结束 -->
  </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, putAction } from '../../api/manage'
import { addSampleData, getSampleData, updateSampleData } from '@/utils/SampleStore'
import { cloneDeep } from 'lodash'
import GammaModal from './components/Modals/SelfStation/GammaModal.vue'
import BetaModal from './components/Modals/SelfStation/BetaModal.vue'

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

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,
    GammaModal,
    BetaModal,
  },
  props: {
    sample: {
      type: Object,
    },
  },
  data() {
    this.SampleType = SampleType
    this.ROIColors = ROIColors

    return {
      currSpectrum: 'Sample',
      isLoading: false,
      spectrumData: {}, // Detailed Infomation 信息
      spectraType: 'sample',
      gammaEnergyData: [],
      betaEnergyData: [],
      ROILists: [],
      ROIAnalyzeLists: [],
      roiParamList: cloneDeep(InitialRoiParamList),
      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()
          }
          this.ROIAnalyzeLists = []
        }
      },
      immediate: true,
      deep: true,
    },
  },
  created() {
    this.$bus.$on('selfRefresh', this.handleRefresh)
    this.$bus.$on('selfAccept', this.handleAccept)
  },
  beforeDestroy() {
    this.cancelLastRequest()
    this.$bus.$on('selfRefresh', this.handleRefresh)
    this.$bus.$off('selfAccept', this.handleAccept)
  },
  methods: {
    async getAnalyzeCurrentSpectrum() {
      if (this.isLoading) {
        return
      }

      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,
          })
        } else {
          const arr = message.split('\n')
          this.$warning({
            title: 'Warning',
            content: () => arr.map((text) => <div>{text}</div>),
          })
        }
        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)
    },
    // 点击Update
    async handleUpdate() {
      const hasEmpty = this.roiParamList.some(
        ([startChannel, endChannel]) => (!startChannel && startChannel !== '0') || (!endChannel && endChannel !== '0')
      )
      if (hasEmpty) {
        this.$message.warning('Channel cannot be null')
        return
      }

      const hasNegative = this.roiParamList.some(([startChannel, endChannel]) => startChannel < 0 || endChannel < 0)
      if (hasNegative) {
        this.$message.warning('Channel cannot be negative')
        return
      }

      try {
        this.isLoading = true
        const { inputFileName } = this.sample

        const params = this.roiParamList.map(([startChannel, endChannel], index) => ({
          startChannel,
          endChannel,
          roiNum: index + 1,
        }))

        const formData = new FormData()
        formData.append('sampleFileName', inputFileName)
        formData.append('roiParams', JSON.stringify(params))

        const { success, result, message } = await putAction('/selfStation/updateROI', formData)
        if (success) {
          const {
            ROIOneList,
            ROITwoList,
            ROIThreeList,
            ROIFourList,
            ROIOneStart,
            ROIOneStop,
            ROITwoStart,
            ROITwoStop,
            ROIThreeStart,
            ROIThreeStop,
            ROIFourStart,
            ROIFourStop,
          } = result

          this.ROILists = [ROIOneList, ROITwoList, ROIThreeList, ROIFourList]

          this.$refs.betaChartRef.setBoundaryList([
            [ROIOneStart, ROIOneStop],
            [ROITwoStart, ROITwoStop],
            [ROIThreeStart, ROIThreeStop],
            [ROIFourStart, ROIFourStop],
          ])
        } else {
          this.isLoading = false
          this.$message.error(message)
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.isLoading = false
      }
    },
    // 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) {
      const currSampleDetail = this.sampleDetail[this.spectraType]
      if (!currSampleDetail) {
        this.$message.warning(`No ${this.spectraType} spectrum file!`)
        return
      }

      if (val == 'sample') {
        this.currSpectrum = 'Sample'
        this.ROIAnalyzeLists = this.sampleDetail.ROIAnalyzeLists
      } else {
        this.ROIAnalyzeLists = []
      }
      if (val == 'detBg') this.currSpectrum = 'Det'
      this.roiParamList = cloneDeep(InitialRoiParamList)
      this.ROILists = []
      const {
        spectrumData,
        betaEnergyData,
        gammaEnergyData,
        histogramDataList,
        ROIOneList,
        ROITwoList,
        ROIThreeList,
        ROIFourList,
        ROIOneStart,
        ROIOneStop,
        ROITwoStart,
        ROITwoStop,
        ROIThreeStart,
        ROIThreeStop,
        ROIFourStart,
        ROIFourStop,
      } = currSampleDetail

      this.spectrumData = spectrumData

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

      this.roiParamList = cloneDeep(boundaryList)
      this.$nextTick(() => {
        this.$refs.betaChartRef.setBoundaryList(boundaryList)
        this.$refs.betaChartRef.setData(histogramDataList)
      })
      this.gammaEnergyData = gammaEnergyData
      this.betaEnergyData = betaEnergyData
      this.ROILists = [ROIOneList, ROITwoList, ROIThreeList, ROIFourList]
      this.$bus.$emit('selfAnalyzeSampleTypeChange', val)
    },
    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.roiParamList, index, [start, end])
    },

    // 从分析工具刷新部分数据
    handleRefresh(data, index) {
      this.ROIAnalyzeLists[index] = this.$set(this.ROIAnalyzeLists, index, data)

      const { inputFileName } = this.sample
      updateSampleData({
        inputFileName,
        key: 'ROIAnalyzeLists',
        data: this.ROIAnalyzeLists,
      })
    },

    // 分析工具Accept时刷新部分数据
    handleAccept(data, index) {
      const {
        allData,
        peak,
        shadowChannelChart,
        shadowEnergyChart,
        shapeChannelData,
        shapeEnergyData,
        barChart,
        BaseCtrls,
      } = data

      this.ROIAnalyzeLists[index] = this.$set(this.ROIAnalyzeLists, index, {
        allData,
        peak,
        shadowChannelChart,
        shadowEnergyChart,
        shapeChannelData,
        shapeEnergyData,
        barChart,
        BaseCtrls,
      })

      const { inputFileName } = this.sample
      updateSampleData({
        inputFileName,
        key: 'ROIAnalyzeLists',
        data: this.ROIAnalyzeLists,
      })
    },

    // 打开Gamma或Beta弹窗
    handleOpenModal(index) {
      const currSampleDetail = this.sampleDetail[this.spectraType]
      if (!currSampleDetail) {
        this.$message.warning(`No ${this.spectraType} spectrum file!`)
        return
      }
      if (index == 0) {
        this.$refs.gammaModalRef.open(currSampleDetail.gSpectrum, currSampleDetail.gammaEnergyData)
      } else if (index == 1) {
        this.$refs.betaModalRef.open(currSampleDetail.bSpectrum, currSampleDetail.betaEnergyData)
      }
    },

    // 保存当前谱到db
    async saveCurrentToDB() {
      if (!this.ROIAnalyzeLists || !this.ROIAnalyzeLists.length) {
        throw new Error('Please Analyse Spectrum First')
      }
      const { inputFileName: fileName } = this.sample
      const { success, message, result } = await getAction('/selfStation/saveToDB', {
        fileName,
      })
      if (success) {
        const { DetailedInformation } = result
        this.spectrumData = DetailedInformation
        // 更新缓存中的DetailedInfomation数据
        updateSampleData({
          inputFileName: fileName,
          key: `${this.spectraType}.spectrumData`,
          data: DetailedInformation,
        })

        console.log('%c [  ]-617', 'font-size:13px; background:pink; color:#bf2c9f;', getSampleData(fileName))
      } else {
        throw new Error(message)
      }
    },
  },
}
</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>