<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 && currentNode.children.length == 0)">新增</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" style="height: 50vh; overflow-y: scroll">
          <!-- <el-form-item label="飞机编码" prop="aircraftCode">
            <el-input v-model="form.aircraftCode" placeholder="请输入飞机编码" />
          </el-form-item> -->
          <el-form-item label="编目" prop="aircraftCode">
            <el-select v-model="form.aircraftCode" placeholder="请选择编目" 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="换件前器材编码" label-width="120px" prop="beforeEquipmentCode">
            <el-input v-model="form.beforeEquipmentCode" placeholder="请输入换件前器材编码" />
          </el-form-item>
          <el-form-item label="换件前器材名称" label-width="120px" prop="beforeEquipmentName">
            <el-input v-model="form.beforeEquipmentName" placeholder="请输入换件前器材名称" />
          </el-form-item>
          <el-form-item label="换件前规格型号" label-width="120px" prop="beforeModelNumber">
            <el-input v-model="form.beforeModelNumber" placeholder="请输入换件前规格型号" />
          </el-form-item>
          <el-form-item label="换件后器材编码" label-width="120px" prop="afterEquipmentCode">
            <el-input v-model="form.afterEquipmentCode" placeholder="请输入换件后器材编码" />
          </el-form-item>
          <el-form-item label="换件后器材名称" label-width="120px" prop="afterEquipmentName">
            <el-input v-model="form.afterEquipmentName" placeholder="请输入换件后器材名称" />
          </el-form-item>
          <el-form-item label="换件后规格型号" label-width="120px" prop="afterModelNumber">
            <el-input v-model="form.afterModelNumber" 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="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 { getPartReplacement, addPartReplacement, updatePartReplacement, removePartReplacement } from '@/api/als/partReplacement'
import { getAircaftCatalogTree, getAircaftTypeAndModelTree } from '@/api/als/sideTree'
import { getAircaftModelAll, getAircaftCatalogAll } from '@/api/als/aircraft'
import { deepClone, debounce } from '@/utils/index'
export default {
  name: 'PartReplacement',
  components: {},
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      keyWordData: '',
      aircraftCodeIdList: [],
      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: 'aircraftCode',
          label: '编目',
          render: (h, params) => {
            const matchedItem = this.aircaftCatalogAll.find((item) => params.row.aircraftCode.trim() === item.aircaftCatalogId.trim())
            if (matchedItem) {
              return h('span', matchedItem.aircaftCatalogCode)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          prop: 'beforeEquipmentCode',
          label: '换件前器材编码'
        },
        {
          prop: 'beforeEquipmentName',
          label: '换件前器材名称'
        },
        {
          prop: 'beforeModelNumber',
          label: '换件前规格型号'
        },
        {
          prop: 'afterEquipmentCode',
          label: '换件后器材编码'
        },
        {
          prop: 'afterEquipmentName',
          label: '换件后器材名称'
        },
        {
          prop: 'afterModelNumber',
          label: '换件后规格型号'
        },
        {
          prop: 'quantity',
          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)'
      },
      tableCheckItems: [],
      tableData: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      form: {
        id: '',
        aircraftCode: '',
        beforeEquipmentCode: '',
        beforeEquipmentName: '',
        beforeModelNumber: '',
        afterEquipmentCode: '',
        afterEquipmentName: '',
        afterModelNumber: '',
        quantity: '',
        remarks: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftCatalogAll: []
    }
  },
  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.aircraftCodeIdList = this.getTreeLeafData(data[0]?.children)
          .map((e) => e.id)
          .toString()
        this.getPartReplacementAPI({ aircraftCode: this.aircraftCodeIdList })
        // this.getPartReplacementAPI()
      }
    },

    async removePartReplacementAPI(params) {
      try {
        const { code } = await removePartReplacement(params)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          await this.getPartReplacementAPI({ aircraftCode: this.aircraftCodeIdList })
          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 getPartReplacementAPI(params) {
      if (this.$refs.table) this.$refs.table.clearSelection()
      const { keyWord } = this
      const { pageSize, pageIndex } = this.tableRequset
      const {
        data: { list, total }
      } = await getPartReplacement({ pageSize, pageNum: pageIndex, ...params })
      this.tableData = list
      this.tableRequset.total = total
    },

    fetch() {
      this.getPartReplacementAPI({ aircraftCode: this.aircraftCodeIdList })
    },

    async searchClick() {
      this.getPartReplacementAPI({ aircraftCode: this.aircraftCodeIdList, beforeEquipmentName: this.keyWordData })
    },

    async addPartReplacementAPI() {
      try {
        delete this.form.aircaftModelName
        const { code } = await addPartReplacement({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getPartReplacementAPI({ aircraftCode: this.aircraftCodeIdList })
        }
      } catch (error) {}
    },

    async updatePartReplacementAPI() {
      try {
        const { code } = await updatePartReplacement({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getPartReplacementAPI({ aircraftCode: this.aircraftCodeIdList })
        }
      } catch (error) {}
    },

    treeNodeClick(data) {
      this.$refs.table.clearSelection()
      this.currentNodeKey = data.id
      this.currentNode = data
      this.aircraftCodeIdList = this.getTreeLeafData(data.children.length ? data.children : [data])
        .map((e) => e.id)
        .toString()
      this.getPartReplacementAPI({ aircraftCode: this.aircraftCodeIdList })
    },

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

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        aircraftCode: '',
        beforeEquipmentCode: '',
        beforeEquipmentName: '',
        beforeModelNumber: '',
        afterEquipmentCode: '',
        afterEquipmentName: '',
        afterModelNumber: '',
        quantity: '',
        remarks: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      }
    },

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

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

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

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

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