<template>
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline>
      <el-form-item label="检查标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入检查标题"
          clearable v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检查记录编号" prop="recordCode">
        <el-input
          v-model="queryParams.recordCode"
          placeholder="请输入检查记录编号"
          clearable v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检查级别" prop="inspectLevel">
        <el-select v-model="queryParams.inspectLevel" placeholder="请选择检查级别" clearable>
          <el-option v-for="item in checkLevelOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="排查类型" prop="checkType">
        <el-select v-model="queryParams.checkType" placeholder="请选择排查类型" clearable>
          <el-option v-for="item in checkTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!-- 日期范围 -->
      <el-form-item label="检查时间范围" prop="checkTimeRange">
        <el-date-picker
          v-model="queryParams.checkTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="tableList" fit highlight-current-row style="width: 100%">
      <!-- 多选 -->
      <el-table-column type="selection" width="55" align="center" @selection-change="selectionChange" />
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column
        v-for="(column, index) in tableColumns"
        show-overflow-tooltip
        :key="column.prop"
        :label="column.label"
        :prop="column.prop"
        align="center"
      >
        <!-- 插槽 -->
        <template v-slot="scope" v-if="column.prop == 'photoList'">
          <span v-if="scope.row.photoList.length == 1" class="see" @click="handleSeeFill(scope.row, 1)">查看</span>
          <span v-else-if="scope.row.photoList.length > 1" class="see" @click="handleSeeFills(scope.row, 1)">查看</span>
          <span v-else>-</span>
        </template>
        <template v-slot="scope" v-else-if="column.prop == 'attachmentList'">
          <span v-if="scope.row.attachmentList.length == 1" class="see" @click="handleSeeFill(scope.row, 2)">查看</span>
          <span v-else-if="scope.row.attachmentList.length > 1" class="see" @click="handleSeeFills(scope.row, 2)">
            查看
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" align="center" width="190">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            type="text"
            size="mini"
            icon="el-icon-plus"
            style="color: #e6a23c"
            @click="handleAddHazard(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="文件查看" :visible.sync="previewOpen" width="90%" append-to-body>
      <div style="width: 100%; height: 720px">
        <bns-kkFile-preview :items="filePreview"></bns-kkFile-preview>
      </div>
    </el-dialog>

    <el-dialog title="文件查看" :visible.sync="document" width="80%" top="5vh" append-to-body>
      <div style="width: 100%; height: 720px">
        <bns-file-list-tabs :items="fileList" />
      </div>
    </el-dialog>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="80%">
      <el-form ref="dialogForm" :model="dialogForm" label-width="120px" :rules="dialogRules" :disabled="isDlgDisabled">
        <el-form-item label="检查标题" prop="title">
          <el-input v-model="dialogForm.title" placeholder="请输入检查标题" clearable maxlength="200" show-word-limit v-no-whitespace/>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="6" :offset="0" v-if="!isAdd && dialogForm.recordCode">
            <el-form-item label="检查记录编号" prop="recordCode">
              <el-input v-model="dialogForm.recordCode" placeholder="请输入检查记录编号" clearable disabled  v-no-whitespace/>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="检查级别" prop="inspectLevel">
              <el-select v-model="dialogForm.inspectLevel" placeholder="请选择检查级别" clearable>
                <el-option
                  v-for="item in checkLevelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="排查类型" prop="checkType">
              <el-select v-model="dialogForm.checkType" placeholder="请选择排查类型" clearable>
                <el-option v-for="item in checkTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="检查时间" prop="checkTime">
          <el-date-picker
            v-model="dialogForm.checkTime"
            type="datetime"
            placeholder="请选择检查时间"
            clearable
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            :picker-options="{
              disabledDate(time) {
                return time.getTime() > Date.now()
              },
            }"
          />
        </el-form-item>
        <el-form-item label="照片" prop="photoList">
          <el-upload
            action="#"
            accept="image/*"
            :auto-upload="false"
            list-type="picture-card"
            :on-change="handleUpImg"
            :on-exceed="handleExceedImg"
            :on-remove="handleRemoveImg"
            :file-list="dialogForm.photoList"
            :limit="9"
            :multiple="true"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="附件" prop="attachmentList">
          <el-upload
            action="#"
            accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.DOC,.DOCX,.XLS,.XLSX,.PPT,.PPTX,.PDF"
            :auto-upload="false"
            list-type="text"
            :on-change="handleUpFile"
            :on-exceed="handleExceedFile"
            :on-remove="handleRemoveFile"
            :file-list="dialogForm.attachmentList"
            :limit="9"
            :multiple="true"
          >
            <el-button size="mini" type="primary" icon="el-icon-plus">选择上传文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!isDlgDisabled" type="primary" @click="dialogConfirm" v-preventReClick="5000">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import bnsFileListTabs from '@/components/pro-tabs/bns-file-list-tabs.vue'
