<template>
  <div class="view-table-content">
    <div style="width: 100%">
      <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="handleImport">导入</el-dropdown-item>
              <el-dropdown-item command="handleExport" :disabled="tableData.length == 0">导出</el-dropdown-item>
              <el-dropdown-item command="importTemplate">下载数据模板</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </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(keyWordData)"></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="aircraftTypeName">
            <treeselect :value="form.aircraftTypeName" :normalizer="aircraftTypeNormalizer" :options="aircraftTypeTreeData" :show-count="true" placeholder="请选择机型" @select="aircraftTypeChange" />
          </el-form-item>
          <el-form-item label="系统" prop="aircraftSystemName">
            <el-input v-model="form.aircraftSystemName" placeholder="请输入系统" />
          </el-form-item>
          <el-form-item label="分系统" prop="aircraftSubsystemName">
            <el-input v-model="form.aircraftSubsystemName" 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="faultCause">
            <el-input 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>

      <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="系统">{{ form.aircraftSystemName }}</el-descriptions-item>
          <el-descriptions-item label="分系统">{{ form.aircraftSubsystemName }}</el-descriptions-item>
          <el-descriptions-item label="故障现象">{{ form.faultPhenomenon }}</el-descriptions-item>
          <el-descriptions-item label="故障原因">{{ form.faultCause }}</el-descriptions-item>
          <!-- <el-descriptions-item :span="1" label="排故方法">{{ form.troubleshootingMethodPath }}</el-descriptions-item>
          <el-descriptions-item label="故障图"><img :src="faultPicturePathUrl" width="200px" /></el-descriptions-item>
          <el-descriptions-item label="故障树"><img :src="faultPicturePathUrl" width="200px" /></el-descriptions-item> -->
        </el-descriptions>
        <span slot="footer" class="dialog-footer">
          <el-button @click="detailSubmit">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip"><el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getFaultCase, addFaultCase, updateFaultCase, removeFaultCase } from '@/api/als/faultCase'
import { deepClone, debounce } from '@/utils/index'
import { getListByIdsApi } from '@/api/als/oss'
import { getItem } from '@/utils/index'
import { getAircaftTypeAndModelTree } from '@/api/als/sideTree'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { flattenTree, download } from '../utils/common'
// import FileUpload from '@/views/als/components/FileUpload'

