<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="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" style="height: 50vh; overflow-y: scroll">
          <el-form-item label="机型" prop="aircraftType">
            <el-select v-model="form.aircraftType" 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="serialNumber">
            <el-input v-model="form.serialNumber" 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="systemName">
            <el-input v-model="form.systemName" placeholder="请输入系统" />
          </el-form-item>
          <el-form-item label="发动机型别" prop="engineType" label-width="90px">
            <el-input v-model="form.engineType" placeholder="请输入发动机型别" />
          </el-form-item>
          <el-form-item label="发动机号码" prop="engineSerialNumber" label-width="90px">
            <el-input v-model="form.engineSerialNumber" placeholder="请输入发动机号码" />
          </el-form-item>
          <el-form-item label="单位" prop="unitName">
            <el-input v-model="form.unitName" placeholder="请输入单位" />
          </el-form-item>
          <el-form-item label="故障现象" prop="faultPhenomenon">
            <el-input v-model="form.faultPhenomenon" placeholder="请输入故障现象" />
          </el-form-item>
          <el-form-item label="故障发生地点" prop="locationFault" label-width="110px">
            <el-input v-model="form.locationFault" placeholder="请输入故障发生地点" />
          </el-form-item>
          <el-form-item label="发现时机" prop="discoveryTime">
            <el-input v-model="form.discoveryTime" placeholder="请输入发现时机" />
          </el-form-item>
          <el-form-item label="故障件名称" prop="itemName" label-width="90px">
            <el-input v-model="form.itemName" placeholder="请输入故障件名称" />
          </el-form-item>
          <el-form-item label="故障件型别" prop="itemType" label-width="90px">
            <el-input v-model="form.itemType" placeholder="请输入故障件型别" />
          </el-form-item>
          <el-form-item label="故换件号码" prop="partNumber" label-width="90px">
            <el-input v-model="form.partNumber" placeholder="请输入故换件号码" />
          </el-form-item>
          <el-form-item label="故换件型别" prop="partType" label-width="90px">
            <el-input v-model="form.partType" placeholder="请输入故换件型别" />
          </el-form-item>
          <el-form-item label="故障失常码" prop="faultCode" label-width="90px">
            <el-input v-model="form.faultCode" placeholder="请输入故障失常码" />
          </el-form-item>
          <el-form-item label="故障件装机日期" prop="installationDate" label-width="120px">
            <el-date-picker v-model="form.installationDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择发生日期"> </el-date-picker>
          </el-form-item>
          <el-form-item label="故障原因" prop="causeFault">
            <el-input v-model="form.causeFault" placeholder="请输入故障原因" />
          </el-form-item>
          <el-form-item label="故障性质" prop="natureFault">
            <el-input v-model="form.natureFault" placeholder="请输入故障性质" />
          </el-form-item>
          <el-form-item label="故障责任" prop="liabilityFault">
            <el-input v-model="form.liabilityFault" placeholder="请输入故障责任" />
          </el-form-item>
          <el-form-item label="故障后果" prop="consequencesFault">
            <el-input v-model="form.consequencesFault" placeholder="请输入故障后果" />
          </el-form-item>
          <el-form-item label="发生日期" prop="occurDate">
            <el-date-picker v-model="form.occurDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择发生日期"> </el-date-picker>
          </el-form-item>
          <el-form-item label="判明方法" prop="methodDetermination">
            <el-input v-model="form.methodDetermination" placeholder="请输入判明方法" />
          </el-form-item>
          <el-form-item label="排除方法" prop="methodRectification">
            <el-input v-model="form.methodRectification" placeholder="请输入排除方法" />
          </el-form-item>
          <el-form-item label="发现人" prop="discoveredBy">
            <el-input v-model="form.discoveredBy" placeholder="请输入发现人" />
          </el-form-item>
          <el-form-item label="排故人" prop="rectificationBy">
            <el-input v-model="form.rectificationBy" placeholder="请输入排故人" />
          </el-form-item>
          <el-form-item label="审核人" prop="reviewerBy">
            <el-input v-model="form.reviewerBy" placeholder="请输入审核人" />
          </el-form-item>
          <el-form-item label="排故人数" prop="rectificationNumber">
            <el-input v-model="form.rectificationNumber" placeholder="请输入排故人数" />
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" :rows="2" 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>
  </div>
</template>

