<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">
          <el-button type="success" @click="openDialog()" :disabled="!(currentNode.type == 1 && currentNode.children.length == 0)">新增</el-button>
          <el-button type="warning" @click="remove(tableCheckItems)" :disabled="tableCheckItems.length == 0">删除</el-button>
        </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" :disabled="!(currentNode.type == 1 && currentNode.children.length == 0)"></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" width="1000px" :before-close="handleClose">
        <el-form ref="executeForm" :model="executeForm" label-width="80px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="编目" prop="aircraftId">
                <el-select v-model="executeForm.aircraftId" placeholder="请选择编目" disabled @change="changeAircraftId(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-col>
            <el-col :span="8">
              <el-form-item label="模型类型" prop="modelType">
                <el-select v-model="executeForm.modelType" placeholder="请选择模型类型" @change="changeModelType(executeForm.modelType)">
                  <el-option v-for="item in [$enumData.agloModelList[3]]" :key="item.key" :label="item.name" :value="item.key" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="模型" prop="modelId">
                <el-select v-model="executeForm.modelId" placeholder="请选择模型" @change="changeModelId(executeForm.modelId)">
                  <el-option v-for="item in modelList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select> </el-form-item
            ></el-col>
          </el-row>

          <el-form-item label="架次号" prop="sortieNo">
            <LTable ref="sortieNoTableRef" @current-change="sortieNoSelection" class="single-select-table" :columns="sortieNoColumns" :dataSource="sortieNoList" :options="sortieNoOptions" :pagination="SortieNoTableRequset"></LTable>
          </el-form-item>
          <el-form-item label="警告列表" prop="warningIds">
            <el-table ref="warningTableRef" :data="warningIdsList" @current-change="warningSelection" style="width: 100%; height: 200px" highlight-current-row>
              <el-table-column prop="id" label="警告ID"> </el-table-column>
              <el-table-column prop="name" label="名称"> </el-table-column>
              <el-table-column prop="describe" label="描述"> </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item label="参数" prop="param"> <el-input v-model="executeForm.param" type="textarea" :rows="2" placeholder="请输入参数" /> </el-form-item>
          <el-form-item label="数据列" prop="columnData">
            <el-transfer v-model="transferRightData" :data="transferData" @change="changeColumnData"></el-transfer>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="执行进度" :visible.sync="progressVisible" width="800px" :before-close="handleClose">
        <el-progress :text-inside="true" :stroke-width="24" :percentage="percentage" status="success"></el-progress>
      </el-dialog>
      <el-dialog title="结果展示" :visible.sync="resultVisible" width="1200px">
        <!-- <falseAlarmResult :falseAlarmId="form.id" /> -->
        <LTable ref="resultTableRef" :columns="resultColumns" :dataSource="resultTableData" :options="resultOptions" :pagination="resultTableRequset"></LTable>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="resultVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getFalseAlarm, addFalseAlarm, updateFalseAlarm, removeFalseAlarm } from '@/api/als/falseAlarm'
import { getFalseAlarmResult } from '@/api/als/falseAlarmResult'
import { getColumnDataAPI, executeFalseAlarm } from '@/api/als/algorithm'
import { getAircaftCatalogTree } from '@/api/als/sideTree'
import { getAircaftCatalogAll } from '@/api/als/aircraft'
import { getDataImport } from '@/api/als/dataImport'
import { getModel } from '@/api/als/model'
import { deepClone, debounce } from '@/utils/index'
import { getWarning } from '@/api/als/warning'

