<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 == 1 && currentNode.children.length == 0)">新增</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 == 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="800px" :before-close="handleClose">
        <el-form ref="executeForm" :model="executeForm" label-width="80px">
          <el-form-item label="编目" prop="aircraftId">
            <el-select v-model="executeForm.aircraftId" placeholder="请选择编目" @change="changeAircraftId(executeForm.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="modelType">
            <el-select v-model="executeForm.modelType" placeholder="请选择模型类型" @change="changeModelType(executeForm.modelType)">
              <el-option v-for="item in algoTypeList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <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="name">
            <el-input v-model="executeForm.name" placeholder="请输入部件" />
            <!-- <treeselect v-model="executeForm.name" :normalizer="normalizer" :options="partsTreeData" :show-count="true" placeholder="请选择部件" /> -->
          </el-form-item>
          <!-- <el-form-item label="所属系统" prop="system">
            <el-input v-model="form.system" placeholder="请输入所属系统" />
          </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="800px">
        展示结果
        <span slot="footer" class="dialog-footer">
          <el-button @click="resultVisible = false">取 消</el-button>
          <el-button type="primary" @click="resultVisible = false">确 定</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 { getDataImport } from '@/api/als/dataImport'
import { getModel } from '@/api/als/model'
import { getAircaftCatalogAll } from '@/api/als/aircraft'
// import Treeselect from '@riophae/vue-treeselect'
// import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'LifePrediction',
  components: {},
  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: 'id', label: '编号' },
        {
          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: 'name',
          label: '部件名称'
        },
        {
          prop: 'model',
          label: '型号'
        },
        {
          prop: 'system',
          label: '所属系统'
        },
        {
          prop: 'methodType',
          label: '处理方式'
        },
        {
          prop: 'remainTiem',
          label: '剩余时长'
        },
        {
          prop: 'status',
          label: '状态'
        },
        {
          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'
        }
      ],
      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,
        loading: false,
        initTable: false,
        border: true,
        height: '250px'
      },
      SortieNoTableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      tableCheckItems: [],
      tableData: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      form: {
        id: '',
        aircraftId: '',
        name: '',
        model: '',
        system: '',
        methodType: '',
        remainTiem: '',
        status: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      debounceFn: debounce(this.fetch, 500),
      executeForm: {
        sortieNo: '',
        aircraftId: '',
        modelType: '',
        name: ''
      },
      aircaftCatalogAll: [],
      algoTypeList: [{ id: 6, name: '寿命预测' }],
      percentage: 0,
      modelList: [],
      sortieNoList: []
    }
  },
  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 === 1) {
            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 })
    },

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

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

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

    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() {
      this.executeForm.aircraftId = this.currentNodeKey
      if (this.executeForm.aircraftId !== '') {
        this.changeAircraftId(this.executeForm.aircraftId)
      }
      this.dialogTitle = '新增'
      this.dialogVisible = true
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        aircraftId: '',
        name: '',
        model: '',
        system: '',
        methodType: '',
        remainTiem: '',
        status: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      }
    },
    handUpdate(row) {
      this.dialogTitle = '编辑'
      this.form = deepClone(row)
      this.dialogVisible = true
    },
    checkResultList(row) {
      this.form = deepClone(row)
      this.resultVisible = true
    },
    executeAglo(row) {
      // this.executeVisible = true
      // this.agloForm.sortieNo = row.sortieNo
      // this.agloForm.aircraftId = row.aircraftId
    },
    beginExecute() {
      // 调用算法接口

      // this.executeVisible = false
      this.progressVisible = true
      const myTimer = setInterval(() => {
        if (this.percentage < 100) {
          this.percentage += 1
        } else {
          this.progressVisible = false
          this.percentage = 0
          clearInterval(myTimer)
          // this.$router.push({ name: 'PreResult', params: { agloForm: this.agloForm } })
          this.handleClose()
          this.$message({
            type: 'success',
            message: '执行成功!'
          })
          this.$alert('寿命预测结果为：寿命前期', '寿命预测结果', {
            confirmButtonText: '确定'
          })
        }
      }, 30)
    },

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

    async sortieNoSelection(val) {
      this.executeForm.ossId = val.ossId //得到架次数据
      this.executeForm.sortieNo = val.sortieNo
    },

    async changeModelType(type) {
      try {
        const {
          data: { list }
        } = await getModel({ type })
        this.modelList = list
      } catch (error) {}
    },

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

    submit() {
      switch (this.dialogTitle) {
        case '编辑':
          this.updateLifePredictionAPI()
          this.handleClose()
          break
        case '新增':
          // this.addLifePredictionAPI()
          // this.handleClose()
          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>
