<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">
      <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>
          <el-dropdown split-button type="primary" style="margin-left: 10px" trigger="click" @command="handleExport">
            更多
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="importOperation">导入</el-dropdown-item>
              <el-dropdown-item command="allExport" :disabled="tableData.length == 0">导出</el-dropdown-item>
              <el-dropdown-item command="downloadTemplate">下载数据模板</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </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" :rules="rules" label-width="80px">
          <el-form-item label="机型" prop="airModelId">
            <el-select v-model="form.airModelId" 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="airId">
            <el-select v-model="form.airId" 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="构型" prop="configId">
            <el-select v-model="form.configId" placeholder="请选择构型" disabled>
              <el-option v-for="item in configAll" :key="item.id" :label="item.name" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="部件名称" prop="componentName">
            <el-input v-model="form.componentName" placeholder="请输入部件名称" />
          </el-form-item>
          <el-form-item label="部件型号" prop="componentModel">
            <el-input v-model="form.componentModel" placeholder="请输入部件型号" />
          </el-form-item>
          <el-form-item label="部件编码" prop="componentNum">
            <el-input v-model="form.componentNum" placeholder="请输入部件编码" />
          </el-form-item>
          <el-form-item label="出厂日期" prop="factoryDate">
            <el-date-picker clearable v-model="form.factoryDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择出厂日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="当前安装飞机" prop="currentInstallAircraft">
            <el-input v-model="form.currentInstallAircraft" placeholder="请输入当前安装飞机" />
          </el-form-item>
          <el-form-item label="工作时次" prop="workTime">
            <el-input v-model="form.workTime" placeholder="请输入工作时次" />
          </el-form-item>
          <el-form-item label="额定寿命" prop="ratedLifetime">
            <el-input v-model="form.ratedLifetime" placeholder="请输入额定寿命" />
          </el-form-item>
          <el-form-item label="剩余寿命" prop="remainingLifetime">
            <el-input v-model="form.remainingLifetime" 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>
      <!-- 导入 -->
      <ImportDialog ref="ImportDialog" @submitCallBack="ImportDialogCallBack" />
    </div>
  </div>
</template>

