<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>
          <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" label-width="80px">
          <el-form-item label="机型" prop="aircraftModel">
            <el-select v-model="form.aircraftModel" 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="name">
            <el-input v-model="form.name" placeholder="请输入检查项名称" />
          </el-form-item>
          <el-form-item label="专业" prop="specialty">
            <el-input v-model="form.specialty" placeholder="请输入专业" />
          </el-form-item>
          <el-form-item label="任务编码" prop="taskCode">
            <el-input v-model="form.taskCode" placeholder="请输入任务编码" />
          </el-form-item>
          <el-form-item label="周期" prop="periodTime">
            <el-input v-model="form.periodTime" placeholder="请输入周期" />
          </el-form-item>
          <!-- <el-form-item label="剩余时间" prop="remainTime">
            <el-input v-model="form.remainTime" placeholder="请输入剩余时间" />
          </el-form-item> -->
          <el-form-item label="负责人" prop="headName">
            <el-input v-model="form.headName" placeholder="请输入负责人" />
          </el-form-item>
          <el-form-item label="系统" prop="systemName">
            <el-input v-model="form.systemName" placeholder="请输入系统" />
          </el-form-item>
          <el-form-item label="任务内容" prop="contents">
            <el-input v-model="form.contents" placeholder="请输入任务内容" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" 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 { getSmTask, addSmTask, updateSmTask, removeSmTask, downLoadSmTask, exportSmTask } from '@/api/als/smTask'
import { deepClone, debounce } from '@/utils/index'
import { getAircaftCatalogTree } from '@/api/als/sideTree'
import { getAircaftModelAll, getAircaftCatalogAll } from '@/api/als/aircraft'
import { flattenTree } from '../utils/common'
import ImportDialog from './importDialog/index.vue'

export default {
  name: 'SmTask',
  components: { ImportDialog },
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      keyWord: '',
      aircaftModelIdList: [],
      currentNodeKey: '',
      currentNode: {},
      menuTreeData: [],
      treeObj: {
        title: '所属机种',
        activityheight: '275px',
        searchIcon: false,
        configure: {
          children: 'children',
          label: 'label'
        }
      },
      typeTree: {
        children: 'children',
        label: 'label'
      },
      searchValue: '',
      columns: [
        {
          prop: 'aircraftModel',
          label: '机型',
          render: (h, params) => {
            const matchedItem = this.aircaftModelAll.find((item) => params.row.aircraftModel === item.aircaftModelId)
            if (matchedItem) {
              return h('span', matchedItem.aircaftModelName)
            } else {
              return h('span', params.row.aircraftModel)
            }
          }
        },
        {
          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', params.row.aircraftId)
            }
          }
        },
        {
          prop: 'name',
          label: '检查项名称'
        },
        {
          prop: 'specialty',
          label: '专业'
        },
        {
          prop: 'taskCode',
          label: '任务编码'
        },
        {
          prop: 'periodTime',
          label: '周期'
        },
        // {
        //   prop: 'remainTime',
        //   label: '剩余时间'
        // },
        {
          prop: 'headName',
          label: '负责人'
        },
        {
          prop: 'systemName',
          label: '系统'
        },
        {
          prop: 'contents',
          label: '任务内容'
        },
        // {
        //   prop: 'status',
        //   label: '状态',
        //   render: (h, params) => {
        //     if (params.row.status == 0) {
        //       return h('span', { class: 'warning-state' }, '未分配')
        //     } else {
        //       return h('span', { class: 'success-state' }, '已分配')
        //     }
        //   }
        // },
        {
          prop: 'remark',
          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.checkDetails(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: '',
        aircraftId: '',
        aircraftModel: '',
        name: '',
        specialty: '',
        taskCode: '',
        periodTime: '',
        remainTime: '',
        headName: '',
        systemName: '',
        contents: '',
        status: '',
        remark: ''
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftModelAll: [],
      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 getAircaftModelAllParams = {
        aircaftTypeCode: '',
        aircaftTypeId: '',
        queryParam: ''
      }
      const { data: data1 } = await getAircaftModelAll(getAircaftModelAllParams)
      this.aircaftModelAll = data1
      if (data.length) {
        this.currentNodeKey = data[0].id
        this.currentNode = data[0]
        this.aircaftModelIdList = String(this.getTreeLeafData(data[0]?.children).map((e) => e.id))
        this.getSmTaskAPI({ aircraftId: this.aircaftModelIdList })
      }
      const { data: data2 } = await getAircaftCatalogAll({
        keyWord: '',
        aircaftModelIdList: []
      })
      this.aircaftCatalogAll = flattenTree(data2)
    },

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

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

    searchClick() {
      this.getSmTaskAPI({ aircraftId: this.aircaftModelIdList })
    },

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

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

    async treeNodeClick(data) {
      this.$refs.table.clearSelection()
      this.currentNodeKey = this.form.aircraftId = data.id
      console.log(data)
      this.currentNode = data
      this.aircaftModelIdList = String(this.getTreeLeafData(data.children.length ? data.children : [data]).map((e) => e.id))
      this.getSmTaskAPI({ aircraftId: this.aircaftModelIdList })
    },

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

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        aircraftId: '',
        aircraftModel: '',
        name: '',
        specialty: '',
        taskCode: '',
        periodTime: '',
        remainTime: '',
        headName: '',
        systemName: '',
        contents: '',
        status: '',
        remark: ''
      }
    },

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

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

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

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

    checkDetails(row) {
      // this.$router.push({ name: 'SMTaskDetails', params: { smTaskId: row.id } })
      this.$router.push({
        name: 'SMTaskDetails',
        query: {
          smTaskId: row.id
        }
      })
    },
    //更多按钮
    handleExport(type) {
      this[type]()
    },
    //导入
    importOperation() {
      this.$refs.ImportDialog.triggerDialog()
    },
    //导入回写
    ImportDialogCallBack() {
      this.getAircaftCatalogTreeAPI()
    },
    //导出全部
    async allExport() {
      // const params = {
      //   queryParam: this.searchValue
      // }
      await exportSmTask({})
    },
    //下载模板
    async downloadTemplate() {
      await downLoadSmTask()
    }
  }
}
</script>

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