<template>
  <div class="view-table-content">
    <div class="view-dataSpecies-left" style="display: flex; width: 430px">
      <MenuTree :currentNodeKey="currentNodeKey" nodeKey="id" :treedata="menuTreeData" @TreeNodeclick="treeNodeClick" v-bind="treeObj" style="width: 250px"> </MenuTree>
      <MenuTree :currentNodeKey="currentConfigNodeKey" nodeKey="id" :treedata="configTreeData" @TreeNodeclick="treeConfigNodeClick" v-bind="configurationTreeObj" style="width: 250px"> </MenuTree>
    </div>
    <div class="view-dataSpecies-right" style="width: calc(100% - 460px)">
      <div class="view-dataType-title">
        <div class="view-dataType-title-btn">
          <el-button type="success" @click="openDialog()" :disabled="currentConfigNodeKey === '' || currentConfigNodeKey === '1'">新增</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.id === ''"></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="600px" :before-close="handleClose">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="机型" prop="aircraftType">
            <el-select v-model="form.aircraftType" placeholder="请选择机型" disabled>
              <el-option v-for="item in aircaftModelAll" :key="item.aircaftModelId" :label="item.aircaftModelName" :value="item.aircaftModelId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="系统" prop="sysId">
            <el-select v-model="form.sysId" placeholder="请选择构型" disabled>
              <el-option v-for="item in allAirConfig" :key="item.id" :label="item.name" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="参数名称" prop="name">
            <el-input v-model="form.name" 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>
    </div>
  </div>
</template>

<script>
import { getAirConfigParams, addAirConfigParams, updateAirConfigParams, removeAirConfigParams } from '@/api/als/airConfigParams'
import { getAircaftCatalogTree, getAircaftTypeAndModelTree } from '@/api/als/sideTree'
import { getAircaftModelAll, getAircaftCatalogAll } from '@/api/als/aircraft'
import { handleTree } from '../utils/common'
import { getAirConfiguration } from '@/api/als/airConfiguration'
import { deepClone, debounce } from '@/utils/index'
export default {
  name: 'AirConfigParams',
  components: {},
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      keyWordData: '',
      aircaftModelIdList: [],
      currentNodeKey: '',
      currentNode: {},
      currentConfigNodeKey: '',
      currentConfigNode: {},
      menuTreeData: [],
      configTreeData: [],
      treeObj: {
        title: '所属机种',
        activityheight: '275px',
        searchIcon: false,
        configure: {
          children: 'children',
          label: 'label'
        }
      },
      configurationTreeObj: {
        title: '飞机系统',
        activityheight: '275px',
        searchIcon: false,
        configure: {
          children: 'children',
          label: 'name'
        }
      },
      typeTree: {
        children: 'children',
        label: 'label'
      },
      searchValue: '',
      columns: [
        {
          prop: 'sysId',
          label: '系统',
          render: (h, params) => {
            const matchedItem = this.allAirConfig.find((item) => params.row.sysId === item.id)
            if (matchedItem) {
              return h('span', matchedItem.name)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          prop: 'name',
          label: '参数名称'
        },
        {
          button: true,
          label: '操作',
          width: '240px',
          group: [
            {
              name: '编辑',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.handUpdate(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: ''
      },
      form: {
        id: '',
        aircraftType: '',
        sysId: '',
        name: ''
      },
      debounceFn: debounce(this.fetch, 500),
      allAirConfig: [],
      aircaftModelAll: []
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getAircaftTypeAndModelTreeAPI()
  },
  methods: {
    async getAircaftTypeAndModelTreeAPI(params) {
      const { data } = await getAircaftTypeAndModelTree(params)
      this.menuTreeData = data
      const { data: airConfigData } = await getAirConfiguration()
      this.allAirConfig = airConfigData
      const getAircaftModelAllParams = {
        aircaftTypeCode: '',
        aircaftTypeId: '',
        queryParam: ''
      }
      const { data: data1 } = await getAircaftModelAll(getAircaftModelAllParams)
      this.aircaftModelAll = data1
    },

    async removeAirConfigParamsAPI(params) {
      try {
        const { code } = await removeAirConfigParams(params)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          await this.getAirConfigParamsAPI({ sysId: this.currentConfigNodeKey })
          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 getAirConfigParamsAPI(params) {
      if (this.$refs.table) this.$refs.table.clearSelection()
      const { pageSize, pageIndex } = this.tableRequset
      const {
        data: { list, total }
      } = await getAirConfigParams({ pageSize, pageNum: pageIndex, ...params })
      this.tableData = list
      this.tableRequset.total = total
    },

    fetch() {
      this.getAirConfigParamsAPI({ sysId: this.currentConfigNodeKey })
    },

    searchClick() {
      this.getAirConfigParamsAPI({ aircraftType: this.currentNode.id, sysId: this.currentConfigNodeKey, name: this.keyWordData })
    },

    async addAirConfigParamsAPI() {
      try {
        delete this.form.aircaftModelName
        const { code } = await addAirConfigParams({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose()
          this.getAirConfigParamsAPI({ sysId: this.currentConfigNodeKey })
        }
      } catch (error) {}
    },

    async updateAirConfigParamsAPI() {
      try {
        const { code } = await updateAirConfigParams({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose()
          this.getAirConfigParamsAPI({ sysId: this.currentConfigNodeKey })
        }
      } catch (error) {}
    },

    async treeNodeClick(data) {
      this.currentNode = data
      let dataTree = []
      if (data.type === 1) {
        const { data: data1 } = await getAirConfiguration({ aircraftType: data.id })
        dataTree = data1
        this.getAirConfigParamsAPI({ aircraftType: data.id })
        this.currentNodeKey = data.id
      }
      this.configTreeData = []
      const topNode = { id: '1', name: '整机', children: [] }
      topNode.children = handleTree(dataTree, 'id')
      this.configTreeData.push(topNode)
    },

    treeConfigNodeClick(data) {
      this.$refs.table.clearSelection()
      this.currentConfigNodeKey = this.form.sysId = data.id
      this.currentConfigNode = data
      this.getAirConfigParamsAPI({ sysId: this.currentConfigNodeKey })
    },

    openDialog() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.form.aircraftType = this.currentNode.id
      this.form.sysId = this.currentConfigNodeKey
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        aircraftType: '',
        sysId: '',
        name: ''
      }
    },

    handUpdate(row) {
      this.dialogTitle = '编辑'
      this.form = deepClone(row)
      this.dialogVisible = true
    },

    submit() {
      switch (this.dialogTitle) {
        case '编辑':
          this.updateAirConfigParamsAPI()
          break
        case '新增':
          this.addAirConfigParamsAPI()
          break
      }
    },

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

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

    getAircraftType(item) {
      const matchedItem = this.aircaftModelAll?.find((i) => item === i.aircaftModelId)
      if (matchedItem) {
        return matchedItem.aircaftModelName
      } else {
        return item
      }
    }
  }
}
</script>

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