<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 class="view-dataType-title-btn">
            <el-button type="success" @click="openDialog()" :disabled="!(currentNode.type == 2)">新增</el-button>
            <el-button type="warning" @click="remove(tableCheckItems)" :disabled="tableCheckItems.length == 0">删除</el-button>
          </div>
        </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 == 2)"></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="60%" :before-close="handleClose">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="编目" prop="aircraftId">
            <el-select v-model="form.aircraftId" placeholder="请选择编目" @change="changeAircraftId(form.aircraftId)" disabled>
              <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">
            <LTable ref="sortieNoTableRef" :defaultFetch="false" :fetch="sortieNoFetch" @selection-change="sortieNoSelection" class="single-select-table" :columns="sortieNoColumns" :dataSource="sortieNoList" :options="sortieNoOptions"></LTable>
          </el-form-item>
          <el-form-item label="部件" prop="partId">
            <treeselect noOptionsText="该机型暂无构型信息，请在构型管理中添加" :value="form.partId" :normalizer="normalizer" :options="partsData" :show-count="true" placeholder="请选择部件" @select="partIdSelect" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="部件型号" prop="model">
                <el-input disabled placeholder="选择部件自动关联" style="width: 90%" v-model="form.model" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部件编号" prop="code">
                <el-input style="width: 90%" disabled placeholder="选择部件自动关联" v-model="form.code" />
              </el-form-item>
            </el-col>
          </el-row>
        </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">
        <el-progress :text-inside="true" :stroke-width="24" :percentage="percentage" status="success"></el-progress>
      </el-dialog>
      <el-dialog title="结果展示" :visible.sync="resultVisible" width="50%" :before-close="resultShowDialogClose" style="text-align: center">
        <el-image style="width: 500px" :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 { getLifePrediction, addLifePrediction, updateLifePrediction, removeLifePrediction } from '@/api/als/lifePrediction'
import { getAircaftCatalogTree } from '@/api/als/sideTree'
import { deepClone, debounce } from '@/utils/index'
import { getAircaftCatalogAll } from '@/api/als/aircraft'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getAirConfiguration } from '@/api/als/airConfiguration'
import { handleTree } from '../utils/common'
import { executeEvaluation } from '@/api/als/algorithm'
import { getAllDataImport } from '@/api/als/dataImport'
import { getListByIdsApi } from '@/api/als/oss'

