<template>
  <custom-modal v-model="visible" :width="1280" title="Load From Database" class="load-from-db-modal">
    <search-form ref="searchFormRef" :items="formItems" v-model="queryParam">
      <a-space slot="additional">
        <a-button @click="handleReset">Reset</a-button>
        <a-button type="primary" @click="searchQuery">Search</a-button>
      </a-space>
    </search-form>
    <custom-table
      size="middle"
      rowKey="sampleId"
      :columns="columns"
      :list="dataSource"
      :pagination="ipagination"
      :loading="loading"
      @change="handleTableChange"
      :selectedRowKeys.sync="selectedRowKeys"
      :selectionRows.sync="selectionRows"
      :multiple="true"
      :scroll="{ y: 'calc(100vh - 550px)' }"
    >
    </custom-table>
    <!-- 底部操作栏 -->
    <template slot="custom-footer">
      <a-space>
        <a-radio-group v-model="queryParam.dbName">
          <a-radio value="auto">From Auto DB</a-radio>
          <a-radio value="man">From Interactive DB</a-radio>
        </a-radio-group>
        <a-button type="primary" @click="handleLoad">Load</a-button>
      </a-space>
    </template>
  </custom-modal>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction } from '../../../../api/manage'
import moment from 'moment'
import { cloneDeep } from 'lodash'

const columns = [
  {
    title: 'SampleID',
    align: 'left',
    dataIndex: 'sampleId',
  },
  {
    title: 'Station',
    align: 'left',
    dataIndex: 'stationName',
  },
  {
    title: 'Detector',
    align: 'left',
    dataIndex: 'detectorsName',
    width: 130,
  },
  {
    title: 'Sample',
    align: 'left',
    dataIndex: 'sampleType',
  },
  {
    title: 'DataType',
    align: 'left',
    dataIndex: 'dataType',
  },
  {
    title: 'Qualifier',
    align: 'left',
    dataIndex: 'spectralQualifie',
  },
  {
    title: 'Col.Stop',
    align: 'left',
    dataIndex: 'collectStop',
    sorter: true,
    width: 170,
  },
  {
    title: 'Acq.Start',
    align: 'left',
    dataIndex: 'acquisitionStart',
    width: 170,
  },
  {
    title: 'Acq.real',
    align: 'left',
    dataIndex: 'acquisitionRealSec',
  },
  {
    title: 'Acq.live',
    align: 'left',
    dataIndex: 'acquisitionLiveSec',
  },
  {
    title: 'Status',
    align: 'left',
    dataIndex: 'status',
  },
]