export default {
  name: 'FalseAlarm',
  components: {},
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      progressVisible: false,
      resultVisible: 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: 'sortieNo',
          label: '架次号'
        },
        {
          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: 'modelType',
          label: '模型类型',
          render: (h, params) => {
            const matchedItem = this.$enumData.agloModelList.find((item) => params.row.modelType === item.key)
            if (matchedItem) {
              return h('span', matchedItem.name)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          prop: 'param',
          label: '参数'
        },
        {
          prop: 'columnData',
          label: '数据列'
        },
        // {
        //   prop: 'ossId',
        //   label: '文件Id'
        // },
        {
          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.checkResultList(row)
              }
            },
            {
              name: '删除',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.remove([row])
              }
            }
          ]
        }
      ],
      sortieNoColumns: [
        {
          prop: 'sortieNo',
          label: '架次号'
        },
        {
          prop: 'source',
          label: '数据来源'
        },
        {
          prop: 'ossId',
          label: '文件Id'
        }
      ],
      resultColumns: [
        {
          prop: 'sortieNo',
          label: '架次号'
        },
        {
          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: 'code',
          label: '警告代码'
        },
        {
          prop: 'name',
          label: '警告名称'
        },
        {
          prop: 'describe',
          label: '警告描述'
        },
        {
          prop: 'status',
          label: '结果',
          render: (h, params) => {
            const result = JSON.parse(params.row.status)[0]
            const isfalseAlarm = result['是否虚警']
            if (isfalseAlarm == 0) {
              return h('span', { class: 'warning-state' }, '否')
            } else {
              return h('span', { class: 'success-state' }, '是')
            }
          }
        }
      ],
      options: {
        stripe: true, // 斑马纹
        mutiSelect: true, // 多选框
        index: false, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: 'calc(100vh - 300px)'
      },
      sortieNoOptions: {
        stripe: true, // 斑马纹
        mutiSelect: false, // 多选框
        index: true, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: '250px'
      },
      resultOptions: {
        stripe: true,
        mutiSelect: false,
        index: false,
        loading: false,
        initTable: false,
        border: true,
        height: '300px'
      },
      resultTableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      tableCheckItems: [],
      tableData: [],
      resultTableData: [],
      SortieNoTableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      executeForm: {
        modelId: '',
        modelType: '',
        ossId: '',
        aircraftId: '',
        sortieNo: '',
        param: '',
        columnData: [],
        warningIds: []
      },
      form: {
        id: '',
        sortieNo: '',
        aircraftId: '',
        modelType: '',
        param: '',
        columnData: [],
        ossId: '',
        status: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftCatalogAll: [],
      transferData: [],
      transferRightData: [],
      algoTypeList: [{ id: 4, name: '虚警抑制' }],
      modelList: [],
      percentage: 0,
      sortieNoList: [],
      warningIdsList: [],
      sortieNoTableCheck: []
    }
  },
  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.getFalseAlarmAPI({ aircraftId: this.aircaftModelIdList })
        }
      } catch (error) {}
    },

    async removeFalseAlarmAPI(params) {
      try {
        const { code } = await removeFalseAlarm(params)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          await this.getFalseAlarmAPI({ aircraftId: this.aircaftModelIdList })
          this.handleClose()
        }
      } catch (error) {}
    },

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

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

    async getFalseAlarmResultAPI(params) {
      if (this.$refs.resultTableRef) this.$refs.resultTableRef.clearSelection()
      const { keyWord } = this
      const { pageSize, pageIndex } = this.resultTableRequset
      const {
        data: { list, total }
      } = await getFalseAlarmResult({ pageSize, pageNum: pageIndex, ...params })
      this.resultTableData = list
      this.resultTableRequset.total = total
    },

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

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

    async addFalseAlarmAPI() {
      try {
        delete this.form.aircaftModelName
        const { code } = await addFalseAlarm({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getFalseAlarmAPI({ aircraftId: this.aircaftModelIdList })
        }
      } catch (error) {}
    },

    async updateFalseAlarmAPI() {
      try {
        const { code } = await updateFalseAlarm({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getFalseAlarmAPI({ aircraftId: this.aircaftModelIdList })
        }
      } catch (error) {}
    },

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

    openDialog() {
      this.executeForm.aircraftId = this.currentNodeKey
      if (this.executeForm.aircraftId !== '') {
        this.changeAircraftId(this.executeForm.aircraftId)
      }
      this.dialogTitle = '新增'
      this.dialogVisible = true
    },

    handleClose() {
      this.dialogVisible = false
      this.transferRightData = []
      this.$refs.sortieNoTableRef.clearSelection()
      this.executeForm = {
        modelId: '',
        modelType: '',
        ossId: '',
        aircraftId: '',
        sortieNo: '',
        param: '',
        columnData: [],
        warningIds: []
      }
    },

    handUpdate(row) {
      this.dialogTitle = '编辑'
      this.form = deepClone(row)
      this.dialogVisible = true
    },
    changeColumnData(value) {
      const data = []
      this.transferData.forEach((item) => {
        value.forEach((rightData) => {
          if (rightData === item.key) {
            data.push(item.label)
          }
        })
      })
      this.executeForm.columnData = data
    },
    checkResultList(row) {
      if (row.status === '0') {
        this.$message({
          type: 'warning',
          message: '执行失败，无法查看结果!'
        })
        return
      }
      this.getFalseAlarmResultAPI({ falseAlarmId: row.id })
      this.resultVisible = true
    },
    async beginExecute() {
      this.progressVisible = true

      try {
        this.percentage += 1
        const res = await executeFalseAlarm(this.executeForm)
        const myTimer = setInterval(() => {
          if (res?.code === 200 && this.percentage == 100) {
            this.progressVisible = false
            clearInterval(myTimer)
            this.percentage = 0
            this.handleClose()
            this.$message({
              type: 'success',
              message: '执行成功!'
            })
            const result = JSON.parse(res.data)[0]
            const isfalseAlarm = result['是否虚警'] === 0 ? '否' : '是'
            this.getFalseAlarmAPI({ aircraftId: this.aircaftModelIdList })
            this.$alert(`故障编码为：${result['故障编码']},是否虚警：${isfalseAlarm},`, '虚警抑制结果', {
              confirmButtonText: '确定'
            })
          } else {
            this.percentage += 1
          }
        }, 30)
      } catch (error) {
        this.progressVisible = false
        clearInterval(myTimer)
        this.percentage = 0
      }
    },
    async changeModelType(type) {
      try {
        const {
          data: { list }
        } = await getModel({ type })
        this.modelList = list
      } catch (error) {}
    },

    changeModelId(modelId) {
      const modelColumnData = JSON.parse(
        this.modelList.find((item) => {
          return item.id === modelId
        }).columnData
      )

      const labelToKeyMap = this.transferData.reduce((acc, item) => {
        acc[item.label] = item.key
        return acc
      }, {})

      modelColumnData.forEach((item) => {
        if (labelToKeyMap.hasOwnProperty(item)) {
          this.executeForm.columnData.push(item)
          this.transferRightData.push(labelToKeyMap[item])
        }
      })
    },

    async changeAircraftId(aircraftId) {
      try {
        const {
          data: { list, total }
        } = await getDataImport({ aircraftId })
        this.sortieNoList = list
        this.SortieNoTableRequset.total = total
      } catch (error) {}
    },

    async changeSortieNo(sortieNo) {
      try {
        const {
          data: { list }
        } = await getWarning({ aircraftId: this.executeForm.aircraftId, sortieNo })
        this.executeForm.sortieNo = sortieNo
        this.warningIdsList = list
      } catch (error) {}
    },

    submit() {
      switch (this.dialogTitle) {
        case '编辑':
          this.updateFalseAlarmAPI()
          this.handleClose()
          break
        case '新增':
          this.beginExecute()
          break
      }
    },

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

    async sortieNoSelection(val) {
      this.executeForm.ossId = val.ossId
      if (val.ossId) {
        try {
          const res = await getColumnDataAPI(val.ossId)
          if (res.code === 200) {
            this.transferData = []
            res.data.forEach((item, index) => {
              this.transferData.push({
                key: index,
                label: item
              })
            })

            this.changeSortieNo(val.sortieNo)
          }
        } catch (error) {}
      }
    },

    warningSelection(val) {
      this.executeForm.warningIds = [val.id]
      if (this.executeForm.modelId) {
        this.changeModelId(this.executeForm.modelId)
      }
    },

    remove(row) {
      this.$confirm('是否删除该数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.removeFalseAlarmAPI(row.map((e) => e.id))
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../index.scss';
::v-deep .single-select-table thead .el-table-column--selection .cell {
  display: none;
}
</style>
