<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="机型" prop="aircraftTypeId">
        <el-select v-model="queryParams.aircraftTypeId" placeholder="请选择" @change="handleaircraftChange">
          <el-option
            v-for="item in typeOption"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="系统" prop="aircraftSystemId">
        <!-- <el-input
          v-model="queryParams.aircraftSystemId"
          placeholder="请输入系统"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-select v-model="queryParams.aircraftSystemId" placeholder="请选择" @change="handlesystemChange">
          <el-option
            v-for="item in systemOption"
            :key="item.id"
            :label="item.aircraftTypeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="分系统" prop="aircraftSubsystemId">
        <!-- <el-input
          v-model="queryParams.aircraftSubsystemId"
          placeholder="请输入分系统"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-select v-model="queryParams.aircraftSubsystemId" placeholder="请选择">
          <el-option
            v-for="item in subSystemOption"
            :key="item.id"
            :label="item.aircraftTypeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="故障现象" prop="faultPhenomenon">
        <el-input
          v-model="queryParams.faultPhenomenon"
          placeholder="请输入故障现象"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="故障原因" prop="faultCause">
        <el-input
          v-model="queryParams.faultCause"
          placeholder="请输入故障原因"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- <el-form-item label="故障树" prop="faultTreePath">
        <el-input
          v-model="queryParams.faultTreePath"
          placeholder="请输入故障树"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="故障图" prop="faultPicturePath">
        <el-input
          v-model="queryParams.faultPicturePath"
          placeholder="请输入故障图"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排故方法" prop="troubleshootingMethodPath">
        <el-input
          v-model="queryParams.troubleshootingMethodPath"
          placeholder="请输入排故方法"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="浏览次数" prop="viewCount">
        <el-input
          v-model="queryParams.viewCount"
          placeholder="请输入浏览次数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:case:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:case:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:case:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:case:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="caseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="机型" align="center" prop="aircraftTypeName" />
      <el-table-column label="系统" align="center" prop="aircraftSystemName" />
      <el-table-column label="分系统" align="center" prop="aircraftSubsystemName" />
      <el-table-column label="故障现象" align="center" prop="faultPhenomenon" />
      <el-table-column label="故障原因" align="center" prop="faultCause" />
      <!-- <el-table-column label="故障树" align="center" prop="faultTreePath" />
      <el-table-column label="故障图" align="center" prop="faultPicturePath" />
      <el-table-column label="排故方法" align="center" prop="troubleshootingMethodPath" /> -->
      <el-table-column label="浏览次数" align="center" prop="viewCount" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后修改人" align="center" prop="updateBy" />
      <el-table-column label="最后修改时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:case:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['system:case:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改故障案例管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="6"><div class="grid-content bg-purple">
            <el-form-item label="机型" prop="faultPhenomenon">
              <el-select v-model="form.aircraftTypeId" placeholder="请选择" @change="handleaircraftChange1">
                <el-option
                  v-for="item in typeOption1"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div></el-col>
          <el-col :span="6"><div class="grid-content bg-purple">
            <el-form-item label="系统" prop="aircraftSystemId">
              <el-select v-model="form.aircraftSystemId" placeholder="请选择" @change="handlesystemChange1">
                <el-option
                  v-for="item in systemOption1"
                  :key="item.id"
                  :label="item.aircraftTypeName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div></el-col>
          <el-col :span="6"><div class="grid-content bg-purple">
            <el-form-item label="分系统" prop="aircraftSubsystemId">
              <el-select v-model="form.aircraftSubsystemId" placeholder="请选择">
                <el-option
                  v-for="item in subSystemOption1"
                  :key="item.id"
                  :label="item.aircraftTypeName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div>
          </el-col>
          <el-col :span="6"><div class="grid-content bg-purple" /></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-card class="box-card" style="margin:5px">
              <div slot="header" class="clearfix">
                <span>故障现象</span>
              </div>
              <div>
                <el-input v-model="form.faultPhenomenon" type="textarea" :rows="5" placeholder="请输入内容" />
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card" style="margin:5px">
              <div slot="header" class="clearfix">
                <span>故障原因</span>
              </div>
              <div>
                <el-input v-model="form.faultCause" type="textarea" :rows="5" placeholder="请输入内容" />
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-row>
          <el-card class="box-card" style="margin:5px">
            <div slot="header" class="clearfix">
              <span>故障树</span>
            </div>
            <div>
              <el-upload
                v-if="!form.faultTreePath"
                ref="loadtree"
                v-model="form.faultTreePath"
                class="avatar-uploader"
                :action="uploadFileUrl"
                :multiple="false"
                list-type="picture-card"
                :before-upload="beforeTreeUpload"
                :on-success="afterTreeUpload"
                :headers="headers"
              >
                <i class="el-icon-plus" />
              </el-upload>
              <div v-if="form.faultTreePath">
                <img :src="baseUrl+form.faultTreePath" style="max-width: 100%;" @load="showResetBtn = true;">
                <div style="flex: 1;" /> <!-- 占位符，用于将重置按钮推到最右侧 -->
                <el-button v-if="showResetBtn" type="danger" @click="reuploadTree">重置</el-button>
              </div>
            </div>
          </el-card>
        </el-row>
        <el-row>
          <el-card class="box-card" style="margin:5px">
            <div slot="header" class="clearfix">
              <span>排故方法</span>
            </div>
            <el-row>
              <el-col :span="4">
                <span>故障图</span>
                <div>
                  <el-upload
                    v-if="!form.faultPicturePath"
                    v-model="form.faultPicturePath"
                    class="avatar-uploader"
                    :action="uploadFileUrl"
                    :multiple="false"
                    list-type="picture-card"
                    :before-upload="beforePicUpload"
                    :on-success="afterPicUpload"
                    :headers="headers"
                  >
                    <i class="el-icon-plus" />
                  </el-upload>
                  <div v-if="form.faultPicturePath">
                    <img :src="baseUrl+form.faultPicturePath" style="max-width: 100px;" @load="showResetBtnpic = true" @click="showModal = true;imageSrc=form.faultPicturePath">
                    <div style="flex: 1;" /> <!-- 占位符，用于将重置按钮推到最右侧 -->
                    <el-button v-if="showResetBtnpic" type="danger" @click="reuploadPic">重置</el-button>
                  </div>
                </div>
              </el-col>
              <el-col :span="20">
                <span>文档</span>
                <div>
                  <el-upload
                    v-if="!form.troubleshootingMethodPath"
                    v-model="form.troubleshootingMethodPath"
                    class="avatar-uploader"
                    :action="uploadFileUrl"
                    :multiple="false"
                    list-type="picture-card"
                    :before-upload="beforeMethodUpload"
                    :on-success="afterMethodUpload"
                    :headers="headers"
                  >
                    <i class="el-icon-plus" />
                  </el-upload>
                  <div v-if="form.troubleshootingMethodPath">
                    <div ref="troubleshootingMethodFile" />
                    <div style="flex: 1;" /> <!-- 占位符，用于将重置按钮推到最右侧 -->
                    <el-button type="danger" @click="reuploadMethod">重置</el-button>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-row>
        <div v-if="showModal" class="modal" @click="showModal = false">
          <img :src="baseUrl+imageSrc" class="full-image">
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listCase, getCase, delCase, addCase, updateCase } from '@/api/system/case'
import { getTypeOption } from '@/api/system/type'
import { getSystemOption } from '@/api/system/system'
import { getSubSystemOption } from '@/api/system/subsystem'
import { renderAsync } from 'docx-preview'
import { getToken } from '@/utils/auth'
import axios from 'axios'

