<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="form" :inline="true" :model="form" label-width="80px" disabled>
          <el-form-item label="编目" prop="aircraftId">
            <el-select v-model="form.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="form.sortieNo" />
          </el-form-item>
          <el-form-item label="飞行时间" prop="flightDate">
            <el-input v-model="form.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>
      <el-dialog title="执行进度" :visible.sync="progressVisible" width="800px">
        <el-progress :text-inside="true" :stroke-width="24" :percentage="percentage" status="success"></el-progress>
      </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'
import { executeFalseAlarm, getOssIdDataAPI } from '@/api/als/algorithm'
import { getWarningResult } from '@/api/als/falseAlarmResult'

export default {
  name: 'FalseAlarm',
  components: { PlayBackChart },
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      innerVisible: false,
      progressVisible: 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: 'dataStatus',
          label: '状态',
          // 1 未处理，2  已处理
          render: (h, params) => {
            if (params.row.dataStatus == '1') {
              return h('span', '未处理')
            } else if (params.row.dataStatus == '2') {
              return h('span', { class: 'success-state' }, '已处理')
            } else {
              return h('span', { class: 'warning-state' }, '异常')
            }
          }
        },
        {
          // 算法执行时间
          prop: 'createTime',
          label: '创建时间'
        },
        {
          button: true,
          label: '操作',
          width: '240px',
          group: [
            {
              name: '虚警判断',
              type: 'text',
              statusKey: 'dataStatus',
              disableKey: '2',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.beginExecute(row)
              }
            },
            {
              name: '查看',
              type: 'text',
              statusKey: 'dataStatus',
              unDisableKey: '2',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.checkResultList(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: 20,
        searchValue: ''
      },
      warningColumns: [
        {
          prop: 'name',
          label: '故障名称'
        },
        {
          prop: 'code',
          label: 'HMC码'
        },
        {
          prop: 'attribute1',
          label: '判据名称',
          // render: (h, params) => {
          //   return h('span', { class: 'warning-state' }, params.row.attribute1)
          // },
          onClick: (row, index, scope) => {
            console.log(4444)
            this.$router.push({ name: 'JudgeFaultLogic' })
          }
        },
        {
          prop: 'resultContent',
          label: '判断结果',
          render: (h, params) => {
            if (params.row.resultContent == '0') {
              return h('span', { class: 'warning-state' }, '实警')
            } else if (params.row.resultContent == '1') {
              return h('span', { class: 'success-state' }, '虚警')
            } else if (params.row.resultContent == '2') {
              return h('span', '判故公式参数不匹配')
            } else if (params.row.resultContent == '3') {
              return h('span', '该HMC码无判据公式')
            }
          }
        },
        {
          button: true,
          label: '操作',
          width: '240px',
          group: [
            {
              name: '查看',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.checkCurve(row)
              }
            }
          ]
        }
      ],
      warningOptions: {
        stripe: true, // 斑马纹
        mutiSelect: false, // 多选框
        index: true, // 显示序号， 多选则 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: '',
        ossId: '',
        dataStatus: '',
        flightDate: ''
      },
      isFalseAlarm: '0',
      currentSortieNo: '',
      percentage: 0
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  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.form = {
        id: '',
        sortieNo: '',
        aircraftId: '',
        ossId: '',
        dataStatus: '',
        flightDate: ''
      }
    },

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

    submit() {
      this.form.dataStatus = 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
    },

    checkResultList(row) {
      this.currentSortieNo = this.form.sortieNo = row.sortieNo
      this.form.aircraftId = row.aircraftId
      this.form.flightDate = row.flightDate
      this.getWarningResultAPI({ sortieNo: row.sortieNo })
      this.openDialog()
    },

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

    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.dataStatus
      this.form = deepClone(row)
      try {
        const { code, data } = await getCurveData(row.code, row.sortieNo)
        console.log('resultData', code, data)
        if (code === 200) {
          if (data) {
            this.getResultData(data)
          } else {
            this.$message({
              type: 'warning',
              message: '无飞参数据!'
            })
          }
        }
      } catch (error) {}
    },

    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) {
      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 }
    },

    async beginExecute(row) {
      this.form = deepClone(row)
      this.progressVisible = true
      let myTimer = setInterval(() => {
        if (this.percentage < 100) {
          if (this.percentage === 99) {
            this.percentage = 99
          } else {
            this.percentage += 1
          }
        }
      }, 30)
      try {
        this.form.dataId = row.id
        const res = await executeFalseAlarm(this.form)

        clearInterval(myTimer)
        if (res?.code === 200) {
          this.handleClose()
          this.$message({
            type: 'success',
            message: '执行成功!'
          })
          // const res = await getWarningResult({ falseAlarmId: row.sortieNo })
          // const { data } = await getListByIdsApi(JSON.parse(res.data).ossId)
          // this.resultShowData.url = data[0].url
          this.checkResultList(row)
          this.dialogVisible = true
          this.getDataImportAPI({ aircraftId: this.aircaftModelIdList })
        }
      } catch (error) {
        clearInterval(myTimer)
      } finally {
        this.progressVisible = false
        this.percentage = 0
      }
    }
  }
}
</script>

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