<template>
  <div class="view-table-content">
    <div class="view-dataSpecies-left">
      <MenuTree :currentNodeKey="currentNodeKey" nodeKey="id" :treedata="menuTreeData" @TreeNodeclick="treeNodeClick" v-bind="treeObj"> </MenuTree>
    </div>
    <div class="view-dataSpecies-right">
      <div class="view-dataType-title">
        <div class="view-dataType-title-btn"></div>
        <div class="view-dataType-title-search">
          <el-input placeholder="请输入架次号" v-model="keyWordData" class="input1">
            <el-button slot="append" icon="el-icon-search" @click="searchClick"></el-button>
          </el-input>
        </div>
      </div>
      <div class="view-dataType-table">
        <LTable ref="table" @selection-change="selection" :defaultFetch="false" :fetch="fetch" :columns="columns" :dataSource="tableData" :options="options" :pagination="tableRequset"></LTable>
      </div>
      <!-- 警告列表对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :before-close="handleClose" width="1200px">
        <el-dialog width="80%" title="飞参数据曲线" :visible.sync="innerVisible" :before-close="innerDialogClose" append-to-body>
          <div style="width: 100%; position: relative; color: #fff">
            <el-radio-group class="isFalseAlarm" v-model="isFalseAlarm" size="small">
              <el-radio-button label="0">实警</el-radio-button>
              <el-radio-button label="1">虚警</el-radio-button>
            </el-radio-group>
          </div>
          <PlayBackChart :chartData="chartData" />
          <span slot="footer" class="dialog-footer">
            <el-button @click="innerDialogClose">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
          </span>
        </el-dialog>
        <el-form ref="airForm" :inline="true" :model="airForm" label-width="80px" disabled>
          <el-form-item label="编目" prop="aircraftId">
            <el-select v-model="airForm.aircraftId">
              <el-option v-for="item in aircaftCatalogAll" :key="item.aircaftCatalogId" :label="item.aircaftCatalogCode" :value="item.aircaftCatalogId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="架次" prop="sortieNo">
            <el-input v-model="airForm.sortieNo" />
          </el-form-item>
          <el-form-item label="飞行时间" prop="flightDate">
            <el-input v-model="airForm.flightDate" />
          </el-form-item>
        </el-form>
        <LTable ref="warningTable" @selection-change="selection" :defaultFetch="false" :columns="warningColumns" :dataSource="warningTableData" :options="warningOptions" :pagination="warningTableRequset"></LTable>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getDataImport } from '@/api/als/dataImport'
import { getCurveData, getWarning, updateWarning } from '@/api/als/warning'
import { getAircaftCatalogTree } from '@/api/als/sideTree'
import { getAircaftCatalogAll } from '@/api/als/aircraft'
import PlayBackChart from '@/views/als/components/Charts/playBackChart.vue'
import { deepClone, debounce } from '@/utils/index'