export default {
  props: {
    value: {
      type: Boolean,
    },
  },
  mixins: [JeecgListMixin],
  data() {
    this.columns = columns
    this.disableMixinCreated = true
    return {
      queryParam: {
        menuTypes: 'G,B',
        sampleType: '',
        startDate: moment().add(-7, 'd').format('YYYY-MM-DD'),
        endDate: moment().format('YYYY-MM-DD'),
        dbName: 'auto',
        spectralQualifie: 'FULL',
      },
      selectedRowKeys: [],
      selectionRows: [],

      stationList: [],
      detectorList: [],
      url: {
        list: '/spectrumAnalysis/getDBSpectrumList',
      },
      sampleTypeOption: [
        {
          label: 'P',
          value: 'P',
        },
        {
          label: 'B',
          value: 'B',
        },
        {
          label: 'G',
          value: 'G',
        },
      ],
    }
  },
  created() {
    this.getStationAndDetectorList(this.queryParam.menuTypes)
  },
  methods: {
    loadData(arg) {
      const params = this.getQueryParams() //查询条件
      const { startDate, endDate, menuTypes } = params
      if (!menuTypes) {
        this.$message.warn('Please Select SampleType First')
        return
      }

      if (!startDate || !endDate) {
        this.$message.warn(`'From' Date And 'To' Date Cannot Be Null`)
        return
      }

      if (moment(startDate).isAfter(moment(endDate))) {
        this.$message.warn(`'From' Date Cannot Be Late Than 'To' Date`)
        return
      }

      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }

      params.AllUsers = this.allUsersValue
      params.CollectStopB = this.collectStopValue
      params.AcqStartB = this.acqStartValue
      delete params.checkboxGroup

      this.onClearSelected()

      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            const result = res.result.records || res.result
            result.forEach((item) => {
              const fileName = item.inputFileName
              if (fileName) {
                const arr = fileName.split('/')
                item.inputFileName = arr[arr.length - 1]
              }
            })

            this.dataSource = result

            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * 加载
     */
    async handleLoad() {
      if (!this.selectedRowKeys.length) {
        this.$message.warn('Please Select Sample To Load')
        return
      }
      this.selectedRowKeys = []
      this.visible = false
      this.$emit('loadSample', cloneDeep(this.selectionRows))
    },

    // 获取台站和探测器列表
    async getStationAndDetectorList(value) {
      try {
        this.stationList = []
        this.detectorList = []

        const { success, result, message } = await getAction('/spectrumAnalysis/getDBSearchList', {
          menuTypes: value,
          dbName: this.queryParam.dbName,
          AllUsers: this.allUsersValue,
        })
        if (success) {
          this.stationList = result.stationCode.map((item) => ({ label: item, value: item }))
          this.detectorList = result.detectorCode.map((item) => ({ label: item, value: item }))
        } else {
          this.$message.error(message)
        }
      } catch (error) {
        console.error(error)
      }
    },

    // 重置搜索栏
    handleReset() {
      this.$refs.searchFormRef.$refs.form.resetFields()
    },

    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      },
    },
    formItems() {
      return [
        {
          label: 'SampleType',
          type: 'custom-select',
          name: 'menuTypes',
          props: {
            options: [
              {
                label: 'All',
                value: 'G,B',
              },
              {
                label: 'Gamma',
                value: 'G',
              },
              {
                label: 'Beta',
                value: 'B',
              },
            ],
            allowClear: true,
          },
          style: {
            width: '18%',
          },
          on: {
            change: (event) => {
              console.log('event', event)
              if (!event) {
                this.stationList = []
                this.detectorList = []
                return
              }
              let arr_B = [
                {
                  label: 'B',
                  value: 'B',
                },
              ]
              let arr_G = [
                {
                  label: 'P',
                  value: 'P',
                },
                {
                  label: 'G',
                  value: 'G',
                },
              ]
              let arr_A = [
                {
                  label: 'P',
                  value: 'P',
                },
                {
                  label: 'B',
                  value: 'B',
                },
                {
                  label: 'G',
                  value: 'G',
                },
              ]
              if (event == 'B') {
                this.sampleTypeOption = arr_B
                this.$nextTick(() => {
                  this.queryParam.sampleType = 'B'
                })
              } else if (event == 'G') {
                this.sampleTypeOption = arr_G
                this.$nextTick(() => {
                  this.queryParam.sampleType = 'P'
                })
              } else {
                this.sampleTypeOption = arr_A
                this.$nextTick(() => {
                  this.queryParam.sampleType = ''
                })
              }
              this.getStationAndDetectorList(event)
            },
          },
        },
        {
          label: 'Station',
          type: 'custom-select',
          name: 'stationName',
          props: {
            options: this.stationList,
            showSearch: true,
            filterOption: this.filterOption,
            allowClear: true,
          },
          style: {
            width: '19%',
          },
        },
        {
          label: 'Detector',
          type: 'custom-select',
          name: 'detectorsName',
          props: {
            options: this.detectorList,
            showSearch: true,
            filterOption: this.filterOption,
            allowClear: true,
          },
          style: {
            width: '19%',
          },
        },
        {
          label: 'Sample',
          type: 'custom-select',
          name: 'sampleType',
          props: {
            options: this.sampleTypeOption,
            allowClear: true,
          },
          style: {
            width: '14%',
          },
        },
        {
          label: 'DataType',
          type: 'custom-select',
          name: 'dataType',
          props: {
            options: [
              {
                label: 'S',
                value: 'S',
              },
              {
                label: 'G',
                value: 'G',
              },
              {
                label: 'D',
                value: 'D',
              },
              {
                label: 'Q',
                value: 'Q',
              },
              {
                label: 'B',
                value: 'B',
              },
              {
                label: 'C',
                value: 'C',
              },
            ],
            allowClear: true,
          },
          style: {
            width: '14%',
          },
        },
        {
          label: 'Qualifier',
          type: 'custom-select',
          name: 'spectralQualifie',
          props: {
            options: [
              {
                label: 'FULL',
                value: 'FULL',
              },
              {
                label: 'PREL',
                value: 'PREL',
              },
            ],
            allowClear: true,
          },
          style: {
            width: '16%',
            paddingRight: 0,
          },
        },
        {
          label: 'SampleID',
          type: 'a-input',
          name: 'sampleId',
          props: {
            allowClear: true,
          },
          style: {
            width: '207px',
          },
        },
        {
          label: '',
          type: 'a-checkbox-group',
          name: 'checkboxGroup',
          props: {
            options: [
              { label: 'All User', value: 'AllUsers' },
              { label: 'Collect Stop', value: 'CollectStopB' },
              { label: 'Acq.Start', value: 'AcqStartB' },
            ],
          },
          style: {
            width: '305px',
            paddingRight: 0,
          },
        },
        {
          label: 'From',
          type: 'custom-date-picker',
          name: 'startDate',
          props: {
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            style: {
              minWidth: 'auto',
            },
          },
          style: {
            width: '16%',
          },
        },
        {
          label: 'To',
          type: 'custom-date-picker',
          name: 'endDate',
          props: {
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            style: {
              minWidth: 'auto',
            },
          },
          style: {
            paddingRight: 0,
            marginRight: '8px',
            width: '13%',
          },
        },
        {
          label: 'Status',
          type: 'custom-select',
          name: 'status',
          props: {
            options: [
              {
                label: 'U',
                value: 'U',
              },
              {
                label: 'A',
                value: 'A',
              },
              {
                label: 'P',
                value: 'P',
              },
              {
                label: 'R',
                value: 'R',
              },
              {
                label: 'F',
                value: 'F',
              },
            ],
            allowClear: true,
          },
          style: {
            width: '14%',

            marginRight: '10px',
          },
        },
      ]
    },

    allUsersValue() {
      const checkboxGroup = this.queryParam.checkboxGroup
      return !!(checkboxGroup && checkboxGroup.includes('AllUsers'))
    },

    collectStopValue() {
      const checkboxGroup = this.queryParam.checkboxGroup
      return !!(checkboxGroup && checkboxGroup.includes('CollectStopB'))
    },

    acqStartValue() {
      const checkboxGroup = this.queryParam.checkboxGroup
      return !!(checkboxGroup && checkboxGroup.includes('AcqStartB'))
    },
  },
  watch: {
    // All User 变化时重新获取station 和detector
    allUsersValue() {
      if (this.queryParam.menuTypes) {
        this.stationList = []
        this.detectorList = []
        this.getStationAndDetectorList(this.queryParam.menuTypes)
      }
    },
  },
}
</script>

<style lang="less" scoped>
.load-from-db-modal {
  ::v-deep {
    .search-btn {
      display: none;
    }
  }
}
</style>
