<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">
          <el-button type="success" @click="openDialog()" :disabled="!(currentNode.type == 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"></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="conCode">
            <treeselect v-model="form.parentId" :normalizer="normalizer" :options="tableData" :show-count="true" placeholder="选择上级名称" />
            <!-- <el-input v-model="form.conCode" placeholder="请输入构型编码" /> -->
          </el-form-item>
          <el-form-item label="构型编码" prop="conCode">
            <el-input v-model="form.conCode" placeholder="请输入构型编码" />
          </el-form-item>
          <el-form-item label="产品名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入产品名称" />
          </el-form-item>
          <el-form-item label="规格型号" prop="specsModel">
            <el-input v-model="form.specsModel" placeholder="请输入规格型号" />
          </el-form-item>
          <el-form-item label="图号" prop="drawingNumber">
            <el-input v-model="form.drawingNumber" placeholder="请输入图号" />
          </el-form-item>
          <el-form-item label="供应商" prop="supplier">
            <el-input v-model="form.supplier" placeholder="请输入供应商" />
          </el-form-item>
          <el-form-item label="描述" prop="remarks">
            <el-input type="textarea" :rows="2" v-model="form.remarks" 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 { getAirConfiguration, addAirConfiguration, updateAirConfiguration, removeAirConfiguration } from '@/api/als/airConfiguration'
import { getAircaftCatalogTree, getAircaftTypeAndModelTree } from '@/api/als/sideTree'
import { deepClone, debounce } from '@/utils/index'
import { getAircaftModelAll } from '@/api/als/aircraft'
import { handleTree } from '../utils/common'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'AirConfiguration',
  components: { Treeselect },
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: 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: '唯一ID' },
        {
          prop: 'name',
          label: '产品名称',
          align: 'left'
        },
        {
          prop: 'conCode',
          label: '构型编码'
        },

        {
          prop: 'aircraftType',
          label: '机型',
          render: (h, params) => {
            const matchedItem = this.aircaftModelAll.find((item) => params.row.aircraftType === item.aircaftModelId)
            if (matchedItem) {
              return h('span', matchedItem.aircaftModelName)
            } else {
              return h('span', {}, '')
            }
          }
        },

        {
          prop: 'specsModel',
          label: '规格型号'
        },
        {
          prop: 'drawingNumber',
          label: '图号'
        },
        {
          prop: 'supplier',
          label: '供应商'
        },
        {
          prop: 'remarks',
          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)',
        treeProps: {
          children: 'children',
          hasChildren: 'hasChildren'
        }
      },
      tableCheckItems: [],
      tableData: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      form: {
        id: '',
        aircraftType: '',
        conCode: '',
        name: '',
        specsModel: '',
        drawingNumber: '',
        supplier: '',
        remarks: '',
        tenantId: '',
        delFlag: '',
        version: '',
        createdBy: '',
        createdTime: '',
        updatedBy: '',
        updatedTime: ''
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftModelAll: []
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getAircaftCatalogTreeAPI()
  },
  methods: {
    async getAircaftCatalogTreeAPI(params) {
      const { data } = await getAircaftTypeAndModelTree(params)
      this.menuTreeData = data
      const getAircaftModelAllParams = {
        aircaftTypeCode: '',
        aircaftTypeId: '',
        queryParam: ''
      }
      const { data: data1 } = await getAircaftModelAll(getAircaftModelAllParams)
      this.aircaftModelAll = data1
      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.getAirConfigurationAPI({ aircraftType: this.aircaftModelIdList })
        // this.getAirConfigurationAPI()
      }
    },

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

    async removeAirConfigurationAPI(params) {
      try {
        const { code } = await removeAirConfiguration(params)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          await this.getAirConfigurationAPI({ aircraftType: 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 getAirConfigurationAPI(params) {
      if (this.$refs.table) this.$refs.table.clearSelection()
      const { keyWord } = this
      const { pageSize, pageIndex } = this.tableRequset
      const { data, code } = await getAirConfiguration({ pageSize, pageNum: pageIndex, ...params })
      if (code === 200) {
        this.tableData = []
        if (!(this.currentNode.type == 1 && this.currentNode.children.length == 0)) {
          if (data?.length !== 0) {
            const allData = handleTree(data, 'id')
            this.tableData = allData
          }
        } else {
          const menu = { id: 1, aircraftType: this.currentNode.id, name: '整机', children: [] }
          menu.children = handleTree(data, 'id')
          this.tableData.push(menu)
        }
      }
    },

    fetch() {
      this.getAirConfigurationAPI({ aircraftType: this.aircaftModelIdList })
    },

    searchClick() {
      this.getAirConfigurationAPI({ aircraftType: this.aircaftModelIdList, name: this.keyWordData })
    },

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

    async updateAirConfigurationAPI() {
      try {
        const { code } = await updateAirConfiguration({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getAirConfigurationAPI({ aircraftType: this.aircaftModelIdList })
        }
      } catch (error) {}
    },

    treeNodeClick(data) {
      this.$refs.table.clearSelection()
      this.currentNodeKey = data.id
      this.currentNode = data
      console.log('this.currentNode', this.currentNode)
      this.aircaftModelIdList = this.getTreeLeafData(data.children.length ? data.children : [data])
        .map((e) => e.id)
        .toString()
      this.getAirConfigurationAPI({ aircraftType: this.aircaftModelIdList })
    },

    openDialog() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.form.aircraftType = this.currentNodeKey
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        aircraftType: '',
        conCode: '',
        name: '',
        specsModel: '',
        drawingNumber: '',
        supplier: '',
        remarks: '',
        tenantId: '',
        delFlag: '',
        version: '',
        createdBy: '',
        createdTime: '',
        updatedBy: '',
        updatedTime: ''
      }
    },

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

    submit() {
      switch (this.dialogTitle) {
        case '编辑':
          this.updateAirConfigurationAPI()
          this.handleClose()
          break
        case '新增':
          this.addAirConfigurationAPI()
          this.handleClose()
          break
      }
    },

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

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

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