export default {
  name: 'LifePrediction',
  components: { Treeselect },
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      resultVisible: 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: 'name',
          label: '部件名称'
        },
        {
          prop: 'model',
          label: '部件型号'
        },
        {
          prop: 'code',
          label: '部件编码'
        },
        {
          prop: 'timeRange',
          label: '时间区间'
        },
        {
          prop: 'sortiesCount',
          label: '架次数量'
        },
        {
          prop: 'createTime',
          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: '200px',
          group: [
            {
              name: '查看结果',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.checkResult(row)
              }
            },
            {
              name: '删除',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.remove([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: ''
      },
      sortieNoColumns: [
        {
          prop: 'sortieNo',
          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数据')
            }
          }
        },
        {
          prop: 'ossId',
          label: '文件Id'
        }
      ],
      sortieNoOptions: {
        stripe: true, // 斑马纹
        mutiSelect: true, // 多选框
        index: true, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: '250px'
      },
      sortieNoList: [],
      sortieNoCheckItems: [],
      form: {
        id: '',
        aircraftId: '',
        partId: null,
        aircraftType: '',
        code: '',
        name: '',
        model: '',
        methodType: '',
        status: '',
        resultContent: '',
        ossIds: [],
        timeRange: '',
        sortiesCount: ''
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftCatalogAll: [],
      percentage: 0,
      partsData: [],
      rules: {
        aircraftId: [{ required: true, message: '编目不能为空', trigger: 'change' }],
        partId: [{ required: true, message: '部件不能为空', trigger: 'change' }]
      },
      resultUrl: '',
      resultShowData: {
        url: ''
      },
      timeValue: ''
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getAircaftCatalogTreeAPI()
  },
  methods: {
    async getAircaftCatalogTreeAPI(params) {
      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.getLifePredictionAPI({ aircraftId: this.aircaftModelIdList })
        // this.getLifePredictionAPI()
        // this.getDataImportAPI()
      }
    },

    async removeLifePredictionAPI(params) {
      try {
        const { code } = await removeLifePrediction(params)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          await this.getLifePredictionAPI({ aircraftId: this.aircaftModelIdList })
          this.handleClose()
        }
      } 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 getLifePredictionAPI(params) {
      if (this.$refs.table) this.$refs.table.clearSelection()
      const { keyWord } = this
      const { pageSize, pageIndex } = this.tableRequset
      const {
        data: { list, total }
      } = await getLifePrediction({ pageSize, pageNum: pageIndex, ...params })
      this.tableData = list
      this.tableRequset.total = total
    },

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

    sortieNoFetch() {
      this.getAirDataAPI({ aircraftId: this.currentNode.id })
    },

    async sortieNoSelection(val) {
      this.sortieNoCheckItems = val
    },

    async getAirDataAPI(params) {
      this.sortieNoCheckItems = []
      try {
        if (this.$refs.sortieNoTableRef) this.$refs.sortieNoTableRef.clearSelection()
        const { code, data } = await getAllDataImport({ ...params, source: 1 })
        if (code === 200) {
          this.sortieNoList = data
        }
      } catch (error) {}
    },

    async searchClick() {
      this.getLifePredictionAPI({ aircraftId: this.aircaftModelIdList, name: this.keyWordData })
    },

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

    openDialog() {
      const aircraftType = this.currentNode.parentId
      this.form.aircraftId = this.currentNode.id
      this.getAirConfigurationAPI({ aircraftType })
      this.getAirDataAPI({ aircraftId: this.currentNode.id })
      this.dialogTitle = '新增'
      this.dialogVisible = true
    },

    partIdSelect(node) {
      this.form.partId = node.id
      this.form.model = node.specsModel
      this.form.code = node.conCode
    },

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

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        aircraftId: '',
        partId: null,
        aircraftType: '',
        code: '',
        name: '',
        model: '',
        methodType: '',
        status: '',
        resultContent: '',
        ossIds: [],
        timeRange: '',
        sortiesCount: ''
      }
    },

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

    async checkResult(row) {
      const { data } = await getListByIdsApi(JSON.parse(row.resultContent).ossId)
      this.resultShowData.url = data[0].url
      this.resultVisible = true
    },
    async beginExecute() {
      this.sortieNoCheckItems.forEach((item) => {
        this.form.ossIds.push(item.ossId)
      })
      if (this.sortieNoCheckItems.length == 0) {
        this.$message({
          type: 'warning',
          message: '请选择架次号!'
        })
        return
      }
      if (this.sortieNoCheckItems.length == 1) {
        this.form.timeRange = this.sortieNoCheckItems[0].flightDate
      } else {
        let minDate = this.sortieNoCheckItems[0].flightDate
        let maxDate = this.sortieNoCheckItems[0].flightDate
        for (let i = 1; i < this.sortieNoCheckItems.length; i++) {
          let currentDate = this.sortieNoCheckItems[i].flightDate
          if (currentDate < minDate) {
            minDate = currentDate
          } else if (currentDate > maxDate) {
            maxDate = currentDate
          }
        }
        this.form.timeRange = `${minDate} 至 ${maxDate}`
      }
      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 executeEvaluation(this.form)

        clearInterval(myTimer)
        if (res?.code === 200) {
          this.handleClose()
          this.$message({
            type: 'success',
            message: '执行成功!'
          })
          const { data } = await getListByIdsApi(JSON.parse(res.data).ossId)
          this.resultShowData.url = data[0].url
          this.resultVisible = true
          this.getLifePredictionAPI({ aircraftId: this.aircaftModelIdList })
        }
      } catch (error) {
        clearInterval(myTimer)
      } finally {
        this.progressVisible = false
        this.percentage = 0
      }
    },

    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },

    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          switch (this.dialogTitle) {
            case '编辑':
              break
            case '新增':
              this.beginExecute()
              break
          }
        }
      })
    },

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

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

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