<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-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" :showColumnSetting="false" :columns="warningColumns" :dataSource="warningTableData" :options="warningOptions" :pagination="warningTableRequset"></LTable>
        <el-dialog width="80%" title="飞参数据曲线" :visible.sync="innerVisible" :before-close="innerDialogClose" append-to-body>
          <PlayBackChart :chartData="chartData" />
          <div style="margin-top: 20px">
            <span style="color: #fff; margin-left: 30px">请选择时间区间：</span>
            <el-date-picker v-model="mathTime" placement="bottom-start" value-format="yyyy-MM-dd HH:mm:ss.SSS" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="handleMathTime" :clearable="false">
            </el-date-picker>

            <el-button icon="el-icon-refresh" circle class="refresh" @click="resetTime"></el-button>
            <el-button type="success" @click="getExecuteMathAPI" style="margin-left: 15px">确 定</el-button>
            <LTable ref="mathTable" :defaultFetch="false" :columns="mathColumns" :dataSource="mathTableData" :options="mathOptions"></LTable>
          </div>
          <div style="width: 100%; color: #fff; text-align: center">
            <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>
          <span slot="footer" class="dialog-footer">
            <el-button @click="innerDialogClose">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
          </span>
        </el-dialog>
      </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, executeMath } from '@/api/als/algorithm'
import { getWarningResult, updateWarningResult } 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: false, // 斑马纹
        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) => {
            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: false, // 斑马纹
        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: ''
      },
      mathColumns: [
        {
          prop: 'params',
          label: '参数'
        },
        {
          prop: 'mean',
          label: '算数平均数'
        },
        {
          prop: 'variance',
          label: '方差'
        },
        {
          prop: 'populationVariance',
          label: '总体方差'
        },
        {
          prop: 'sum',
          label: '和'
        },
        {
          prop: 'max',
          label: '最大值'
        },
        {
          prop: 'min',
          label: '最小值'
        },
        {
          prop: 'mode',
          label: '众数'
        },
        {
          prop: 'geometricMean',
          label: '几何平均数'
        },
        {
          prop: 'sumSq',
          label: '平方和'
        }
      ],
      mathOptions: {
        stripe: false, // 斑马纹
        mutiSelect: false, // 多选框
        index: false, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: '300px'
      },
      mathTableData: [],
      debounceFn: debounce(this.fetch, 500),
      aircaftCatalogAll: [],
      chartData: {
        title: '',
        legendData: [],
        xAxisData: [],
        yAxisData: [],
        seriesData: []
      },
      form: {
        id: '',
        sortieNo: '',
        aircraftId: '',
        ossId: '',
        dataStatus: '',
        flightDate: ''
      },
      warningForm: {
        id: null,
        resultContent: ''
      },
      isFalseAlarm: '0',
      currentSortieNo: '',
      percentage: 0,
      mathTime: [],
      mathParams: {
        code: '',
        sortieNo: '',
        beginTime: '',
        endTime: ''
      },
      backupsTime: []
      // startTime:'',
      // endTime:'',
    }
  },
  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.warningForm = {
        id: null,
        resultContent: ''
      }
      this.mathParams = {
        code: '',
        sortieNo: '',
        beginTime: '',
        endTime: ''
      }
      this.mathTableData = []
      this.isFalseAlarm = false
    },

    submit() {
      this.warningForm.resultContent = this.isFalseAlarm
      this.updateWarningResultAPI()
    },

    async updateWarningResultAPI() {
      try {
        const { code } = await updateWarningResult({ ...this.warningForm })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.innerDialogClose()
          this.getWarningResultAPI({ 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.resultContent
      this.warningForm = deepClone(row)
      this.mathParams.code = row.code
      this.mathParams.sortieNo = row.sortieNo
      this.getExecuteMathAPI()
      try {
        const { code, data } = await getCurveData(row.code, row.sortieNo)
        if (code === 200) {
          if (data) {
            this.getResultData(data)
          } else {
            this.$message({
              type: 'warning',
              message: '无飞参数据!'
            })
          }
        }
      } catch (error) {}
    },

    handleMathTime(time) {
      this.mathParams.beginTime = time[0]
      this.mathParams.endTime = time[1]
    },

    resetTime() {
      this.mathTime = this.backupsTime
    },

    // 获取数学数据
    async getExecuteMathAPI() {
      try {
        const { data, code } = await executeMath(this.mathParams)
        if (code === 200) {
          this.mathTableData = []
          Object.keys(data).forEach((item) => {
            this.mathTableData.push({
              params: item,
              ...data[item]
            })
          })
        }
      } 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 === '时间') {
          const timeList = contentData['时间']
          const time = [timeList[0], timeList[timeList.length - 1]]
          this.mathTime = this.backupsTime = time
          this.chartData.xAxisData = timeList
        } 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;
  margin-top: 20px;
  color: #fff;
  z-index: 9999;
}
.refresh {
  padding: 5px !important;
  border-radius: 50% !important;
  margin-left: 10px;
}
</style>
