<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 == 1 && currentNode.children.length == 0)">新增</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="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>
    </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="aircraftType">
          <el-select v-model="form.aircraftType" placeholder="请选择机型">
            <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="aircraftCode">
          <el-select v-model="form.aircraftCode" placeholder="请选择编目">
            <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="dataType">
          <el-select v-model="form.dataType" placeholder="请输入数据来源">
            <el-option v-for="item in dataTypeList" :key="item.id" :label="item.label" :value="item.label"> </el-option>
          </el-select>
          <!-- <el-input v-model="form.dataType" placeholder="请输入所属系统" /> -->
        </el-form-item>
        <el-form-item label="故障代码" prop="faultCode">
          <el-input v-model="form.faultCode" placeholder="请输入故障代码" />
        </el-form-item>
        <el-form-item label="故障描述" prop="faultDescription">
          <el-input v-model="form.faultDescription" placeholder="请输入故障描述" />
        </el-form-item>
        <el-form-item label="故障位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入故障位置" />
        </el-form-item>
        <el-form-item label="故障等级" prop="level">
          <el-select v-model="form.level" placeholder="请输入故障等级">
            <el-option v-for="item in levelList" :key="item.id" :label="item.label" :value="item.label"> </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="故障发生时间" prop="flightDate">
            <el-date-picker v-model="form.flightDate" type="date" value-format="yyyy-MM-dd" placement="bottom-start" placeholder="请选择故障发生时间"> </el-date-picker>
          </el-form-item> -->
        <el-form-item label="故障现象" prop="symptoms">
          <el-input v-model="form.symptoms" placeholder="请输入故障现象" />
        </el-form-item>
        <el-form-item label="故障原因" prop="faultCause">
          <el-input type="textarea" :rows="2" v-model="form.faultCause" 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>
  </div>
</template>

<script>
import { getMaintenanceask, addMaintenanceask, updateMaintenanceask, removeMaintenanceask } from '@/api/als/maintenanceask'
import { getAircaftTypeAndModelTree } from '@/api/als/sideTree'
import { getAircaftModelAll, getAircaftCatalogAll } from '@/api/als/aircraft'
import { deepClone, debounce } from '@/utils/index'
export default {
  name: 'Maintenanceask',
  components: {},
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      detailVisible: 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: 'id', label: '编号' },
        {
          prop: 'aircraftType',
          label: '机型',
          render: (h, params) => {
            const matchedItem = this.aircaftModelAll.find((item) => params.row.aircraftType === item.aircaftModelId)
            if (matchedItem) {
              return h('span', matchedItem.aircaftModelName)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          prop: 'aircraftCode',
          label: '编目',
          render: (h, params) => {
            const matchedItem = this.aircaftCatalogAll.find((item) => params.row.aircraftCode.trim() === item.aircaftCatalogId.trim())
            if (matchedItem) {
              return h('span', matchedItem.aircaftCatalogCode)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          prop: 'faultDescription',
          label: '故障描述'
        },
        {
          prop: 'dataType',
          label: '数据来源'
        },
        {
          prop: 'createTime',
          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' }, '已分配')
            }
          }
        },
        {
          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: '',
        sortieNo: '',
        aircraftId: '',
        systemName: '',
        unitName: '',
        operator: '',
        faultPart: '',
        proposal: '',
        handlerDate: '',
        status: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftModelAll: [],
      aircaftCatalogAll: [],
      dataTypeList: [
        { id: 1, label: '维修决策' },
        { id: 2, label: '定检任务' },
        { id: 3, label: '需要确认' }
      ],
      levelList: [
        { id: 1, label: '一般故障' },
        { id: 2, label: '较大故障' },
        { id: 3, label: '重大故障' }
      ]
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getAircaftTypeAndModelTreeAPI()
  },
  methods: {
    async getAircaftTypeAndModelTreeAPI(params) {
      const { data } = await getAircaftTypeAndModelTree(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 = this.getTreeLeafData(data[0]?.children)
          .map((e) => e.id)
          .toString()
        this.getMaintenanceaskAPI({ aircraftType: this.aircaftModelIdList })
      }
    },

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

    fetch() {
      this.getMaintenanceaskAPI({ aircraftType: this.aircaftModelIdList })
    },

    searchClick() {
      this.getMaintenanceaskAPI({ aircraftType: this.aircaftModelIdList })
    },

    async addMaintenanceaskAPI() {
      try {
        delete this.form.aircaftModelName
        const { code } = await addMaintenanceask({ ...this.form })
        if (code == 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getMaintenanceaskAPI({ aircraftType: this.aircaftModelIdList })
        }
      } catch (error) {}
    },

    async updateMaintenanceaskAPI() {
      try {
        const { code } = await updateMaintenanceask({ ...this.form })
        if (code == 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getMaintenanceaskAPI({ aircraftType: this.aircaftModelIdList })
        }
      } catch (error) {}
    },

    async treeNodeClick(data) {
      this.$refs.table.clearSelection()
      this.currentNodeKey = this.form.aircraftType = data.id
      this.currentNode = data
      this.aircaftModelIdList = this.getTreeLeafData(data.children.length ? data.children : [data])
        .map((e) => e.id)
        .toString()
      this.getMaintenanceaskAPI({ aircraftType: this.aircaftModelIdList })
      const getAircaftCatalogAllParams = {
        keyWord: '',
        aircaftModelIdList: [this.currentNodeKey]
      }
      const { data: data2 } = await getAircaftCatalogAll(getAircaftCatalogAllParams)
      this.aircaftCatalogAll = data2
    },

    openDialog() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.form.aircraftType = this.currentNode.id
      this.form.status = 0
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        sortieNo: '',
        aircraftId: '',
        systemName: '',
        unitName: '',
        operator: '',
        faultPart: '',
        proposal: '',
        handlerDate: '',
        status: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      }
    },

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

    submit() {
      switch (this.dialogTitle) {
        case '编辑':
          this.updateMaintenanceaskAPI()
          this.handleClose()
          break
        case '新增':
          this.addMaintenanceaskAPI()
          this.handleClose()
          break
      }
    },

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

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

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