<script>
import { getLifetimeSpareParts, addLifetimeSpareParts, updateLifetimeSpareParts, removeLifetimeSpareParts, downLoadLifetimeSpareParts, exportLifetimeSparePartsExcel } from '@/api/als/lifetimeSpareParts'
import { getAircaftCatalogTree, getAircaftTypeAndModelTree } from '@/api/als/sideTree'
import { getAvmatCatalog } from '@/api/basicData/dataSailingMaterialMaterialCoding'
import { getAirConfiguration } from '@/api/als/airConfiguration'
import { deepClone, debounce } from '@/utils/index'
import { handleTree, flattenTree } from '../utils/common'
import { getAircaftModelAll, getAircaftCatalogAll } from '@/api/als/aircraft'
import ImportDialog from './importDialog/index.vue'
export default {
  name: 'LifetimeSpareParts',
  components: { ImportDialog },
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      keyWord: '',
      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: 'id', label: '编号' },
        {
          prop: 'airModelId',
          label: '机型',
          render: (h, params) => {
            const matchedItem = this.aircaftModelAll.find((item) => params.row.airModelId === item.aircaftModelId)
            if (matchedItem) {
              return h('span', matchedItem.aircaftModelName)
            } else {
              return h('span', params.row.airModelId)
            }
          }
        },
        {
          prop: 'airId',
          label: '编目',
          render: (h, params) => {
            const matchedItem = this.aircaftCatalogAll.find((item) => params.row.airId.trim() === item.aircaftCatalogId.trim())
            if (matchedItem) {
              return h('span', matchedItem.aircaftCatalogCode)
            } else {
              return h('span', params.row.airId)
            }
          }
        },
        {
          prop: 'configId',
          label: '构型',
          render: (h, params) => {
            const matchedItem = this.configAll.find((item) => params.row.configId.trim() === item.id.trim())
            if (matchedItem) {
              return h('span', matchedItem.name)
            } else {
              return h('span', params.row.configId)
            }
          }
        },
        {
          prop: 'componentName',
          label: '部件名称'
        },
        {
          prop: 'componentModel',
          label: '部件型号'
        },
        {
          prop: 'componentNum',
          label: '部件编码'
        },
        {
          prop: 'factoryDate',
          label: '出厂日期'
        },
        {
          prop: 'currentInstallAircraft',
          label: '当前安装飞机'
        },
        {
          prop: 'workTime',
          label: '工作时次'
        },
        {
          prop: 'ratedLifetime',
          label: '额定寿命'
        },
        {
          prop: 'remainingLifetime',
          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: [],
      avmatTableData: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 20,
        searchValue: ''
      },
      avmatTableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 20,
        searchValue: ''
      },
      form: {
        id: '',
        airId: '',
        airModelId: '',
        configId: '',
        componentName: '',
        componentModel: '',
        componentNum: '',
        factoryDate: '',
        currentInstallAircraft: '',
        workTime: '',
        ratedLifetime: '',
        remainingLifetime: '',
        remarks: '',
        tenantId: '',
        delFlag: '',
        version: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftModelAll: [],
      aircaftCatalogAll: [],
      configAll: [],
      rules: {
        airId: [{ required: true, message: '编目不能为空', trigger: 'blur' }],
        airModelId: [{ required: true, message: '机型不能为空', trigger: 'blur' }],
        configId: [{ required: true, message: '构型不能为空', trigger: 'blur' }],
        componentName: [{ required: true, message: '部件名称不能为空', trigger: 'blur' }],
        componentModel: [{ required: true, message: '部件型号不能为空', trigger: 'blur' }],
        componentNum: [{ required: true, message: '部件编码不能为空', trigger: 'blur' }],
        factoryDate: [{ required: true, message: '出厂日期不能为空', trigger: 'blur' }],
        currentInstallAircraft: [{ required: true, message: '当前安装飞机不能为空', trigger: 'blur' }],
        workTime: [{ required: true, message: '工作时次不能为空', trigger: 'blur' }],
        ratedLifetime: [{ required: true, message: '额定寿命不能为空', trigger: 'blur' }]
      }
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getAircaftTypeAndModelTreeAPI()
  },
  methods: {
    async getAircaftTypeAndModelTreeAPI(params) {
      const { data } = await getAircaftCatalogTree(params)
      this.menuTreeData = data
      const { pageSize, pageIndex } = this.avmatTableRequset
      const {
        data: { list, totalCount }
      } = await getAvmatCatalog({
        pageIndex,
        pageSize,
        avmatCategoriesId: '',
        avmatType: '1'
      })
      this.avmatTableData = flattenTree(list)
      this.avmatTableRequset.total = totalCount
      const getAircaftModelAllParams = {
        aircaftTypeCode: '',
        aircaftTypeId: '',
        queryParam: ''
      }
      const { data: data1 } = await getAircaftModelAll(getAircaftModelAllParams)
      this.aircaftModelAll = data1
      const { data: data2 } = await getAircaftCatalogAll({
        keyWord: '',
        aircaftModelIdList: []
      })
      this.aircaftCatalogAll = flattenTree(data2)
    },

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

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

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

    async addLifetimeSparePartsAPI() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          try {
            delete this.form.aircaftModelName
            const { code } = await addLifetimeSpareParts({ ...this.form })
            if (code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getLifetimeSparePartsAPI({ configId: this.currentConfigNodeKey })
              this.handleClose()
            }
          } catch (error) {}
        }
      })
    },

    async updateLifetimeSparePartsAPI() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          try {
            const { code } = await updateLifetimeSpareParts({ ...this.form })
            if (code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getLifetimeSparePartsAPI({ configId: this.currentConfigNodeKey })
              this.handleClose()
            }
          } catch (error) {}
        }
      })
    },

    async treeNodeClick(data) {
      // this.$refs.table.clearSelection()
      this.currentAirId = this.form.airId = data.id
      this.currentAirModelId = this.form.airModelId = data.parentId
      // this.currentNode = data
      // this.form.aircraftType = data.label
      // this.getAirInstallAPI(this.currentNodeKey)
      let dataTree = []
      if (data.type === 1) {
        const { data: data1 } = await getAirConfiguration({ aircraftType: data.id })
        dataTree = data1
      } else if (data.type === 2) {
        const { data: data1 } = await getAirConfiguration({ aircraftType: data.parentId })
        dataTree = data1
      }
      this.configAll = dataTree
      this.configTreeData = []
      const topNode = { id: 1, name: '整机', children: [] }
      // topNode.children = data1
      topNode.children = handleTree(dataTree, 'id')
      this.configTreeData.push(topNode)
      console.log(this.aircaftModelAll)
      console.log(this.aircaftCatalogAll)
      console.log(this.configAll)
    },

    treeConfigNodeClick(data) {
      this.$refs.table.clearSelection()
      this.currentConfigNodeKey = this.form.configId = data.id
      this.currentConfigNode = data
      // const dataTree = this.configTreeData
      // console.log('dataTree', dataTree)
      // this.configNodeIdList = String(this.getAllTreeData(dataTree[0].children.length ? dataTree[0].children : [dataTree[0]]).map((e) => e.id))
      // console.log('this.configNodeIdList', this.configNodeIdList)
      // this.getAirInstallAPI({ configId: this.configNodeIdList })
      this.getLifetimeSparePartsAPI({ configId: this.currentConfigNodeKey })
    },

    openDialog() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.form.aircaftModelName = this.currentNode.label
      this.form.aircaftModelId = this.currentNode.id
    },

    handleClose() {
      this.dialogVisible = false
      this.form.componentName = ''
      this.form.componentModel = ''
      this.form.componentNum = ''
      this.form.factoryDate = ''
      this.form.currentInstallAircraft = ''
      this.form.workTime = ''
      this.form.ratedLifetime = ''
      this.form.remainingLifetime = ''
      this.form.remarks = ''
      this.form.tenantId = ''
      this.form.delFlag = ''
      this.form.version = ''
      this.form.createBy = ''
      this.form.createTime = ''
      this.form.updateBy = ''
      this.form.updateTime = ''
    },

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

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

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

    remove(row) {
      this.$confirm('是否删除该机种', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.removeLifetimeSparePartsAPI(row.map((e) => e.id))
        })
        .catch(() => {})
    },
    //更多按钮
    handleExport(type) {
      this[type]()
    },
    //导入
    importOperation() {
      this.$refs.ImportDialog.triggerDialog()
    },
    //导入回写
    ImportDialogCallBack() {
      this.getAircaftTypeAndModelTreeAPI()
    },
    //导出全部
    async allExport() {
      // const params = {
      //   queryParam: this.searchValue
      // }
      await exportLifetimeSparePartsExcel({})
    },
    //下载模板
    async downloadTemplate() {
      await downLoadLifetimeSpareParts()
    }
  }
}
</script>

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