export default {
  name: 'Case',
  data() {
    return {
      wordText: '',
      wordURL: 'test.docx', // 文件地址，看你对应怎末获取、赋值
      showResetBtn: false,
      showResetBtnpic: false,
      name: '',
      fileList: [],
      hideUpload: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 故障案例管理表格数据
      caseList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      picUrl_tree: '',
      faultTreePath: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        aircraftTypeId: null,
        aircraftSystemId: null,
        aircraftSubsystemId: null,
        faultPhenomenon: null,
        faultCause: null,
        faultTreePath: null,
        faultPicturePath: null,
        troubleshootingMethodPath: null,
        viewCount: null
      },
      // 表单参数
      form: {
        aircraftTypeId: null,
        aircraftSystemId: null,
        aircraftSubsystemId: null,
        faultPhenomenon: null,
        faultCause: null,
        id: null,
        faultTreePath: null, // 存储上传成功后的文件路径
        faultPicturePath: null,
        troubleshootingMethodPath: null,
        viewCount: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      },
      // 表单校验
      rules: {
      },
      fileList: [], // 存储上传文件列表
      typeOption: [],
      typeOption1: [],
      systemOption: [],
      subSystemOption: [],
      systemOption1: [],
      subSystemOption1: [],
      showModal: false, // 控制模态框显示的变量
      imageSrc: '', // 图片路径
      showResetBtnMethod: false,
      // file upload
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传文件服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  created() {
    this.getList()
    this.getOption()
    this.getOption1()
  },
  methods: {
    getOption() {
      getTypeOption().then(resp => {
        this.typeOption = resp.data
      })
    },
    // 用于获取飞机机型(放到添加功能中)
    getOption1() {
      getTypeOption().then(resp => {
        this.typeOption1 = resp.data
      })
    },

    // 故障树
    beforeTreeUpload(file) {
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf('.'))
      const isOKType =
        fileType === '.jpg' ||
        fileType === '.png' ||
        fileType === '.jpeg' ||
        fileType === '.bmp' ||
        fileType === '.gif'
      if (!isOKType) {
        this.$message.error('图片格式只能为jpeg/png/jpg/bmp/gif')
      }

      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isLt2M && isOKType
    },
    afterTreeUpload(response, file) {
      // 上传完成后的处理逻辑
      console.log('上传完成', response, file)
      if (response.code === 200) {
        this.form.faultTreePath = response.fileName
      }
    },
    reuploadTree() {
      this.form.faultTreePath = ''
      this.showResetBtn = false
    },

    // 故障图
    beforePicUpload(file) {
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf('.'))
      const isOKType =
        fileType === '.jpg' ||
        fileType === '.png' ||
        fileType === '.jpeg' ||
        fileType === '.bmp' ||
        fileType === '.gif'
      if (!isOKType) {
        this.$message.error('图片格式只能为jpeg/png/jpg/bmp/gif')
      }

      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isLt2M && isOKType
    },

    afterPicUpload(response, file) {
      if (response.code === 200) {
        this.form.faultPicturePath = response.fileName
      }
      // 上传完成后的处理逻辑
      console.log('上传完成', response, file)
    },
    reuploadPic() {
      this.form.faultPicturePath = ''
      // this.$refs.loadtree.clearFiles();
      this.showResetBtnpic = false
    },

    // 排故流程word文档
    beforeMethodUpload(file) {
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf('.'))
      const isOKType =
        fileType === '.doc' ||
        fileType === '.docx'
      if (!isOKType) {
        this.$message.error('文件格式只能为doc/docx')
      }

      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 5MB!')
      }
      return isLt2M && isOKType
    },
    afterMethodUpload(response, file) {
      debugger
      if (response.code === 200) {
        this.form.troubleshootingMethodPath = response.fileName
        axios({
          method: 'get',
          responseType: 'blob',
          url: this.baseUrl + this.form.troubleshootingMethodPath
        }).then((response) => {
          debugger;
          renderAsync(response.data, this.$refs.troubleshootingMethodFile)
        })
      }
      // 上传完成后的处理逻辑
      console.log('上传完成', response, file)
    },
    reuploadMethod() {
      this.form.troubleshootingMethodPath = ''
      // this.$refs.loadtree.clearFiles();
      this.showResetBtnMethod = false
    },

    // 机型变化后更新系统下拉框
    handleaircraftChange() {
      this.queryParams.aircraftSystemId = ''
      this.queryParams.aircraftSubsystemId = ''
      // alert(this.queryParams.aircraftTypeId)
      getSystemOption(this.queryParams.aircraftTypeId).then(resp => {
        this.systemOption = resp.data
      })
    },

    // 系统变化后更新分系统
    handlesystemChange() {
      this.queryParams.aircraftSubsystemId = ''
      getSubSystemOption(this.queryParams.aircraftSystemId).then(resp => {
        this.subSystemOption = resp.data
      })
    },

    // 添加或修改对话框中机型变化后，修改系统
    handleaircraftChange1() {
      this.form.aircraftSystemId = ''
      this.form.aircraftSubsystemId = ''
      // alert(this.queryParams.aircraftTypeId)
      getSystemOption(this.form.aircraftTypeId).then(resp => {
        this.systemOption1 = resp.data
      })
    },

    // 添加或修改对话框中系统变化后，修改分系统
    handlesystemChange1() {
      this.form.aircraftSubsystemId = ''
      getSubSystemOption(this.form.aircraftSystemId).then(resp => {
        this.subSystemOption1 = resp.data
      })
    },

    /** 查询故障案例管理列表 */
    getList() {
      this.loading = true
      listCase(this.queryParams).then(response => {
        this.caseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        aircraftTypeId: null,
        aircraftSystemId: null,
        aircraftSubsystemId: null,
        faultPhenomenon: null,
        faultCause: null,
        faultTreePath: null,
        faultPicturePath: null,
        troubleshootingMethodPath: null,
        viewCount: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加故障案例管理'
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.resetForm('queryForm')
      const id = row.id || this.ids
      getCase(id).then(response => {
        debugger;
        this.form = response.data
        this.open = true
        this.title = '修改故障案例管理'
        if (this.form.troubleshootingMethodPath) {
          axios({
            method: 'get',
            responseType: 'blob',
            url: this.baseUrl + this.form.troubleshootingMethodPath
          }).then((response) => {
            debugger;
            renderAsync(response.data, this.$refs.troubleshootingMethodFile)
          })
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetForm('queryForm')
      const id = row.id || this.ids
      getCase(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改故障案例管理'
        if (this.form.troubleshootingMethodPath) {
          axios({
            method: 'get',
            responseType: 'blob',
            url: this.baseUrl + this.form.troubleshootingMethodPath
          }).then((response) => {
            debugger;
            renderAsync(response.data, this.$refs.troubleshootingMethodFile)
          })
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCase(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.queryParams.aircraftTypeId = null
              this.queryParams.aircraftSystemId = null
              this.queryParams.aircraftSubsystemId = null
              this.getList()
            })
          } else {
            addCase(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.queryParams.aircraftTypeId = null
              this.queryParams.aircraftSystemId = null
              this.queryParams.aircraftSubsystemId = null
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除故障案例管理编号为"' + ids + '"的数据项？').then(function() {
        return delCase(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/case/export', {
        ...this.queryParams
      }, `case_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style>
  .avatar-uploader {
    display: inline-block;
    text-align: center;
    position: relative;
    overflow: hidden;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    display: block;
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  .modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }

  .full-image {
    max-width: 80%;
    max-height: 80%;
  }

  /* .disabled .el-upload.el-upload--picture-card {
    display: none !important;
}

.disabled .el-button--success.is-plain {
    display: none !important;
} */

</style>