export default {
  name: 'FaultCase',
  components: { Treeselect },
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      detailVisible: false,
      keyWordData: '',
      aircaftModelIdList: [],
      currentNodeKey: '',
      currentNode: {},
      menuTreeData: [],
      typeTree: {
        children: 'children',
        label: 'label'
      },
      searchValue: '',
      columns: [
        {
          prop: 'aircraftTypeName',
          label: '机型',
          render: (h, params) => {
            const matchedItem = this.aircraftTypeAll.find((item) => params.row.aircraftTypeName.trim() === item.id.trim())
            if (matchedItem) {
              return h('span', matchedItem.label)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          prop: 'aircraftSystemName',
          label: '系统'
        },
        {
          prop: 'aircraftSubsystemName',
          label: '分系统'
        },
        {
          prop: 'faultPhenomenon',
          label: '故障现象',
          render: (h, params) => {
            return h('span', {
              domProps: {
                innerHTML: params.row.faultPhenomenon ? params.row.faultPhenomenon : params.row.pcontent
              }
            })
          }
        },
        {
          prop: 'faultCause',
          label: '故障原因',
          render: (h, params) => {
            return h('span', {
              domProps: {
                innerHTML: params.row.faultCause ? params.row.faultCause : params.row.fcontent
              }
            })
          }
        },
        {
          prop: 'viewCount',
          label: '浏览次数'
        },
        // {
        //   prop: 'createBy',
        //   label: '创建人'
        // },
        // {
        //   prop: 'createTime',
        //   label: '创建时间'
        // },
        // {
        //   prop: 'updateBy',
        //   label: '最后修改人'
        // },
        // {
        //   prop: 'updateTime',
        //   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: false,
        index: true,
        loading: false,
        initTable: false,
        border: true,
        height: 'calc(100vh - 300px)'
      },
      tableCheckItems: [],
      tableData: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      form: {
        aircraftTypeName: null,
        aircraftSystemName: '',
        aircraftSubsystemName: '',
        faultPhenomenon: '',
        faultCause: '',
        faultTreePath: '',
        faultPicturePath: '',
        troubleshootingMethodPath: '',
        viewCount: 0,
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      debounceFn: debounce(this.fetch, 500),
      faultPicturePathUrl: '',
      faultTreePathUrl: '',
      upload: {
        open: false,
        title: '',
        isUploading: false,
        updateSupport: 0,
        headers: { Authorization: getItem('token') },
        // 上传的地址
        url: '/api/als/faultCase/importData'
      },
      aircraftTypeTreeData: [],
      aircraftTypeAll: [],
      detailAircraftType: ''
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getAirTypeData()
    this.getFaultCaseAPI()
  },
  methods: {
    async removeFaultCaseAPI(params) {
      try {
        const { code } = await removeFaultCase(params)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          await this.getFaultCaseAPI({ faultPhenomenon: keyWordData })
          this.handleClose()
        }
      } catch (error) {}
    },

    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
    },

    async getAirTypeData() {
      try {
        const { data } = await getAircaftTypeAndModelTree()
        this.aircraftTypeTreeData = data[0].children
        this.aircraftTypeAll = flattenTree(data[0].children)
      } catch (error) {}
    },

    async getFaultCaseByEsAPI(keyWordData) {
      console.log(keyWordData)
    },

    fetch() {
      this.getFaultCaseAPI({ faultPhenomenon: keyWordData })
    },

    async searchClick(keyWordData) {
      // this.getFaultCaseByEsAPI(keyWordData)
      this.getFaultCaseAPI({ faultPhenomenon: keyWordData })
    },

    async addFaultCaseAPI() {
      try {
        const { code } = await addFaultCase({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            duration: 3000,
            message: 'ES数据同步中，稍后查询!'
          })

          this.handleClose()
          this.getFaultCaseAPI({ faultPhenomenon: keyWordData })
        }
      } catch (error) {}
    },

    async updateFaultCaseAPI() {
      try {
        const { code } = await updateFaultCase({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose()
          this.getFaultCaseAPI({ faultPhenomenon: keyWordData })
        }
      } catch (error) {}
    },

    openDialog() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
    },

    aircraftTypeChange(node) {
      this.form.aircraftTypeName = node.id
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        aircraftTypeName: null,
        aircraftSystemName: '',
        aircraftSubsystemName: '',
        faultPhenomenon: '',
        faultCause: '',
        faultTreePath: '',
        faultPicturePath: '',
        troubleshootingMethodPath: '',
        viewCount: 0,
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      }
    },

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

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

    aircraftTypeNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },

    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 matchedItem = this.aircraftTypeAll.find((item) => row.aircraftTypeName.trim() === item.id.trim())
      this.detailAircraftType = matchedItem.label
      // if (row.faultPicturePath) {
      //   const res = await getListByIdsApi(row.faultPicturePath)
      //   this.faultPicturePathUrl = res.data[0].url
      //   const res2 = await getListByIdsApi(row.faultTreePath)
      //   this.faultTreePathUrl = res.data[0].url
      // } else {
      //   this.faultPicturePathUrl = row.faultPicturePath
      //   this.faultTreePathUrl = row.faultTreePathUrl
      // }
      this.form.faultPhenomenon = row.pcontent
      this.form.faultCause = row.fcontent
      this.detailVisible = true
      this.addViewCount(row)
      // this.form = deepClone(row)
    },

    async addViewCount(row) {
      try {
        await updateFaultCase({ id: row.id, viewCount: ++row.viewCount })
      } catch (error) {}
    },

    detailSubmit() {
      this.handleClose()
      this.detailVisible = false
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '警告列表导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      download('/faultCase/importTemplate', {}, `faultCase_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (this.uploadFlag) {
        this.upload.open = false
        this.upload.isUploading = false
        this.$refs.upload.clearFiles()
      }
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 导出
    handleExport() {
      download(
        '/faultCase/export',
        {
          ...this.form
        },
        `faultCase_${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>

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