<template>
  <div class="view-dataAircraftConfiguration">
    <div class="view-dataSpecies-left">
      <MenuTree :currentNodeKey="currentNodeKey" nodeKey="value" :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="openStructureEquippingDialog()" :disabled="currentNode && currentNode.type == 0">新增</el-button>
          <el-button type="warning" @click="remove(tableCheckItems)" :disabled="tableCheckItems.length == 0">删除</el-button>
          <el-button type="primary">导入模板</el-button>
          <el-button type="primary">导出模板</el-button>
        </div>
        <div class="view-dataType-title-search">
          <el-input placeholder="机种类/编号" v-model="keyword" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="fetchTableData(1)"></el-button>
          </el-input>
        </div>
      </div>
      <div class="view-dataType-table">
        <LTable ref="table" @selection-change="selection" :defaultFetch="false" :columns="columns" :dataSource="tableData" :options="options" :fetch="fetchTableData" :pagination="tableRequset"></LTable>
      </div>
      <StructureEquipping :treeNode="currentNode" ref="structureEquipping" @handleStructureEquipping="handleStructureEquipping" />
    </div>
  </div>
</template>

<script>
import { getAircaftTypeAndModelTree } from '@/api/basicData/dataAircraftCataloging'
import { queryAircaftComponents, addAircaftComponents, updateAircaftComponentse, deleteAircaftComponents } from '@/api/basicData/dataAircraftConfiguration'
import { defaultProps, columns, options } from './index'
import StructureEquipping from './components/StructureEquipping/index.vue'
import { debounce } from '@/utils/index'

export default {
  name: 'dataAircraftConfiguration',
  components: { StructureEquipping },
  data() {
    // 这里存放数据
    return {
      currentNodeKey: '',
      menuTreeData: [],
      aircaftModelCodeList: [],
      currentNodeName: '',
      currentNode: null,
      treeObj: {
        title: '所属机种',
        activityheight: '275px',
        searchIcon: false,
        configure: defaultProps
      },
      typeTree: {
        children: 'children',
        label: 'aircraftTypeName'
      },
      keyword: '',
      columns: columns(this),
      options,
      tableData: [],
      tableCheckItems: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      form: {
        equipmentName: '',
        serialNumber: '',
        aircraftSpeciesName: '',
        sparePartsNumber: '',
        sparePartsType: ''
      },
      debounceFn: debounce(this.fetchTableData, 500)
    }
  },
  watch: {
    keyword() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  created() {
    this.getAircaftTypeAndModelTreeAPI()
  },

  methods: {
    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 getAircaftTypeAndModelTreeAPI(params) {
      const { data } = await getAircaftTypeAndModelTree(params)
      this.menuTreeData = data
      if (data.length) {
        this.currentNodeKey = data[0].value
        this.currentNode = data[0]
        this.fetchTableData()
      }
    },

    async fetchTableData(pageIndex) {
      const { value: aircaftModelCode } = this.currentNode
      const { pageIndex: pageNum, pageSize } = this.tableRequset
      const {
        data: { list, totalCount }
      } = await queryAircaftComponents({ keyword: this.keyword, aircaftModelCode, pageNum: pageIndex ? pageIndex : pageNum, pageSize, aircaftModelId: this.currentNode.id })
      this.tableData = list
      this.tableRequset.total = totalCount
    },

    treeNodeClick(data) {
      this.$refs.table.clearSelection()
      this.currentNodeKey = data.value
      this.currentNode = data
      this.fetchTableData()
    },

    openStructureEquippingDialog() {
      this.$refs.structureEquipping.openModal({
        type: 'add',
        title: '新增'
      })
    },

    async addAircaftComponentsAPI(params) {
      params.aircaftModelId = this.currentNode.id
      delete params.type
      delete params.aircaftModelCodeName
      const { success } = await addAircaftComponents(params)
      if (success) {
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
        this.fetchTableData()
      }
    },

    handleStructureEquipping(row) {
      switch (row.type) {
        case 'add':
          this.addAircaftComponentsAPI({ ...row })
          break

        case 'edit':
          break
      }
      this.$refs.structureEquipping.closeModal()
    },

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

    handleNodeClick(data) {
      const { parentTypeName, parentTypeId } = data
      this.form.parentTypeName = parentTypeName
      this.form.parentTypeId = parentTypeId
      this.$refs.onSelect.blur()
    },

    async updateRow(row) {
      const { installedCount, installedPosition, avmatCatalogId } = row
      let regex = /^[0-9]+$/
      if (!regex.test(installedCount)) {
        this.fetchTableData()
        this.$message({
          type: 'warning',
          message: '只能输入数字'
        })
        return
      }
      try {
        await updateAircaftComponentse({ installedCount, installedPosition, avmatCatalogId })
      } catch (error) {}
      this.fetchTableData()
      this.$message({
        type: 'success',
        message: '编辑成功!'
      })
    },

    async deleteAircaftComponentsAPI(params) {
      try {
        const { success } = await deleteAircaftComponents(params)
        if (success) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchTableData()
        }
      } catch (error) {}
    },

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

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