<script>
import { getMaintenanceRecord, addMaintenanceRecord, updateMaintenanceRecord, removeMaintenanceRecord } from '@/api/als/maintenanceRecord'
import { getAircaftCatalogTree, getAircaftTypeAndModelTree } from '@/api/als/sideTree'
import { getAircaftCatalogAll, getAircaftModelAll } from '@/api/als/aircraft'
import { deepClone, debounce } from '@/utils/index'
export default {
  name: 'MaintenanceRecord',
  components: {},
  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: 'id', label: '编号' },
        {
          prop: 'aircraftType',
          label: '机型',
          render: (h, params) => {
            const matchedItem = this.aircaftModelAll.find((item) => params.row.aircraftType.trim() === item.aircaftModelId.trim())
            console.log(params.row.aircraftType.trim())
            if (matchedItem) {
              return h('span', matchedItem.aircaftModelName)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          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: 'serialNumber',
          label: '出厂号码'
        },
        {
          prop: 'specialty',
          label: '专业'
        },
        {
          prop: 'systemName',
          label: '系统'
        },
        {
          prop: 'engineType',
          label: '发动机型别'
        },
        {
          prop: 'engineSerialNumber',
          label: '发动机号码'
        },
        {
          prop: 'unitName',
          label: '单位'
        },
        {
          prop: 'faultPhenomenon',
          label: '故障现象'
        },
        {
          prop: 'locationFault',
          label: '故障发生地点'
        },
        {
          prop: 'discoveryTime',
          label: '发现时机'
        },
        {
          prop: 'itemName',
          label: '故障件名称'
        },
        {
          prop: 'itemType',
          label: '故障件型别'
        },
        {
          prop: 'partNumber',
          label: '故换件号码'
        },
        {
          prop: 'partType',
          label: '故换件型别'
        },
        {
          prop: 'faultCode',
          label: '故障失常码'
        },
        {
          prop: 'installationDate',
          label: '故障件装机日期'
        },
        {
          prop: 'causeFault',
          label: '故障原因'
        },
        {
          prop: 'natureFault',
          label: '故障性质'
        },
        {
          prop: 'liabilityFault',
          label: '故障责任'
        },
        {
          prop: 'consequencesFault',
          label: '故障后果'
        },
        {
          prop: 'occurDate',
          label: '发生日期'
        },
        {
          prop: 'methodDetermination',
          label: '判明方法'
        },
        {
          prop: 'methodRectification',
          label: '排除方法'
        },
        {
          prop: 'discoveredBy',
          label: '发现人'
        },
        {
          prop: 'rectificationBy',
          label: '排故人'
        },
        {
          prop: 'reviewerBy',
          label: '审核人'
        },
        {
          prop: 'rectificationNumber',
          label: '排故人数'
        },
        {
          prop: 'remarks',
          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: 10,
        searchValue: ''
      },
      form: {
        id: '',
        aircraftType: '',
        aircraftId: '',
        serialNumber: '',
        specialty: '',
        systemName: '',
        engineType: '',
        engineSerialNumber: '',
        unitName: '',
        faultPhenomenon: '',
        locationFault: '',
        discoveryTime: '',
        itemName: '',
        itemType: '',
        partNumber: '',
        partType: '',
        faultCode: '',
        installationDate: '',
        causeFault: '',
        natureFault: '',
        liabilityFault: '',
        consequencesFault: '',
        occurDate: '',
        methodDetermination: '',
        methodRectification: '',
        discoveredBy: '',
        rectificationBy: '',
        reviewerBy: '',
        rectificationNumber: '',
        remarks: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftCatalogAll: [],
      aircaftModelAll: []
    }
  },
  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
      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.getMaintenanceRecordAPI({ aircraftId: this.aircaftModelIdList })
        // this.getMaintenanceRecordAPI()
      }
    },

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

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

    searchClick() {
      this.getMaintenanceRecordAPI({ aircraftId: this.aircaftModelIdList, itemName: this.keyWord })
    },

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

    async updateMaintenanceRecordAPI() {
      try {
        const { code } = await updateMaintenanceRecord({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getMaintenanceRecordAPI({ 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()
      this.getMaintenanceRecordAPI({ aircraftId: this.aircaftModelIdList })
    },

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

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        aircraftType: '',
        aircraftId: '',
        serialNumber: '',
        specialty: '',
        systemName: '',
        engineType: '',
        engineSerialNumber: '',
        unitName: '',
        faultPhenomenon: '',
        locationFault: '',
        discoveryTime: '',
        itemName: '',
        itemType: '',
        partNumber: '',
        partType: '',
        faultCode: '',
        installationDate: '',
        causeFault: '',
        natureFault: '',
        liabilityFault: '',
        consequencesFault: '',
        occurDate: '',
        methodDetermination: '',
        methodRectification: '',
        discoveredBy: '',
        rectificationBy: '',
        reviewerBy: '',
        rectificationNumber: '',
        remarks: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      }
    },

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

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

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

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

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