<template>
  <div class="app-container">
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-form-item label="检查项名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入设备类型名称" clearable />
      </el-form-item>
      <el-form-item label="是否启用" prop="status">
        <el-select style="width: 200px" v-model="queryParams.status" placeholder="选择" clearable>
          <el-option v-for="status in statusList" :key="status.value" :label="status.label" :value="status.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="检查类型" prop="status">
        <el-select style="width: 200px" v-model="queryParams.type" placeholder="选择" clearable>
          <el-option v-for="status in checkType" :key="status.value" :label="status.label" :value="status.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button icon="el-icon-search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      :data="dataList"
      v-loading="loading"
      ref="table"
      border
      header-cell-class-name="el-table-header-cell"
      highlight-current-row
      @sort-change="sortChange">
      <el-table-column type="index" width="50" label="#" />
      <el-table-column prop="name" label="名称" width="480" v-if="columns_showColumn('id')" />
      <el-table-column prop="image" label="图片" align="center" v-if="columns_showColumn('image')">
        <template slot-scope="scope">
          <el-image style="width: 40px; height: 35px" :src="scope.row.image"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类别" align="center" :show-overflow-tooltip="true" v-if="columns_showColumn('type')">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.type == 1">检查</el-tag>
          <el-tag type="primary" v-else-if="scope.row.type == 2">保养</el-tag>
          <el-tag type="danger" v-else>异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" align="center" :show-overflow-tooltip="true" v-if="columns_showColumn('remark')" />
      <el-table-column prop="status" label="检查项状态" align="center" v-if="columns_showColumn('status')">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status == 1">启用</el-tag>
          <el-tag type="danger" v-if="scope.row.status == 0">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="descride" label="描述" align="center" :show-overflow-tooltip="true" v-if="columns_showColumn('descride')" />
      <el-table-column prop="name" label="检查项名称" align="center" :show-overflow-tooltip="true" v-if="columns_showColumn('name')" />

      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button
            type="success"
            size="small"
            icon="el-icon-edit"
            title="编辑"
            @click="handleUpdate(scope.row)"></el-button>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            title="删除"
            @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改设备检查项对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :lock-scroll="false" :visible.sync="open">
      <!-- 基本信息 -->
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :lg="12">
            <el-form-item label="检查项名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入检查项名称" />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="描述" prop="descride">
              <el-input v-model="form.descride" placeholder="请输入描述" />
            </el-form-item>
          </el-col>

          <el-col :lg="24">
            <el-form-item label="图片" prop="image">
              <el-upload
                list-type="picture-card"
                :action="uploadImgUrl"
                :on-success="handleUploadSuccess"
                :before-upload="handleBeforeUpload"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                :on-error="handleUploadError"
                name="file"
                :show-file-list="true"
                :data="{ uploadType: 1, filePath: 'device/inspect' }"
                :limit="1"
                :file-list="fileList"
                :on-preview="handlePictureCardPreview"
                :class="{hide: this.fileList.length >= 1}"
                :headers="headers">
                <i slot="default" class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
                <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
              </el-dialog>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="类型" prop="status">
              <el-select v-model="form.type" placeholder="选择" clearable>
                <el-option v-for="status in checkType" :key="status.value" :label="status.label" :value="status.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="检查项状态" prop="status">
              <el-select v-model="form.status" placeholder="选择" clearable>
                <el-option v-for="status in statusList" :key="status.value" :label="status.label" :value="status.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="检查表单" prop="type" v-show="opertype == 2">
              <el-button type="primary" @click="open_form_dialog">配置表单</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template slot="footer" v-if="opertype != 3">
        <el-button text @click="cancel">取消</el-button>
        <el-button type="success" @click="submitForm">完成</el-button>
      </template>
    </el-dialog>
    <el-dialog title="检查项表单配置" :lock-scroll="false" append-to-body :visible.sync="open_form">
      <formconfig v-bind:message="parentMessage"></formconfig>
      <template slot="footer">
        <el-button type="success" @click="open_form = false">完成</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listDeviceInspect, addDeviceInspect, delDeviceInspect, updateDeviceInspect, getDeviceInspect } from '@/api/deviceManagement/deviceinspect'
import formconfig from '@/views/deviceManagement/deviceformconfig/index'
import { getToken } from '@/utils/auth'