export default {
  name: 'FalseAlarm',
  components: { PlayBackChart },
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      innerVisible: false,
      keyWordData: '',
      aircaftModelIdList: [],
      currentNodeKey: '',
      currentNode: {},
      menuTreeData: [],
      treeObj: {
        title: '所属机种',
        activityheight: '275px',
        searchIcon: false,
        configure: {
          children: 'children',
          label: 'label'
        }
      },
      typeTree: {
        children: 'children',
        label: 'label'
      },
      searchValue: '',
      columns: [
        {
          prop: 'aircraftId',
          label: '编目',
          render: (h, params) => {
            const matchedItem = this.aircaftCatalogAll.find((item) => params.row.aircraftId.trim() === item.aircaftCatalogId.trim())
            if (matchedItem) {
              return h('span', matchedItem.aircaftCatalogCode)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          prop: 'sortieNo',
          label: '架次号'
        },
        {
          prop: 'flightDate',
          label: '飞行时间'
        },
        {
          prop: 'source',
          label: '数据源',
          render: (h, params) => {
            if (params.row.source == 1) {
              return h('span', { class: 'success-state' }, '飞参数据')
            } else {
              return h('span', { class: 'success-state' }, 'MDC数据')
            }
          }
        },
        {
          button: true,
          label: '操作',
          width: '240px',
          group: [
            {
              name: '查看警告列表',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.checkWarningList(row)
              }
            }
          ]
        }
      ],
      options: {
        stripe: true, // 斑马纹
        mutiSelect: true, // 多选框
        index: false, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: 'calc(100vh - 300px)'
      },
      tableCheckItems: [],
      tableData: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      warningColumns: [
        {
          prop: 'code',
          label: 'HMC码'
        },
        {
          prop: 'name',
          label: '名称'
        },
        {
          prop: 'describe',
          label: '描述'
        },
        {
          prop: 'status',
          label: '是否虚警',
          render: (h, params) => {
            if (params.row.status == '0') {
              return h('span', { class: 'warning-state' }, '实警')
            } else {
              return h('span', { class: 'success-state' }, '虚警')
            }
          }
        },
        {
          button: true,
          label: '操作',
          width: '240px',
          group: [
            {
              name: '查看',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.checkCurve(row)
              }
            }
          ]
        }
      ],
      warningOptions: {
        stripe: true, // 斑马纹
        mutiSelect: true, // 多选框
        index: false, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: 'calc(100vh - 600px)'
      },
      warningTableCheckItems: [],
      warningTableData: [],
      warningTableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftCatalogAll: [],
      chartData: {
        title: '',
        legendData: [],
        xAxisData: [],
        yAxisData: [],
        seriesData: []
      },
      form: {
        id: '',
        sortieNo: '',
        aircraftId: '',
        code: '',
        name: '',
        describe: [],
        status: ''
      },
      airForm: {
        aircraftId: '',
        sortieNo: '',
        flightDate: ''
      },
      isFalseAlarm: '0',
      currentSortieNo: ''
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  // computed: {
  //   falseAlarmText() {
  //     console.log('this.isFalseAlarm', this.isFalseAlarm)
  //     return this.isFalseAlarm === '1' ? '实警' : '虚警'
  //   }
  // },
  mounted() {
    this.getAircaftCatalogTreeAPI()
  },
  methods: {
    async getAircaftCatalogTreeAPI(params) {
      try {
        const { data } = await getAircaftCatalogTree(params)
        this.menuTreeData = data
        const getAircaftCatalogAllParams = {
          keyWord: '',
          aircaftModelIdList: []
        }
        const { data: data2 } = await getAircaftCatalogAll(getAircaftCatalogAllParams)
        this.aircaftCatalogAll = data2
        if (data.length) {
          this.currentNodeKey = data[0].id
          this.currentNode = data[0]
          this.aircaftModelIdList = this.getTreeLeafData(data[0]?.children)
            .map((e) => e.id)
            .toString()
          this.getDataImportAPI({ aircraftId: this.aircaftModelIdList })
        }
      } catch (error) {}
    },

    getTreeLeafData(list) {
      const newArr = []
      function getLeaf(data, arr) {
        data.forEach((e) => {
          if (e.type === 2) {
            arr.push(e)
          }
          if (e.children.length) {
            getLeaf(e.children, arr)
          }
        })
      }
      getLeaf(list, newArr)
      return newArr
    },

    async getDataImportAPI(params) {
      if (this.$refs.table) this.$refs.table.clearSelection()
      const { keyWord } = this
      const { pageSize, pageIndex } = this.tableRequset
      const {
        data: { list, total }
      } = await getDataImport({ pageSize, pageNum: pageIndex, ...params, source: 1 })
      this.tableData = list
      this.tableRequset.total = total
    },

    fetch() {
      this.getDataImportAPI({ aircraftId: this.aircaftModelIdList })
    },

    async searchClick() {
      this.getDataImportAPI({ aircraftId: this.aircaftModelIdList, sortieNo: this.keyWordData })
    },

    treeNodeClick(data) {
      this.$refs.table.clearSelection()
      this.currentNodeKey = data.id
      this.currentNode = data
      this.aircaftModelIdList = this.getTreeLeafData(data.children.length ? data.children : [data])
        .map((e) => e.id)
        .toString()
      if (!this.aircaftModelIdList) {
        this.aircaftModelIdList = '#'
      }
      this.getDataImportAPI({ aircraftId: this.aircaftModelIdList })
    },

    openDialog() {
      this.dialogTitle = '警告列表'
      this.dialogVisible = true
    },

    handleClose() {
      this.dialogVisible = false
      this.warningTableData = []
      this.currentSortieNo = ''
      this.airForm = {
        aircraftId: '',
        sortieNo: '',
        flightDate: ''
      }
    },

    innerDialogClose() {
      this.innerVisible = false
      this.chartData = {
        title: '',
        legendData: [],
        xAxisData: [],
        yAxisData: [],
        seriesData: []
      }
      this.isFalseAlarm = false
    },

    submit() {
      this.form.status = this.isFalseAlarm
      this.updateWarningAPI()
    },

    async updateWarningAPI() {
      try {
        const { code } = await updateWarning({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.innerDialogClose()
          this.getWarningAPI({ sortieNo: this.currentSortieNo })
        }
      } catch (error) {}
    },

    selection(val) {
      this.tableCheckItems = val
    },

    checkWarningList(row) {
      this.currentSortieNo = this.airForm.sortieNo = row.sortieNo
      this.airForm.aircraftId = row.aircraftId
      this.airForm.flightDate = row.flightDate
      this.getWarningAPI({ sortieNo: this.currentSortieNo })
      this.openDialog()
    },

    async getWarningAPI(params) {
      if (this.$refs.warningTable) this.$refs.warningTable.clearSelection()
      const { pageSize, pageIndex } = this.warningTableRequset
      const {
        data: { list, total }
      } = await getWarning({ pageSize, pageNum: pageIndex, ...params })
      this.warningTableData = list
      this.warningTableRequset.total = total
    },

    async checkCurve(row) {
      this.isFalseAlarm = row.status
      this.form = deepClone(row)
      const { data } = await getCurveData(row.code, row.sortieNo)
      this.getResultData(data)
    },

    getResultData(data) {
      this.chartData = {
        title: '',
        legendData: [],
        xAxisData: [],
        yAxisData: [],
        seriesData: []
      }
      // const { contentData, headData } = this.handleResultData(JSON.parse(data))
      const contentData = JSON.parse(data)
      const headData = Object.keys(contentData)
      this.chartData.legendData = headData
      for (var key in contentData) {
        if (key === '时间') {
          this.chartData.xAxisData = contentData['时间']
        } else {
          this.chartData.seriesData.push({
            name: key,
            type: 'line',
            data: contentData[key],
            connectNulls: true
          })
        }
      }
      this.innerVisible = true
    },

    handleResultData(resultData) {
      console.log('resultData', resultData)
      const headData = Object.keys(resultData)
      const contentData = {}
      headData.forEach((headItem) => {
        contentData[headItem] = []
      })
      resultData.forEach((item) => {
        for (var key in item) {
          contentData[key].push(item[key])
        }
      })
      return { contentData, headData }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../index.scss';
.isFalseAlarm {
  position: absolute;
  right: 20px;
  color: #fff;
  z-index: 9999;
}
</style>
