<template>
  <div class="view-dataType">
    <!-- 通用代码 左侧按钮 右侧输入框 下拉框 -->
    <div class="view-common-header">
      <div class="view-common-header-left">
        <el-button type="success" @click="openDialog()">新增</el-button>
        <el-button type="warning" @click="remove(removeArr)">删除</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-common-header-right">
        <!-- width-137 在style/excel.js 定义宽度 -->
        <el-input @keyup.enter.native="fetchTableData('search')" placeholder="请输入机种名称/编号" v-model="searchValue" class="input-select">
          <el-button @click="fetchTableData('search')" slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </div>
    </div>
    <div class="view-dataType-table">
      <LTable ref="table" @select-all="selectAll" @selection-change="selection" :defaultFetch="false" :columns="columns" :dataSource="tableData" :options="options" :fetch="fetchTableData"></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="上级机种">
          <el-select ref="onSelect" v-model="form.parentTypeId" placeholder="请选择" class="department-select">
            <el-option hidden :value="form.parentTypeId" :label="form.parentTypeName"></el-option>
            <el-tree default-expand-all :data="tableData" :props="typeTree" @node-click="handleNodeClick"></el-tree>
          </el-select>
        </el-form-item>
        <el-form-item label="机种名称" prop="aircaftTypeName">
          <el-input v-model="form.aircaftTypeName"></el-input>
        </el-form-item>
        <el-form-item label="机种编号" prop="aircaftTypeCode">
          <el-input v-model="form.aircaftTypeCode"></el-input>
        </el-form-item>
        <el-form-item label="显示序号" prop="number">
          <el-input v-model="form.number"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleClick">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 导入 -->
    <ImportDialog ref="ImportDialog" @submitCallBack="ImportDialogCallBack" />
  </div>
</template>

<script>
import { getAircaftTypeTree, addAircaftType, updateAircaftType, removeAircaftType, downLoadAircaftTypeFile, exportAircaftTypeExcel } from '@/api/basicData/dataSpecies'
import ImportDialog from './importDialog/index.vue'
import { columns, options, findParents } from './index'

export default {
  name: 'dataType',
  components: { ImportDialog },
  data() {
    // 这里存放数据
    const validInt = (rule, value, callback) => {
      if (Number.isInteger(Number(value)) && Number(value) >= 0) {
        callback()
      } else {
        callback(new Error('请输入正整数'))
      }
    }
    return {
      dialogTitle: '新增机种',
      searchValue: '',
      dialogVisible: false,
      columns: columns(this),
      options,
      tableData: [],
      typeTree: {
        children: 'children',
        label: 'aircaftTypeName'
      },
      form: {
        parentTypeName: '',
        parentTypeId: '',
        aircaftTypeName: '',
        number: '',
        aircaftTypeCode: ''
      },
      rules: {
        aircaftTypeName: [{ required: true, message: '请输入机种名称', trigger: 'blur' }],
        aircaftTypeCode: [{ required: true, message: '请输入机种编号', trigger: 'blur' }],
        number: [
          {
            validator: validInt,
            trigger: 'change'
          }
        ]
      },
      removeArr: [],
      arr: [],
      parentAircaftTypeId: ''
    }
  },
  mounted() {
    this.fetchTableData()
  },
  methods: {
    async fetchTableData() {
      let params = {
        queryParam: this.searchValue
      }
      const { data } = await getAircaftTypeTree(params)
      this.tableData = data
    },
    selectAll(data) {
      this.removeArr = []
      if (data.length > 0) {
        data.forEach((item) => {
          this.removeArr.push(item.aircaftTypeId)
        })
      } else {
        this.removeArr = []
      }
    },
    // 单选
    selection(data) {
      this.arr = data
      this.removeArr = []
      data.forEach((item) => {
        this.removeArr.push(item.aircaftTypeId)
      })
    },
    openDialog() {
      this.dialogTitle = '新增机种'
      this.dialogVisible = true
    },
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].resetFields()
      this.form = {
        parentTypeName: '',
        parentTypeId: '',
        aircaftTypeName: '',
        number: '',
        aircaftTypeCode: ''
      }
      this.parentAircaftTypeId = ''
    },
    handleClick() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          const parentCodes = findParents(this.tableData, this.form.parentTypeId)
          if (this.dialogTitle === '新增机种') {
            let params = {
              parentAircaftTypeCode: this.form.parentTypeId,
              aircaftTypeName: this.form.aircaftTypeName,
              aircaftTypeCode: this.form.aircaftTypeCode,
              number: this.form.number,
              parentCodes: parentCodes ? parentCodes.join() : '',
              parentAircaftTypeId: this.parentAircaftTypeId
            }
            await addAircaftType(params)
          } else {
            let params = {
              parentAircaftTypeCode: this.form.parentTypeId,
              aircaftTypeName: this.form.aircaftTypeName,
              aircaftTypeCode: this.form.aircaftTypeCode,
              number: this.form.number,
              parentCodes: parentCodes ? parentCodes.join() : '',
              aircaftTypeId: this.form.aircaftTypeId
            }
            await updateAircaftType(params)
          }
          this.fetchTableData()
          this.handleClose()
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        } else {
          return false
        }
      })
    },
    handleNodeClick(data) {
      const { aircaftTypeName, aircaftTypeCode, aircaftTypeId } = data
      this.form.parentTypeName = aircaftTypeName
      this.form.parentTypeId = aircaftTypeCode
      this.parentAircaftTypeId = aircaftTypeId
      this.$refs.onSelect.blur()
    },
    handUpdate(row) {
      this.dialogTitle = '编辑机种'
      // this.form = deepClone(row)
      function findName(treeData, id) {
        for (const item of treeData) {
          if (item.aircaftTypeCode === id) {
            return item.aircaftTypeName
          }
          if (item.children && item.children.length) {
            const result = findName(item.children, id)
            if (result) return result
          }
        }
        return null
      }
      const result = findName(this.tableData, row.parentAircaftTypeCode)
      this.form.parentTypeName = result
      this.form.parentTypeId = row.parentAircaftTypeCode
      this.form.aircaftTypeName = row.aircaftTypeName
      this.form.number = row.number
      this.form.aircaftTypeCode = row.aircaftTypeCode
      this.form.aircaftTypeId = row.aircaftTypeId
      this.dialogVisible = true
    },
    toggle(type, row) {
      this.$confirm(`是否${type}该机种`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let params = {
            ...row,
            status: type === '启用' ? 1 : 0
          }
          await updateAircaftType(params)
          this.fetchTableData()
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        })
        .catch(() => {})
    },
    remove(aircaftTypeCodeList) {
      this.$confirm('是否删除该机种', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await removeAircaftType(aircaftTypeCodeList)
          this.fetchTableData()
          this.$refs.table.clearSelection()
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        })
        .catch(() => {})
    },
    //更多按钮
    handleExport(type) {
      this[type]()
    },
    //导入
    importOperation() {
      this.$refs.ImportDialog.triggerDialog()
    },
    //导入回写
    ImportDialogCallBack() {
      this.fetchTableData()
    },

    //导出全部
    async allExport() {
      const params = {
        queryParam: this.searchValue
      }
      await exportAircaftTypeExcel(params)
    },
    //下载模板
    async downloadTemplate() {
      await downLoadAircaftTypeFile()
    }
  }
}
</script>

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