<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 && !currentNode.type == 1">新增</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="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="faultCode">
            <el-input v-model="form.faultCode" placeholder="请输入故障代码" />
          </el-form-item>
          <el-form-item label="故障名称" prop="faultName">
            <el-input v-model="form.faultName" placeholder="请输入故障名称" />
          </el-form-item>

          <el-form-item label="故障日期" prop="faultDate">
            <el-date-picker v-model="form.faultDate" type="date" value-format="yyyy-MM-dd" placement="bottom-start" placeholder="请选择故障日期"> </el-date-picker>
          </el-form-item>
          <el-form-item label="所属系统" prop="systemItem">
            <el-select v-model="form.systemItem" placeholder="请选择所属系统">
              <el-option v-for="item in systemItemList" :key="item.id" :label="item.label" :value="item.label"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="专业" prop="specialty">
            <el-input v-model="form.specialty" 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="symptoms">
            <el-input type="textarea" :rows="2" v-model="form.symptoms" placeholder="请输入故障现象" />
          </el-form-item>
          <el-form-item label="排除方法" prop="methodRectification">
            <el-input v-model="form.methodRectification" placeholder="请输入排除方法" />
          </el-form-item>
          <el-form-item label="故障原因分类" label-width="100px" prop="faultCauseType">
            <el-select v-model="form.faultCauseType" placeholder="请输入故障原因分类">
              <el-option v-for="item in faultCauseTypeList" :key="item.id" :label="item.label" :value="item.label"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="故障原因" prop="faultCause">
            <el-input v-model="form.faultCause" placeholder="请输入故障原因" />
          </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-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>

      <el-dialog title="故障案例详情" :visible.sync="detailVisible" width="1000px" :show-close="false">
        <el-descriptions border>
          <el-descriptions-item label="飞机型号">{{ detailAircraftType }}</el-descriptions-item>
          <el-descriptions-item label="飞机编号">{{ detailAircraftCode }}</el-descriptions-item>
          <el-descriptions-item label="故障名称">{{ form.faultName }}</el-descriptions-item>
          <el-descriptions-item label="故障日期">{{ form.faultDate }}</el-descriptions-item>
          <el-descriptions-item label="故障现象">{{ form.symptoms }}</el-descriptions-item>
          <el-descriptions-item label="所属系统">{{ form.systemItem }}</el-descriptions-item>
          <el-descriptions-item label="专业">{{ form.specialty }}</el-descriptions-item>
          <el-descriptions-item label="故障位置">{{ form.location }}</el-descriptions-item>
          <el-descriptions-item label="排除方法">{{ form.methodRectification }}</el-descriptions-item>
          <el-descriptions-item :span="1" label="故障原因分类">{{ form.faultCauseType }}</el-descriptions-item>
          <el-descriptions-item :span="2" label="故障性质">{{ form.level }}</el-descriptions-item>
          <el-descriptions-item :span="3" label="故障原因">{{ form.faultCause }}</el-descriptions-item>
          <el-descriptions-item label="故障文件">{{ detailOssId }}</el-descriptions-item>
        </el-descriptions>
        <span slot="footer" class="dialog-footer">
          <el-button @click="detailVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getFaultCase, addFaultCase, updateFaultCase, removeFaultCase } from '@/api/als/faultCase'
import { getAircaftCatalogTree, getAircaftTypeAndModelTree } from '@/api/als/sideTree'
import { getAircaftModelAll, getAircaftCatalogAll } from '@/api/als/aircraft'
import { deepClone, debounce } from '@/utils/index'
import { getListByIdsApi } from '@/api/als/oss'
import FileUpload from '@/views/als/components/FileUpload'

export default {
  name: 'FaultCase',
  components: { FileUpload },
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      detailVisible: false,
      keyWordData: '',
      aircaftModelIdList: [],
      currentNodeKey: null,
      currentNode: null,
      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: 'faultName',
          label: '故障名称'
        },
        {
          prop: 'faultDate',
          label: '故障日期'
        },
        {
          prop: 'systemItem',
          label: '所属系统'
        },
        {
          prop: 'faultCauseType',
          label: '故障原因分类'
        },
        {
          prop: 'level',
          label: '故障性质'
        },
        {
          prop: 'ossId',
          label: '文件编号'
        },
        {
          button: true,
          label: '操作',
          width: '240px',
          group: [
            {
              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.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: '',
        aircraftCode: '',
        faultCode: '',
        faultName: '',
        ossId: '',
        faultDate: '',
        systemItem: '',
        specialty: '',
        faultCauseType: '',
        location: '',
        level: '',
        methodRectification: '',
        symptoms: '',
        faultCause: '',
        remarks: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftModelAll: [],
      aircaftCatalogAll: [],
      systemItemList: [{ id: 1, label: '特设' }],
      levelList: [
        { id: 1, label: '一般故障' },
        { id: 2, label: '较大故障' },
        { id: 3, label: '重大故障' }
      ],
      faultCauseTypeList: [
        { id: 1, label: '设计原因' },
        { id: 2, label: '制造原因' },
        { id: 3, label: '使用维护' },
        { id: 4, label: '成品维护' },
        { id: 5, label: '其他原因' }
      ],
      detailAircraftType: '',
      detailAircraftCode: '',
      detailOssId: ''
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getAircaftCatalogTreeAPI()
  },
  methods: {
    async getAircaftCatalogTreeAPI(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.getFaultCaseAPI({ aircraftId: this.aircaftModelIdList })
      }
    },

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

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

    async searchClick() {
      this.getFaultCaseAPI({ aircraftType: this.aircaftModelIdList, faultName: this.keyWordData })
    },

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

    async updateFaultCaseAPI() {
      try {
        const { code } = await updateFaultCase({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getFaultCaseAPI({ 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.getFaultCaseAPI({ aircraftType: this.currentNode.id })
      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
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        aircraftType: '',
        faultCode: '',
        faultName: '',
        location: '',
        level: '',
        symptoms: '',
        faultCause: '',
        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.updateFaultCaseAPI()
          this.handleClose()
          break
        case '新增':
          this.addFaultCaseAPI()
          this.handleClose()
          break
      }
    },

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

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

    async checkDetails(row) {
      this.form = deepClone(row)
      const aircraftTypeItem = this.aircaftModelAll.find((item) => row.aircraftType === item.aircaftModelId)
      const aircraftCodeItem = this.aircaftCatalogAll.find((item) => row.aircraftCode === item.aircaftCatalogId)
      if (row.ossId) {
        const res = await getListByIdsApi(row.ossId)
        this.detailOssId = res.data[0].originalName
      } else {
        this.detailOssId = row.ossId
      }
      this.detailAircraftType = aircraftTypeItem.aircaftModelName
      this.detailAircraftCode = aircraftCodeItem.aircaftCatalogCode
      this.detailVisible = true
    }
  }
}
</script>

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