<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 === ''">新增</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="keyWord" 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="devicesEncode">
            <el-input v-model="form.devicesEncode" placeholder="请输入航材编码" />
          </el-form-item>
          <el-form-item label="器材代码" prop="devicesCode">
            <el-input v-model="form.devicesCode" placeholder="请输入航材代码" />
          </el-form-item>
          <el-form-item label="器材名称" prop="devicesName">
            <el-input v-model="form.devicesName" 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="category">
            <el-input v-model="form.category" placeholder="请输入所属分类" />
          </el-form-item>
          <el-form-item label="装机数量" prop="quantity">
            <el-input v-model="form.quantity" placeholder="请输入装机数量" />
          </el-form-item>
          <el-form-item label="装机时间" prop="installTime">
            <el-date-picker v-model="form.installTime" type="date" placement="bottom-start" value-format="yyyy-MM-dd" placeholder="请选择装机时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="软件版本" prop="softwareVersion">
            <el-input v-model="form.softwareVersion" placeholder="请输入软件版本" />
          </el-form-item>
          <el-form-item label="是否可修" prop="repairable">
            <el-select v-model="form.repairable" placeholder="请选择是否可修">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否成套" prop="completeSet">
            <el-select v-model="form.completeSet" placeholder="请选择是否成套">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否有寿" prop="serviceLife">
            <el-select v-model="form.serviceLife" placeholder="请选择是否有寿">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" :rows="2" 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 { getAirInstall, addAirInstall, updateAirInstall, removeAirInstall } from '@/api/als/airInstall'
import { getAircaftCatalogTree, getAircaftTypeAndModelTree } from '@/api/als/sideTree'
import { getAircaftModelAll, getAircaftCatalogAll } from '@/api/als/aircraft'
import { getAirConfiguration } from '@/api/als/airConfiguration'
import { deepClone, debounce } from '@/utils/index'
import { handleTree } from '../utils/common'
export default {
  name: 'AirInstall',
  components: {},
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      keyWord: '',
      aircaftConfigIdList: [],
      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: 'devicesEncode',
          label: '器材编码'
        },
        {
          prop: 'devicesCode',
          label: '器材代码'
        },
        {
          prop: 'devicesName',
          label: '器材名称'
        },
        {
          prop: 'specsModel',
          label: '规格型号'
        },
        {
          prop: 'drawingNumber',
          label: '图号'
        },
        {
          prop: 'category',
          label: '所属分类'
        },
        {
          prop: 'quantity',
          label: '装机数量'
        },
        {
          prop: 'installTime',
          label: '装机时间'
        },
        {
          prop: 'softwareVersion',
          label: '软件版本'
        },
        {
          prop: 'repairable',
          label: '是否可修',
          render: (h, params) => {
            if (params.row.repairable == 1) {
              return h('span', '是')
            } else {
              return h('span', '否')
            }
          }
        },
        {
          prop: 'completeSet',
          label: '是否成套',
          render: (h, params) => {
            if (params.row.completeSet == 1) {
              return h('span', '是')
            } else {
              return h('span', '否')
            }
          }
        },
        {
          prop: 'serviceLife',
          label: '是否有寿',
          render: (h, params) => {
            if (params.row.serviceLife == 1) {
              return h('span', '是')
            } else {
              return h('span', '否')
            }
          }
        },
        {
          button: true,
          label: '操作',
          width: '200px',
          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: false, // 多选框
        index: true, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: 'calc(100vh - 300px)'
      },
      tableCheckItems: [],
      tableData: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      form: {
        id: '',
        configId: '',
        devicesEncode: '',
        devicesCode: '',
        devicesName: '',
        specsModel: '',
        drawingNumber: '',
        category: '',
        quantity: '',
        installTime: '',
        softwareVersion: '',
        repairable: '',
        completeSet: '',
        serviceLife: '',
        remarks: '',
        tenantId: '',
        delFlag: '',
        version: '',
        createdBy: '',
        createdTime: '',
        updatedBy: '',
        updatedTime: ''
      },
      debounceFn: debounce(this.fetch, 500)
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getAircaftCatalogTreeAPI()
  },
  methods: {
    async getAircaftCatalogTreeAPI(params) {
      const { data } = await getAircaftCatalogTree(params)
      this.menuTreeData = data
      // if (data.length) {
      //   this.currentNodeKey = data[0].id
      //   this.currentNode = data[0]
      //   this.getAirInstallAPI()
      // }
    },

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

    fetch() {
      this.getAirInstallAPI({ configId: this.currentConfigNodeKey })
    },

    searchClick() {
      this.getAirInstallAPI({ configId: this.currentConfigNodeKey })
    },

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

    async updateAirInstallAPI() {
      try {
        const { code } = await updateAirInstall({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose()
          this.getAirInstallAPI({ configId: this.currentConfigNodeKey })
        }
      } catch (error) {}
    },

    async treeNodeClick(data) {
      // this.$refs.table.clearSelection()
      // this.currentNodeKey = this.form.aircraftId = data.id
      // this.currentNode = data
      // this.form.aircraftType = data.label
      // this.getAirInstallAPI(this.currentNodeKey)
      console.log('data', data)
      this.configTreeData = []
      const { data: data1 } = await getAirConfiguration({ aircraftType: data.parentId })
      const topNode = { id: 1, name: '整机', children: [] }
      // topNode.children = data1
      topNode.children = handleTree(data1, 'id')
      this.configTreeData.push(topNode)
    },

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

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

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        configId: '',
        devicesEncode: '',
        devicesCode: '',
        devicesName: '',
        specsModel: '',
        drawingNumber: '',
        category: '',
        quantity: '',
        installTime: '',
        softwareVersion: '',
        repairable: '',
        completeSet: '',
        serviceLife: '',
        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.updateAirInstallAPI()
          break
        case '新增':
          this.addAirInstallAPI()
          break
      }
    },

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

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

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