export default {
  name: 'deviceinspect',
  components: {
    formconfig
  },
  data() {
    return {
      ids: [],
      loading: false,
      showSearch: true,
      queryParams: {
        name: '',
        status: 1,
        type: 1,
        pageNum: 1,
        pageSize: 10,
        sort: '',
        sortType: 'asc'
      },
      columns: [
        { visible: true, prop: 'id', label: 'id' },
        { visible: true, prop: 'fkDeviceId', label: '设备id' },
        { visible: true, prop: 'image', label: '图片' },
        { visible: true, prop: 'sort', label: '检查顺序' },
        { visible: true, prop: 'type', label: '检查项类型（重点）' },
        { visible: true, prop: 'remark', label: '备注' },
        { visible: true, prop: 'status', label: '检查项状态' },
        { visible: true, prop: 'descride', label: '描述' },
        { visible: false, prop: 'name', label: '检查项名称' },
        { visible: false, prop: 'createdBy', label: '创建人' },
        { visible: false, prop: 'createdTime', label: '创建时间' },
        { visible: false, prop: 'updatedBy', label: '更新人' },
        { visible: false, prop: 'updatedTime', label: '更新时间' }
      ],
      total: 0,
      dataList: [],
      defaultTime: [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)],
      open_form: false,
      parentMessage: 0,
      statusList: [
        {
          label: '启用',
          value: 1
        },
        {
          label: '停用',
          value: 0
        },
        {
          label: ' ',
          value: -1
        }
      ],
      checkType: [
        {
          label: '检查',
          value: 1
        },
        {
          label: '保养',
          value: 2
        }
      ],
      title: '',
      opertype: 0,
      open: false,
      form: {
      
        fkDeviceId: null,
        image: null,
        sort: null,
        type: 1,
        remark: null,
        status: 1,
        descride: null,
        name: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null
      },
      rules: {},
      options: {
        typeOptions: [],
        statusOptions: []
      },
      // 图片上传相关
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      uploadImgUrl: process.env.VUE_APP_BASE_API + (process.env.VUE_APP_UPLOAD_URL || '/common/upload'),
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  mounted() {
    this.handleQuery()
    // 使用字典
    var dictParams = [{ dictType: 'mes_device_inspect_form_config', columnName: 'typeOptions' }]
    this.getDicts(dictParams).then((response) => {
      response.data.forEach((element) => {
        this.options[element.columnName] = element.list
      })
    })
  },
  methods: {
    columns_showColumn(prop) {
      return this.columns.some(column => column.prop === prop && column.visible)
    },
    getList() {
      this.loading = true
      listDeviceInspect(this.queryParams).then((res) => {
        const { code, data } = res
        if (code == 200) {
          this.dataList = data.result
          this.total = data.totalNum
          this.loading = false
        }
      })
    },
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置查询操作
    resetQuery() {
      this.resetForm('queryRef')
      this.handleQuery()
    },
    // 自定义排序
    sortChange(column) {
      var sort = undefined
      var sortType = undefined

      if (column.prop != null && column.order != null) {
        sort = column.prop
        sortType = column.order
      }
      this.queryParams.sort = sort
      this.queryParams.sortType = sortType
      this.handleQuery()
    },
    // 关闭dialog
    cancel() {
      this.open = false
      this.reset()
    },
    // 重置表单
    reset() {
      this.form = {

        fkDeviceId: null,
        image: null,
        sort: null,
        type: 1,
        remark: null,
        status: 1,
        descride: null,
        name: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null
      }
      this.fileList = []
      this.resetForm('formRef')
    },
    // 添加按钮操作
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加设备检查项'
      this.opertype = 1
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDeviceInspect(id).then((res) => {
        const { code, data } = res
        if (code == 200) {
          this.open = true
          this.title = '修改设备检查项'
          this.opertype = 2
          this.form = {
            ...data
          }
          // 初始化图片列表
          if (data.image) {
            this.fileList = [{ name: data.image, url: data.image }]
          }
        }
      })
    },
    // 添加&修改 表单提交
    submitForm() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined && this.opertype === 2) {
            updateDeviceInspect(this.form).then((res) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addDeviceInspect(this.form).then((res) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    // 删除按钮操作
    handleDelete(row) {
      const Ids = row.id || this.ids

      this
        .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？')
        .then(function () {
          return delDeviceInspect(Ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
    },
    // 打开表单
    open_form_dialog() {
      if (this.form.id != undefined && this.opertype === 2) {
        this.open_form = true
        // 父组件向子组件传值
        this.parentMessage = this.form.id
      }
    },
    // 图片上传相关方法
    handleUploadSuccess(res) {
      if (res.code != 200) {
        this.$message.error(`上传失败，原因:${res.msg}!`)
        return
      }
      this.fileList.push({ name: res.data.fileName, url: res.data.url })
      this.form.image = res.data.url
    },
    handleBeforeUpload(file) {
      const fileType = ['png', 'jpg', 'jpeg', 'webp']
      const isImg = fileType.some((type) => {
        return file.type.indexOf(type) > -1
      })
      
      if (!isImg) {
        this.$message.error(`文件格式不正确, 请上传${fileType.join('/')}图片格式文件!`)
        return false
      }
      
      const isLt = file.size / 1024 / 1024 < 5
      if (!isLt) {
        this.$message.error('上传头像图片大小不能超过 5 MB!')
        return false
      }
      return true
    },
    handleExceed() {
      this.$message.error('上传文件数量不能超过 1 个!')
    },
    handleRemove() {
      this.fileList = []
      this.form.image = ''
    },
    handleUploadError() {
      this.$message({
        type: 'error',
        message: '上传失败'
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>

<style scoped>
::v-deep.hide .el-upload--picture-card {
  display: none;
}
/* 去掉动画效果 */
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter,
.el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}
</style>