<template>
  <div class="view-dataSailingMaterialMaterialCoding">
    <div class="view-dataSailingMaterialMaterialCoding-left">
      <MenuTree :currentNodeKey="currentNodeValue" :nodeKey="nodeKey" :treedata="menuTreeData" @TreeNodeclick="treeNodeClick" v-bind="treeObj"> </MenuTree>
    </div>
    <div class="view-dataSailingMaterialMaterialCoding-right">
      <div class="common-box">
        <div class="common-box-button">
          <el-button type="success" @click="handleAdd" :disabled="currentNodeValue == ''">新增</el-button>
          <el-button
            type="warning"
            @click="
              confirmation(
                {
                  msg: '确认删除当前选中项？'
                },
                () => tableDelete(tableCheckItems)
              )
            "
            :disabled="tableCheckItems.length == 0"
            >删除</el-button
          >
          <el-dropdown split-button type="primary" style="margin-left: 10px" trigger="click" @command="handleExportBtn">
            更多
            <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="common-box-select"></div>
        <div class="common-box-search">
          <el-input placeholder="航材编码/名称/规格型号" v-model="searchValue" class="input-with-select">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
      </div>
      <LTable ref="table" @selection-change="selection" :defaultFetch="false" :columns="columns" :dataSource="tableData" :options="options" :fetch="fetchTableData" :pagination="tableRequset"></LTable>

      <!--  -->
      <CrudDialog v-bind="modalConfig" ref="NewDialogRef" @crudDialogSubmit="crudDialogSubmit"></CrudDialog>
      <!-- 导入 -->
      <ImportDialog ref="ImportDialog" @submitCallBack="ImportDialogCallBack" />
    </div>
  </div>
</template>

<script>
import { MessageBox } from 'element-ui' //这里是引入 element
import { defaultProps, columns, options, modalConfig } from './index'
import { debounce } from '@/utils/index'
import { getAvmatCategoriesTree, getAvmatCatalog, queryByCodeOrName } from '@/api/basicData/dataSpecies'
import { addAvmatCatalog, editAvmatCatalog, removeAvmatCatalog, downLoadFile, exportExcel } from '@/api/basicData/dataSailingMaterialMaterialCoding'
import ImportDialog from './importDialog/index.vue'
import Vue from 'vue'
export default {
  name: 'dataSailingMaterialMaterialCoding',
  components: { ImportDialog },
  data() {
    // 这里存放数据
    return {
      nodeKey: 'avmatCategoriesId',
      currentNodeValue: '',
      menuTreeData: [],
      treeObj: {
        title: '所属分类',
        activityheight: '275px',
        searchIcon: false,
        configure: defaultProps
      },
      options,
      columns: columns(this),
      modalConfig: modalConfig(this),
      tableData: [],
      defaultcheCkedKeys: ['1'],
      searchValue: '',
      debounceFn: debounce(this.fetchTableData2, 500),
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 20
      },
      tableCheckItems: [],
      removeArr: []
    }
  },
  mounted() {
    this.getData()
  },
  watch: {
    searchValue: function () {
      this.debounceFn()
    }
  },
  methods: {
    async getData() {
      const { data } = await getAvmatCategoriesTree()
      let obj = {
        avmatCategoriesId: '',
        avmatCategoriesCode: '',
        avmatCategoriesName: '全部',
        children: data
      }
      this.menuTreeData = [obj]
      this.currentNodeValue = ''
      this.fetchTableData()
    },

    treeNodeClick(node) {
      this.searchValue = ''
      this.currentNodeValue = node[this.nodeKey]
      this.fetchTableData()
    },

    async fetchTableData() {
      this.$refs.table.clearSelection()
      let params = {
        pageSize: this.tableRequset.pageSize,
        pageIndex: this.tableRequset.pageIndex,
        avmatCategoriesId: this.currentNodeValue,
        avmatType: 1
      }
      const { data } = await getAvmatCatalog(params)
      this.tableData = data.list
      this.tableRequset.total = data.totalCount
    },

    async fetchTableData2() {
      let params = {
        pageSize: this.tableRequset.pageSize,
        pageIndex: 1,
        queryParam: this.searchValue,
        avmatType: 1
      }
      this.currentNodeValue = ''
      const { data } = await queryByCodeOrName(params)
      this.tableData = data.list
      this.tableRequset.total = data.totalCount
    },

    // 单选
    selection(val) {
      this.tableCheckItems = val
    },

    handleExport(type) {
      let msg = ''
      type == '下载模板' ? (msg = '是否确认下载该模板') : (msg = `是否${type}该航材`)
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        })
        .catch(() => {})
    },

    getClassification(node) {
      let { classificationName } = node
      Vue.set(this.$refs.NewDialogRef.formData, 'classificationName', classificationName)
      this.$refs.NewDialogRef.$refs.onTreeSelect && this.$refs.NewDialogRef?.$refs.onTreeSelect[0].blur()
    },

    confirmation(params, fun) {
      const { msg = '', title = '提示', confirmButtonText = '确定', cancelButtonText = '取消' } = params
      MessageBox.confirm(msg, title, {
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
        type: 'warning'
      })
        .then(() => {
          fun()
        })
        .catch(() => {})
    },

    handleAdd() {
      let config = {
        type: 'add',
        dataShow: {
          isRepairable: 1,
          isCompleteSet: 1,
          isOrdered: 1,
          isImported: 1
        },
        title: '新增'
      }
      this.$refs.NewDialogRef.open(config)
    },

    handUpdate(row) {
      let config = {
        type: 'update',
        dataShow: row, // 回填的值（字段对应上）
        title: '编辑'
      }
      this.$refs.NewDialogRef.open(config)
    },

    async tableDelete(params) {
      const { success } = await removeAvmatCatalog(params.map((e) => e.avmatCatalogId))
      if (success) {
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
        this.fetchTableData()
      }
    },

    async add(params) {
      try {
        const { success } = await addAvmatCatalog({ avmatType: 1, avmatCategoriesId: this.currentNodeValue, ...params })
        if (success) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchTableData()
        }
      } catch (error) {}
    },

    async update(params) {
      try {
        const { success } = await editAvmatCatalog({ avmatType: 1, avmatCategoriesId: this.currentNodeValue, ...params })
        if (success) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchTableData()
        }
      } catch (error) {}
    },

    crudDialogSubmit(data) {
      const { dialogData, type } = data
      switch (type) {
        case 'add':
          this.add(dialogData)
          break
        case 'update':
          this.update(dialogData)
          break
      }
    },
    //更多按钮
    handleExportBtn(type) {
      this[type]()
    },
    //导入
    importOperation() {
      this.$refs.ImportDialog.triggerDialog()
    },
    //导入回写
    ImportDialogCallBack() {
      this.fetchTableData()
    },

    //导出全部
    async allExport() {
      const userInfo = this.$store.state.user.userInfo.user
      const params = {
        queryParam: this.queryParam,
        avmatCategoriesId: this.currentNodeValue,
        userId: userInfo.userId,
        avmatType: 1
      }
      await exportExcel(params)
    },
    //下载模板
    async downloadTemplate() {
      const params = {
        avmatType: 1
      }
      await downLoadFile(params)
    }
  }
}
</script>

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