<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 == 2)">新增</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">
          <!-- <el-form-item label="文件编号" prop="ossId">
            <el-input v-model="form.ossId" placeholder="请输入文件编号" />
          </el-form-item> -->
          <el-form-item label="数据源" prop="source">
            <el-select v-model="form.source" placeholder="请选择数据源" disabled>
              <el-option label="飞参数据" value="1"></el-option>
              <el-option label="MDC数据" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="机型" prop="aircaftModel">
            <el-select v-model="form.aircaftModel" 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="aircraftId">
            <el-select v-model="form.aircraftId" 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="sortieNo">
            <!-- <el-input v-model="form.sortieNo" placeholder="请输入架次号" /> -->
            <el-select v-model="form.sortieNo" placeholder="请选择架次号">
              <el-option v-for="item in sortieNoList" :key="item.taskId" :label="item.taskName" :value="item.taskId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据导入" prop="ossId">
            <FileUpload v-model="form.ossId" :limit="1" :fileSize="500" :fileType="['xls', 'xlsx']" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" :loading="submitBtnLoading" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getDataImport, addDataImport, updateDataImport, removeDataImport } from '@/api/als/dataImport'
import { getAircaftCatalogTree } from '@/api/als/sideTree'
import { getAircaftModelAll, getAircaftCatalogAll, getSortieNo } from '@/api/als/aircraft'
import { getTaskExecondRegister } from '@/api/carrierStandard/carrierListExecutionRegistration'
import { deepClone, debounce } from '@/utils/index'
import FileUpload from '@/views/als/components/FileUpload'
import { flattenTree } from '../utils/common'

export default {
  name: 'MDCData',
  components: { FileUpload },
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      keyWordData: '',
      submitBtnLoading: false,
      aircaftModelIdList: [],
      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: 'aircraftId',
          label: '编目',
          render: (h, params) => {
            const matchedItem = this.aircaftCatalogAll.find((item) => params.row.aircraftId.trim() === item.aircaftCatalogId.trim())
            if (matchedItem) {
              return h('span', matchedItem.aircaftCatalogCode)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          prop: 'sortieNo',
          label: '架次号',
          render: (h, params) => {
            const matchedItem = this.allTaskExecond.find((item) => params.row.sortieNo.trim() === item.taskId.trim())
            if (matchedItem) {
              return h('span', matchedItem.taskName)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          prop: 'source',
          label: '数据源',
          render: (h, params) => {
            if (params.row.source == 1) {
              return h('span', { class: 'success-state' }, '飞参数据')
            } else {
              return h('span', { class: 'success-state' }, 'MDC数据')
            }
          }
        },
        {
          prop: 'ossId',
          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: 20,
        searchValue: ''
      },
      form: {
        id: '',
        ossId: '',
        source: '2',
        aircaftModel: '',
        aircraftId: '',
        sortieNo: '',
        flightDate: '',
        status: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftModelAll: [],
      aircaftCatalogAll: [],
      sortieNoList: [],
      allTaskExecond: []
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getAircaftCatalogTreeAPI()
  },
  methods: {
    async getAircaftCatalogTreeAPI(params) {
      try {
        const { data } = await getAircaftCatalogTree(params)
        this.menuTreeData = data
        const getAircaftModelAllParams = {
          aircaftTypeCode: '',
          aircaftTypeId: '',
          queryParam: ''
        }
        const { data: data1 } = await getAircaftModelAll(getAircaftModelAllParams)
        this.aircaftModelAll = data1
        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.aircaftModelIdList = this.getTreeLeafData(data[0]?.children)
            .map((e) => e.id)
            .toString()

          this.getDataImportAPI({ aircraftId: this.aircaftModelIdList })
        }
        const res = await getTaskExecondRegister({
          status: null,
          queryParam: '',
          taskId: '',
          aircaftCatalogId: ''
        })
        this.allTaskExecond = flattenTree(res.data)
      } catch (error) {}
    },

    async removeDataImportAPI(params) {
      try {
        const { code } = await removeDataImport(params)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          await this.getDataImportAPI({ aircraftId: this.aircaftModelIdList })
          this.handleClose()
        }
      } catch (error) {}
    },

    getTreeLeafData(list) {
      const newArr = []
      function getLeaf(data, arr) {
        data.forEach((e) => {
          if (e.type === 2) {
            arr.push(e)
          }
          if (e.children.length) {
            getLeaf(e.children, arr)
          }
        })
      }
      getLeaf(list, newArr)
      return newArr
    },

    async getDataImportAPI(params) {
      if (this.$refs.table) this.$refs.table.clearSelection()
      const { keyWord } = this
      const { pageSize, pageIndex } = this.tableRequset
      const {
        data: { list, total }
      } = await getDataImport({ pageSize, pageNum: pageIndex, ...params, source: 2 })
      this.tableData = list
      this.tableRequset.total = total
    },

    fetch() {
      this.getDataImportAPI({ aircraftId: this.aircaftModelIdList })
    },

    searchClick() {
      this.getDataImportAPI({ aircraftId: this.aircaftModelIdList, sortieNo: this.keyWordData })
    },

    async addDataImportAPI() {
      try {
        delete this.form.aircaftModelName
        const { code } = await addDataImport({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.submitBtnLoading = false
          this.handleClose()
          this.getDataImportAPI({ aircraftId: this.aircaftModelIdList })
        }
      } catch (error) {}
    },

    async updateDataImportAPI() {
      try {
        const { code } = await updateDataImport({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.submitBtnLoading = false
          this.handleClose()
          this.getDataImportAPI({ aircraftId: this.aircaftModelIdList })
        }
      } catch (error) {}
    },

    treeNodeClick(data) {
      this.$refs.table.clearSelection()
      this.currentNodeKey = data.id
      this.currentNode = data
      this.aircaftModelIdList = this.getTreeLeafData(data.children.length ? data.children : [data])
        .map((e) => e.id)
        .toString()
      if (!this.aircaftModelIdList) {
        this.aircaftModelIdList = '#'
      }
      this.getDataImportAPI({ aircraftId: this.aircaftModelIdList })
      this.getSortieNoAPI(data.label)
    },

    async getSortieNoAPI(aircaftCatalogCode) {
      const res = await getSortieNo({ aircaftCatalogCode })
      this.sortieNoList = res.data.filter((item) => {
        return item.taskName
      })
    },

    openDialog() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.form.aircraftId = this.currentNodeKey
      this.form.aircaftModel = this.currentNode.parentId
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        ossId: '',
        source: '2',
        aircaftModel: '',
        sortieNo: '',
        aircraftId: '',
        flightDate: '',
        status: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      }
    },

    handUpdate(row) {
      this.dialogTitle = '编辑'

      const matchedItem = this.aircaftCatalogAll.find((item) => row.aircraftId.trim() === item.aircaftCatalogId.trim())

      this.getSortieNoAPI(matchedItem.aircaftCatalogCode)
      this.form = deepClone(row)
      console.log('this.form', this.form)
      this.dialogVisible = true
    },

    submit() {
      switch (this.dialogTitle) {
        case '编辑':
          this.submitBtnLoading = true
          this.updateDataImportAPI()
          break
        case '新增':
          this.submitBtnLoading = true
          this.addDataImportAPI()
          break
      }
    },

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

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

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