import bnsKkFilePreview from '@/components/pro-tabs/bns-kkFile-preview.vue'
import { lookFaceFile } from '@/utils/bonus'
import { dictTableOption } from '@/api/tool/select'
import {
  getSecurityCheckRecordList,
  addSecurityCheckRecordForm,
  updateSecurityCheckRecordForm,
  exportSecurityCheckRecordList,
} from '@/api/hiddenDangerManagement'

export default {
  components: {
    bnsKkFilePreview,
    bnsFileListTabs,
  },
  data() {
    return {
      showSearch: true,
      previewOpen: false, // 文件预览弹框
      // 文件预览数据
      filePreview: {
        filePreviewUrl: '',
        fileName: '',
      },
      document: false, // 文件查看弹框
      fileList: [], // 文件查看数据
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: '', // 关键字
        recordCode: '', // 检查记录编号
        inspectLevel: '', // 检查级别
        checkType: '', // 排查类型
        checkTimeRange: [], // 检查时间范围
      },
      proTypeOptions: [], // 工程类型
      proStatusOptions: [], // 工程状态
      // 检查级别-下拉
      checkLevelOptions: [],
      // 检查类型-下拉
      checkTypeOptions: [],
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '检查标题', prop: 'title' },
        { label: '检查记录编号', prop: 'recordCode' },
        { label: '检查级别', prop: 'inspectLevelName' },
        { label: '排查类型', prop: 'checkTypeName' },
        { label: '检查时间', prop: 'checkTime' },
        { label: '照片', prop: 'photoList' },
        { label: '附件', prop: 'attachmentList' },
      ],
      // 表格数据
      tableList: [],
      isDlgDisabled: false,
      dialogTitle: '',
      dialogVisible: false,
      dialogForm: {
        title: '', // 检查标题
        recordCode: '', // 检查记录编号
        inspectLevel: '', // 检查级别
        checkType: '', // 排查类型
        checkTime: '', // 检查时间
        photoList: [], // 照片
        attachmentList: [], // 附件
        fileId: [], // 删除id
      },
      dialogRules: {
        title: [{ required: true, message: '请输入检查标题', trigger: 'blur' }],
        inspectLevel: [{ required: true, message: '请选择检查级别', trigger: 'change' }],
        checkType: [{ required: true, message: '请选择排查类型', trigger: 'change' }],
        checkTime: [{ required: true, message: '请选择检查时间', trigger: 'change' }],
      },
      isAdd: true,
    }
  },
  created() {
    this.getCheckLevel()
    this.getCheckType()
    this.getList()
  },
  methods: {
    // 获取检查级别-下拉
    async getCheckLevel() {
      try {
        const params = {
          dictType: 'yh_inspect_level',
          dictValue: '',
        }
        const res = await dictTableOption(params)
        console.log('🚀 ~ 检查级别 ~ res:', res)
        this.checkLevelOptions = res.data
      } catch (error) {
        console.log('获取检查级别-下拉失败', error)
      }
    },
    // 获取排查类型-下拉
    async getCheckType() {
      try {
        const params = {
          dictType: 'yh_check_type',
          dictValue: '',
        }
        const res = await dictTableOption(params)
        console.log('🚀 ~ 排查类型 ~ res:', res)
        this.checkTypeOptions = res.data
      } catch (error) {
        console.log('获取排查类型-下拉失败', error)
      }
    },
    // 查询
    handleQuery() {
      console.log('查询')
      this.getList()
    },
    // 重置
    handleReset() {
      console.log('重置', this.queryParams)
      this.$refs.queryForm.resetFields()
      this.getList()
    },
    // 获取列表
    async getList() {
      try {
        let startTime = ''
        let endTime = ''
        if (this.queryParams.checkTimeRange && this.queryParams.checkTimeRange.length > 0) {
          startTime = this.queryParams.checkTimeRange[0]
          endTime = this.queryParams.checkTimeRange[1]
        } else {
          startTime = ''
          endTime = ''
        }
        const params = { ...this.queryParams, startTime, endTime }
        delete params.checkTimeRange
        const res = await getSecurityCheckRecordList(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.rows
        this.total = res.total
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
      }
    },
    // 多选
    selectionChange(val) {
      console.log('selectionChange', val)
    },
    // 查看附件
    handleSeeFill(row, type) {
      console.log('查看附件', row)
      this.filePreview = {
        filePreviewUrl: type == 1 ? row.photoList[0].filePath : row.attachmentList[0].filePath,
        fileName: type == 1 ? row.photoList[0].fileName : row.attachmentList[0].fileName,
      }
      this.previewOpen = true
    },
    handleSeeFills(row, type) {
      console.log('查看附件s', row)
      this.fileList = type == 1 ? row.photoList : row.attachmentList
      console.log('🚀 ~ handleSeeFills ~ this.fileList :', this.fileList)
      this.document = true
    },
    handleAdd() {
      console.log('新增')
      this.dialogVisible = true
      this.isAdd = true
      this.dialogTitle = '新增安全检查记录'
      this.isDlgDisabled = false
      this.dialogForm = {
        title: '', // 检查标题
        recordCode: '', // 检查记录编号
        inspectLevel: '', // 检查级别
        checkType: '', // 排查类型
        checkTime: '', // 检查时间
        photoList: [], // 照片
        attachmentList: [], // 附件
        fileId: [], // 删除id
      }
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
        // this.$refs.dialogForm.resetFields()
      })
    },
    // 编辑
    handleEdit(row) {
      console.log('编辑', row)
      this.isAdd = false
      this.dialogForm = { ...row }
      this.dialogForm.fileId = []
      this.dialogForm.photoList.forEach(item => {
        item.url = lookFaceFile() + item.filePath
        item.name = item.fileName
      })
      this.dialogForm.attachmentList.forEach(item => {
        item.filePath = lookFaceFile() + item.filePath
        item.name = item.fileName
      })
      this.dialogTitle = '编辑安全检查记录'
      this.dialogVisible = true
      this.isDlgDisabled = false
      console.log('🚀 ~ 编辑 ~ this.dialogForm :', this.dialogForm)
    },
    // 查看
    handleView(row) {
      console.log('查看', row)
      this.dialogForm = { ...row }
      this.dialogForm.photoList.forEach(item => {
        item.url = lookFaceFile() + item.filePath
        item.name = item.fileName
      })
      this.dialogForm.attachmentList.forEach(item => {
        item.url = lookFaceFile() + item.filePath
        item.name = item.fileName
      })
      this.dialogTitle = '查看安全检查记录'
      this.dialogVisible = true
      this.isDlgDisabled = true
    },
    // 新增隐患
    handleAddHazard(row) {
      console.log('新增隐患', row)
      this.$router.push({
        path: '/hiddenDangerManagement/hazardRectificationManagement/addHazard/index',
        query: {
          ...row,
        },
      })
    },
    // 导出数据
    handleExport() {
      try {
        let fileName = `安全检查记录_${new Date().getTime()}.xLsx`
        let url = exportSecurityCheckRecordList()
        let startTime = ''
        let endTime = ''
        if (this.queryParams.checkTimeRange && this.queryParams.checkTimeRange.length > 0) {
          startTime = this.queryParams.checkTimeRange[0]
          endTime = this.queryParams.checkTimeRange[1]
        } else {
          startTime = ''
          endTime = ''
        }
        const params = { ...this.queryParams, startTime, endTime }
        delete params.checkTimeRange
        console.log('🚀 ~ 导出 ~ params:', params)
        this.derive(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
    // 弹框确认
    dialogConfirm() {
      this.$refs.dialogForm.validate(async valid => {
        if (valid) {
          console.log('表单验证通过')
          try {
            let allRequestParams = { ...this.dialogForm }
            delete allRequestParams.photoList
            delete allRequestParams.attachmentList
            const photoList = this.dialogForm.photoList
            const attachmentList = this.dialogForm.attachmentList
            console.log('🚀 ~ dialogConfirm ~ params:', allRequestParams)
            console.log('🚀 ~ dialogConfirm ~ photoList:', photoList)
            console.log('🚀 ~ dialogConfirm ~ attachmentList:', attachmentList)
            let formData = new FormData()
            formData.append('params', JSON.stringify(allRequestParams))
            if (photoList.length > 0) {
              photoList.forEach(item => {
                if (item.raw) {
                  formData.append('photoList', item.raw)
                } else {
                  formData.append('photoList', new Blob())
                }
              })
            } else {
              formData.append('photoList', new Blob())
            }
            if (attachmentList.length > 0) {
              attachmentList.forEach(item => {
                if (item.raw) {
                  formData.append('attachmentList', item.raw)
                } else {
                  formData.append('attachmentList', new Blob())
                }
              })
            } else {
              formData.append('attachmentList', new Blob())
            }
            // 打印formData
            // for (let key of formData.keys()) {
            //   console.log('🚀 ~ --++ ~ formData:', key, formData.get(key))
            // }
            let res = ''
            if (this.isAdd) {
              // 新增
              res = await addSecurityCheckRecordForm(formData)
              this.$message.success('新增成功')
              this.dialogVisible = false
            } else {
              // 编辑
              res = await updateSecurityCheckRecordForm(formData)
              this.$message.success('编辑成功')
              this.dialogVisible = false
            }
            console.log('🚀 ~ dialogConfirm ~ res:', res)
            this.getList()
          } catch (error) {
            console.log('表单提交失败', error)
          }
        } else {
          console.log('表单验证失败')
          return false
        }
      })
    },
    // 上传图片
    handleUpImg(file, fileList) {
      console.log('上传图片', file, fileList)
      // 限制上传图片的大小-10M, 超过10M 剔除
      if (file.size > 10 * 1024 * 1024) {
        setTimeout(() => {
          this.$message.error('上传图片大小不能超过10M')
        }, fileList.length + 100)
        // 删除超过10M的图片
        fileList.pop()
        return
      }
      // 超过9张图片 提示
      if (fileList.length > 9) {
        return
      }
      this.dialogForm.photoList = fileList
    },
    // 超过9张图片 提示
    handleExceedImg() {
      this.$message.error('最多上传9张图片')
    },
    handleRemoveImg(file, fileList) {
      console.log('删除图片', file, fileList)
      this.dialogForm.photoList = fileList

      if (file.fileId) {
        this.dialogForm.fileId.push(file.fileId)
      }
      console.log('🚀 ~ 删除 ~ this.dialogForm.fileId :', this.dialogForm.fileId)
    },
    // 上传文件
    handleUpFile(file, fileList) {
      console.log('上传文件', file, fileList)
      if (file.size > 10 * 1024 * 1024) {
        setTimeout(() => {
          this.$message.error('上传文件大小不能超过10M')
        }, fileList.length + 100)
        // 删除超过10M的图片
        fileList.pop()
        return
      }
      // 超过9个文件 提示
      if (fileList.length > 9) {
        return
      }
      this.dialogForm.attachmentList = fileList
    },
    // 删除文件
    handleRemoveFile(file, fileList) {
      console.log('删除文件', fileList)
      this.dialogForm.attachmentList = fileList

      if (file.fileId) {
        this.dialogForm.fileId.push(file.fileId)
      }
      console.log('🚀 ~ 删除 ~ this.dialogForm.fileId :', this.dialogForm.fileId)
    },
    handleExceedFile() {
      this.$message.error('最多上传9个文件')
    },
  },
}
</script>

<style lang="scss" scoped>
.see {
  color: #409eff;
  cursor: pointer;
}
</style>
