<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="诊断结果" :visible.sync="resultVisible" width="1200px">
        <LTable ref="resultTable" :defaultFetch="false" :columns="resultColumns" :dataSource="resultTableData" :options="resultOptions" :pagination="resultTableRequset"></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>
      <el-dialog title="结果展示" :visible.sync="resultShowVisible" :before-close="resultShowDialogClose" width="800px">
        <div style="margin: 10px 0px">{{ resultShowData.result }}</div>
        <el-image style="width: 500px" v-if="resultShowData.url !== ''" :src="resultShowData.url" :preview-src-list="[resultShowData.url]"></el-image>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resultShowDialogClose">取 消</el-button>
          <el-button type="primary" @click="resultShowDialogClose">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getDataImport } from '@/api/als/dataImport'
import { getFaultDiagnosis } from '@/api/als/faultDiagnosis'
import { getFaultDiagnosisResult } from '@/api/als/faultDiagnosisResult'
import { getAircaftCatalogTree } from '@/api/als/sideTree'
import { getAircaftCatalogAll } from '@/api/als/aircraft'
import { deepClone, debounce } from '@/utils/index'
import { handleTree, flattenTree } from '../utils/common'
import { getAirConfiguration } from '@/api/als/airConfiguration'
import { executeFault } from '@/api/als/algorithm'
import { getListByIdsApi } from '@/api/als/oss'

export default {
  name: 'FaultDiagnosis',
  data() {
    // 这里存放数据
    return {
      resultVisible: false,
      progressVisible: false,
      resultShowVisible: 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', '飞参数据')
            } else {
              return h('span', 'MDC数据')
            }
          }
        },
        {
          prop: 'status',
          label: '状态',
          // 1 未处理，2  已处理
          render: (h, params) => {
            if (params.row.status == '1') {
              return h('span', '未处理')
            } else if (params.row.status == '2') {
              return h('span', { class: 'success-state' }, '已处理')
            } else {
              return h('span', { class: 'warning-state' }, '异常')
            }
          }
        },
        {
          button: true,
          label: '操作',
          width: '240px',
          group: [
            {
              name: '故障诊断',
              type: 'text',
              statusKey: 'status',
              disableKey: '2',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.faultExecute(row)
              }
            },
            {
              name: '查看',
              type: 'text',
              statusKey: 'status',
              unDisableKey: '2',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.checkRelustList(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: ''
      },
      resultColumns: [
        {
          prop: 'modelType',
          label: '算法名称'
        },
        {
          prop: 'param',
          label: '部件',
          render: (h, params) => {
            const matchedItem = this.allAirConfig.find((item) => params.row.param === item.id)
            if (matchedItem) {
              return h('span', matchedItem.name)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          prop: 'remarks',
          label: '参数特征'
        },
        {
          prop: 'columnData',
          label: '数据列'
        },
        {
          prop: 'resultContent',
          label: '结果',
          render: (h, params) => {
            const result = JSON.parse(params.row.resultContent).result
            if (result) {
              return h('span', result)
            } else {
              return h('span', {}, '-')
            }
          }
        },
        {
          button: true,
          label: '操作',
          width: '240px',
          group: [
            {
              name: '查看结果',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.checkRelustShow(row)
              }
            }
          ]
        }
      ],
      resultOptions: {
        stripe: true, // 斑马纹
        mutiSelect: true, // 多选框
        index: false, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: 'calc(100vh - 600px)'
      },
      resultTableCheckItems: [],
      resultTableData: [],
      resultTableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftCatalogAll: [],
      form: {
        id: '',
        sortieNo: '',
        ossId: '',
        aircraftId: '',
        aircraftType: '',
        flightDate: '',
        status: '',
        result: '',
        partId: null
      },
      currentSortieNo: '',
      partsData: [],
      allAirConfig: [],
      percentage: 0,
      resultShowData: {
        url: '',
        result: ''
      }
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  computed: {},
  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
        const { data: airConfigData } = await getAirConfiguration()
        this.allAirConfig = airConfigData
        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 getFaultDiagnosisResultAPI(params) {
      if (this.$refs.resultTable) this.$refs.resultTable.clearSelection()
      const { keyWord } = this
      const { pageSize, pageIndex } = this.resultTableRequset
      const {
        data: { list, total }
      } = await getFaultDiagnosisResult({ pageSize, pageNum: pageIndex, ...params })
      this.resultTableData = list
      this.resultTableRequset.total = total
    },

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

    async getAirConfigurationAPI(params) {
      try {
        const { data } = await getAirConfiguration(params)
        const treeData = handleTree(data, 'id')
        this.partsData = treeData
      } catch (error) {}
    },

    faultExecute(row) {
      this.form = deepClone(row)
      const allAir = flattenTree(this.menuTreeData)
      const item = allAir.find((item) => item.id === this.form.aircraftId)
      this.form.aircraftType = item.parentId
      this.currentSortieNo = row.sortieNo
      this.beginExecute()
    },

    partIdSelect(node) {
      this.form.partId = node.id
    },

    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    handleClose() {
      this.currentSortieNo = ''
      this.form = {
        id: '',
        sortieNo: '',
        ossId: '',
        aircraftId: '',
        aircraftType: '',
        flightDate: '',
        status: '',
        result: '',
        partId: null
      }
    },

    resultShowDialogClose() {
      this.resultShowVisible = false
      this.resultShowData = {
        url: '',
        result: ''
      }
    },

    submit() {
      this.beginExecute()
    },

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

    checkRelustList(row) {
      this.getFaultDiagnosisResultAPI({ sortieNo: row.sortieNo })
      this.resultVisible = true
    },

    async checkRelustShow(row) {
      const { data } = await getListByIdsApi(JSON.parse(row.resultContent).ossId)
      this.resultShowData.url = data[0].url
      this.resultShowData.result = JSON.parse(row.resultContent).result
      this.resultShowVisible = true
    },

    async getImgUrl(ossId) {
      const { data } = await getListByIdsApi(ossId)
      const newUrl = data[0].url
      return newUrl
    },

    async beginExecute() {
      this.progressVisible = true

      let myTimer = setInterval(() => {
        if (this.percentage < 100) {
          if (this.percentage === 99) {
            this.percentage = 99
          } else {
            this.percentage += 1
          }
        }
      }, 30)

      try {
        const res = await executeFault(this.form)
        clearInterval(myTimer)
        if (res?.code === 200) {
          this.percentage = 100
          this.$message({
            type: 'success',
            message: '执行成功!'
          })
          // const { data } = await getListByIdsApi(JSON.parse(res.data).ossId)
          // this.resultShowData.url = data[0].url
          // this.resultShowData.result = JSON.parse(res.data).result
          // this.resultShowVisible = true
          this.resultVisible = true
          this.getFaultDiagnosisResultAPI({ sortieNo: this.currentSortieNo })
          this.getDataImportAPI({ aircraftId: this.aircaftModelIdList })
          this.handleClose()
        }
      } catch (error) {
        clearInterval(myTimer)
      } finally {
        this.progressVisible = false
        this.percentage = 0
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../index.scss';
</style>
