<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <el-input v-model="searchParam.nameLike" clearable size="small" placeholder="危险作业名称" style="width: 200px;" class="filter-item" />
        <!-- <el-select v-model="searchParam.auditState" clearable size="small" placeholder="审核状态" style="width: 200px;" class="filter-item">
          <el-option label="未审核" :value="1" />
          <el-option label="审核通过" :value="2" />
          <el-option label="审核不通过" :value="3" />
        </el-select> -->
        <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="searchSubmit">搜索</el-button>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="searchParamReset">重置</el-button>
      </div>
      <el-button class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="doAdd()">危险作业申报</el-button>
    </div>
    <!--弹出框1-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog1Show" :title="editState==1?'新增':editState==2?'危险作业备案变更':''" width="720px">
      <el-form ref="dialog1Form" :hide-required-asterisk="false" :model="dialog1Data" :rules="dialog1Rules" size="mini" label-width="180px" style="margin-right: 80px;">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="危险作业名称：" prop="name">
              <el-input v-model="dialog1Data.name" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="作业时间：" prop="workDate">
              <el-date-picker v-model="dialog1Data.workDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：" prop="note">
              <el-input v-model="dialog1Data.note" type="textarea" :rows="3" maxlength="500" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文件：" prop="filesPath">
              <el-upload
                class="upload-demo"
                action="/api/file/upload"
                multiple
                :headers="httpHeaders"
                :limit="9"
                :on-success="upFileSuccess"
                :on-remove="upFileRemove"
                :on-error="upFileError"
                :on-exceed="upFileExceed"
                :before-upload="upFileBefore"
                :on-preview="openFile"
                :file-list="dialog1Data._fileListShow"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">文件不要超过20M，最多9个文件</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialog1Show=false">取消</el-button>
        <el-button :loading="dialog1Saving" type="primary" @click="dialog1Submit">确认</el-button>
      </div>
    </el-dialog>
    <!--弹出框2-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog2Show" :title="'确认删除'" width="580px">
      <div>
        <span>确认要删除危险作业：</span><span style="font-weight: bold;">{{ dialog2Data.name }}</span><span>吗？</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialog2Show=false">取消</el-button>
        <el-button :loading="dialog2Saving" type="primary" @click="dialog2Submit">确认</el-button>
      </div>
    </el-dialog>
    <!--弹出框3-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog3Show" :title="'危险作业备案变更清单'" width="960px">
      <el-form label-width="140px">
        <el-form-item label="排序方式：">
          <el-radio-group v-model="dialog3Reverse" size="mini">
            <el-radio-button :label="true">最新优先</el-radio-button>
            <el-radio-button :label="false">时间顺序</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-timeline :reverse="dialog3Reverse">
        <el-timeline-item v-for="(dialog3DataItem,i) in dialog3Data" :key="dialog3DataItem.id" :color="dialog3Data.length==i+1?'#67C23A':null" :timestamp="(i==0?'初次提交：':dialog3Data.length==i+1?'最新变更：':'变更：')+dialog3DataItem.createDatetime" placement="top">
          <el-card>
            <el-form :model="dialog3DataItem" size="mini" label-width="120px" style="margin-right: 80px;">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="危险作业名称：" prop="name">
                    <span>{{ dialog3DataItem.name }}</span>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
                  <el-form-item label="审核状态：" prop="auditState">
                    <span v-if="dialog3DataItem.auditState==1">未审核</span>
                    <span v-if="dialog3DataItem.auditState==2">审核通过</span>
                    <span v-if="dialog3DataItem.auditState==3">审核不通过</span>
                  </el-form-item>
                </el-col> -->
                <el-col :span="12">
                  <el-form-item label="作业时间：" prop="workDate">
                    <span>{{ dialog3DataItem.workDate }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="状态：" prop="workState">
                    <span v-if="dialog3DataItem.workState==1">正常</span>
                    <span v-if="dialog3DataItem.workState==2">异常</span>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="备注：" prop="note">
                    <span>{{ dialog3DataItem.note }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="文件：" prop="filesPath">
                    <div v-for="file in dialog3DataItem._fileList" :key="file.url">
                      <el-link type="primary" @click="openFile(file)">{{ file.name }}</el-link>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="提交时间：" prop="createDatetime">
                    <span>{{ dialog3DataItem.createDatetime }}</span>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
                  <el-form-item label="审核时间：" prop="auditDatetime">
                    <span>{{ dialog3DataItem.auditDatetime }}</span>
                  </el-form-item>
                </el-col> -->
                <el-col v-if="dialog3DataItem.complaint" :span="24">
                  <el-form-item label="申诉说明：" prop="complaint">
                    <span>{{ dialog3DataItem.complaint }}</span>
                  </el-form-item>
                </el-col>
                <el-col v-if="dialog3DataItem.complaint" :span="24">
                  <el-form-item label="申诉文件：" prop="complaintFilesPath">
                    <div v-for="file in dialog3DataItem._complaintFileList" :key="file.url">
                      <el-link type="primary" @click="openFile(file)">{{ file.name }}</el-link>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col v-if="dialog3DataItem.complaint" :span="24">
                  <el-form-item label="申诉时间：" prop="complaintDatetime">
                    <span>{{ dialog3DataItem.complaintDatetime }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
    <!--弹出框4-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog4Show" :title="'异常申诉'" width="720px">
      <el-form ref="dialog4Form" :model="dialog4Data" :rules="dialog4Rules" size="mini" label-width="180px" style="margin-right: 80px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="危险作业名称：" prop="name">
              <span>{{ dialog4Data.name }}</span>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="审核状态：" prop="workDate">
              <span v-if="dialog4Data.auditState==1">未审核</span>
              <span v-if="dialog4Data.auditState==2">审核通过</span>
              <span v-if="dialog4Data.auditState==3">审核不通过</span>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="作业时间：" prop="workDate">
              <span>{{ dialog4Data.workDate }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态：" prop="workDate">
              <span v-if="dialog4Data.workState==1">正常</span>
              <span v-if="dialog4Data.workState==2">异常</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：" prop="note">
              <span>{{ dialog4Data.note }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文件：" prop="filesPath">
              <div v-for="file in dialog4Data._fileList" :key="file.url">
                <el-link type="primary" @click="openFile(file)">{{ file.name }}</el-link>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">申诉内容</el-divider>
        <el-row>
          <el-col :span="24">
            <el-form-item label="申诉说明：" prop="complaint">
              <el-input v-model="dialog4Data.complaint" type="textarea" :rows="3" maxlength="500" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="申诉文件：" prop="complaintFilesPath">
              <el-upload
                class="upload-demo"
                action="/api/file/upload"
                multiple
                :headers="httpHeaders"
                :limit="9"
                :on-success="upFile4Success"
                :on-remove="upFile4Remove"
                :on-error="upFileError"
                :on-exceed="upFileExceed"
                :before-upload="upFileBefore"
                :on-preview="openFile"
                :file-list="dialog4Data._complaintFileListShow"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">文件不要超过20M，最多9个文件</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialog4Show=false">取消</el-button>
        <el-button :loading="dialog4Saving" type="primary" @click="dialog4Submit">确认</el-button>
      </div>
    </el-dialog>
    <!--表格-->
    <el-table ref="table" v-loading="searching" :data="tableData" row-key="id">
      <el-table-column :show-overflow-tooltip="true" prop="id" label="编号" width="100px" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="name" label="危险作业名称" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="workDate" label="作业时间" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="workState" label="作业状态" align="center">
        <template slot-scope="scope">
          <span v-show="scope.row.workState==1">正常</span>
          <span v-show="scope.row.workState==2">异常</span>
          <el-button v-show="scope.row.workState==2" size="mini" round @click="doComplaint(scope.row.id)">
            {{ scope.row.complaint ? '修改' : '填写' }}申诉
          </el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column :show-overflow-tooltip="true" prop="auditState" label="审批状态" align="center">
        <template slot-scope="scope">
          <span v-show="scope.row.auditState==1">未审核</span>
          <span v-show="scope.row.auditState==2">审核通过</span>
          <span v-show="scope.row.auditState==3">审核不通过</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" width="300px" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" round @click="doLook(scope.row.workUuid)">查看</el-button>
          <el-button size="mini" round @click="doEdit(scope.row.id)">计划变更</el-button>
          <el-button size="mini" round @click="doDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-sizes="[10, 20, 50, 100]"
      :current-page.sync="searchParam.page"
      :page-size.sync="searchParam.count"
      :total="searchResult.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="searchSubmit"
      @current-change="searchSubmit"
    />
  </div>
</template>

<script>
import dangerousWorkApi from '@/api/kd/dangerousWork'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
const searchParam = {// 默认搜索条件
  page: 1,
  count: 10,
  searchCount: true
}
export default {
  name: 'EDangerousWork', // 本页面名
  components: {},
  data() {
    return {
      selectedMine: {},
      httpHeaders: {
        'Authorization': getToken()
      },
      searching: false,
      searchParam: {},
      searchResult: {
        total: 0,
        results: [] // 搜索结果
      },
      // =====新增、修改窗口数据=====
      dialog1Show: false,
      dialog1Saving: false,
      dialog1Data: {},
      dialog1Rules: {
        name: [
          { required: true, message: '请填写' }
        ]
      },
      editState: 0, // （刚打开窗口时）记录了上次窗口作用；（保存编辑时）记录了当前窗口作用； 0无 1新增 2变更
      addingData: {}, // 上次正在新增时的内容，下次打开dialog1窗口时记录下来
      // =====删除窗口数据=====
      dialog2Show: false,
      dialog2Saving: false,
      dialog2Data: {},
      // =====查看窗口数据=====
      dialog3Show: false,
      dialog3Data: {},
      dialog3Reverse: true,
      // =====申诉窗口数据=====
      dialog4Show: false,
      dialog4Saving: false,
      dialog4Data: {},
      dialog4Rules: {
        complaint: [
          { required: true, message: '请填写' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'baseApi'
    ]),
    tableData() {
      // 此处对返回值进行算法重组
      return this.searchResult.results
    }
  },
  mounted() {
    const selectedMineJson = window.localStorage.getItem('kd.selected.mine')
    let noMine = false
    if (!selectedMineJson) {
      noMine = true
    } else {
      const selectedMine = JSON.parse(selectedMineJson)
      if (!selectedMine || selectedMine.enterpriseId !== this.user.enterpriseId) {
        noMine = true
      } else {
        this.selectedMine = selectedMine
      }
    }
       // if (noMine) {
    //   this.$message.error('当前未选择矿山')
    //   this.$router.replace('/dashboard')
    // }
    this.searchParamReset()
    this.searchSubmit()
  },
  methods: {
    searchParamReset() {
      this.searchParam = JSON.parse(JSON.stringify(searchParam))
    },
    searchSubmit() {
      this.searching = true
      this.searchParam.mineType = this.selectedMine.mineType
      this.searchParam.mineId = this.selectedMine.id
      this.searchParam.hasEnable = true
      dangerousWorkApi.getPage(this.searchParam).then(response => {
        this.searching = false
        this.searchResult = response
      }).catch(() => {
        this.searching = false
      })
    },
    dialog1Submit() {
      this.$refs['dialog1Form'].validate(valid => {
        if (!valid) {
          return
        } else {
          this.dialog1Saving = true
          if (this.dialog1Data._fileList) {
            this.dialog1Data.filesPath = JSON.stringify(this.dialog1Data._fileList)
          }
          if (this.editState === 1) { // 新增
            this.dialog1Data.mineType = this.selectedMine.mineType
            this.dialog1Data.mineId = this.selectedMine.id
            dangerousWorkApi.add(this.dialog1Data).then(() => {
              this.dialog1Show = false
              this.$message.success('保存成功')
              setTimeout(() => { // 立即清除会导致输入框Validate一闪变红
                this.dialog1Data = {}
                this.dialog1Data._fileListShow = []
                this.dialog1Saving = false
              }, 500)
              this.searchSubmit()
            }).catch(() => {
              this.dialog1Saving = false
            })
          } else if (this.editState === 2) { // 变更
            dangerousWorkApi.update(this.dialog1Data).then(() => {
              this.dialog1Show = false
              this.$message.success('变更已提交')
              setTimeout(() => { // 立即清除会导致输入框Validate一闪变红
                this.dialog1Data = {}
                this.dialog1Data._fileListShow = []
                this.dialog1Saving = false
              }, 500)
              this.searchSubmit()
            }).catch(() => {
              this.dialog1Saving = false
            })
          } else {
            this.$message.error('出错啦，请重试')
            this.dialog1Saving = false
          }
        }
      })
    },
    beforeDialog1Open() { // 窗口打开前的统一操作
      if (this.editState === 1) {
        this.addingData = this.dialog1Data
      }
    },
    doAdd() {
      this.beforeDialog1Open()
      this.editState = 1
      this.dialog1Data = this.addingData // 初始值：上次编辑的内容
      this.dialog1Show = true
      this.$nextTick(() => {
        this.$refs['dialog1Form'].clearValidate()
      })
    },
    doLook(workUuid) {
      dangerousWorkApi.getByWorkUuid(workUuid).then(response => {
        this.dialog3Data = response.results
        this.dialog3Data.forEach(dw => {
          if (dw.filesPath) {
            dw._fileList = JSON.parse(dw.filesPath)
          }
          if (dw.complaintFilesPath) {
            dw._complaintFileList = JSON.parse(dw.complaintFilesPath)
          }
        })
        this.dialog3Show = true
      }).catch(() => {
        this.searchSubmit()
      })
    },
    doEdit(id) {
      this.beforeDialog1Open()
      this.editState = 2
      dangerousWorkApi.getById(id).then(response => {
        this.dialog1Data = response
        if (this.dialog1Data.filesPath) {
          this.dialog1Data._fileList = JSON.parse(this.dialog1Data.filesPath)
          this.dialog1Data._fileListShow = JSON.parse(this.dialog1Data.filesPath) // 数据存放与原始绑定分开，可以防止中途赋值产生的闪烁问题
        }
        if (this.dialog1Data.complaintFilesPath) {
          this.dialog1Data._complaintFileList = JSON.parse(this.dialog1Data.complaintFilesPath)
          this.dialog1Data._complaintFileListShow = JSON.parse(this.dialog1Data.complaintFilesPath) // 数据存放与原始绑定分开，可以防止中途赋值产生的闪烁问题
        }
        this.dialog1Show = true
        this.$nextTick(() => {
          this.$refs['dialog1Form'].clearValidate()
        })
      }).catch((e) => {
        this.searchSubmit()
      })
    },
    dialog2Submit() {
      this.dialog2Saving = true
      dangerousWorkApi.del(this.dialog2Data).then(() => {
        this.dialog2Show = false
        this.$message.success('删除成功')
        this.dialog2Data = {}
        this.dialog2Saving = false
        this.searchSubmit()
      }).catch(() => {
        this.dialog2Saving = false
      })
    },
    doDelete(id) {
      dangerousWorkApi.getById(id).then(response => {
        this.dialog2Data = response
        this.dialog2Show = true
      }).catch(() => {
        this.searchSubmit()
      })
    },
    doComplaint(id) {
      dangerousWorkApi.getById(id).then(response => {
        this.dialog4Data = response
        if (this.dialog4Data.filesPath) {
          this.dialog4Data._fileList = JSON.parse(this.dialog4Data.filesPath)
          this.dialog4Data._fileListShow = JSON.parse(this.dialog4Data.filesPath) // 数据存放与原始绑定分开，可以防止中途赋值产生的闪烁问题
        }
        if (this.dialog4Data.complaintFilesPath) {
          this.dialog4Data._complaintFileList = JSON.parse(this.dialog4Data.complaintFilesPath)
          this.dialog4Data._complaintFileListShow = JSON.parse(this.dialog4Data.complaintFilesPath) // 数据存放与原始绑定分开，可以防止中途赋值产生的闪烁问题
        }
        this.$nextTick(() => {
          this.$refs['dialog4Form'].clearValidate()
        })
        this.dialog4Show = true
      }).catch(() => {
        this.searchSubmit()
      })
    },
    dialog4Submit() {
      this.$refs['dialog4Form'].validate(valid => {
        if (!valid) {
          return
        } else {
          this.dialog4Saving = true
          if (this.dialog4Data._complaintFileList) {
            this.dialog4Data.complaintFilesPath = JSON.stringify(this.dialog4Data._complaintFileList)
          }
          this.dialog4Data.mineType = this.selectedMine.mineType
          this.dialog4Data.mineId = this.selectedMine.id
          dangerousWorkApi.complaint(this.dialog4Data).then(() => {
            this.dialog4Show = false
            this.$message.success('保存成功')
            setTimeout(() => { // 立即清除会导致输入框Validate一闪变红
              this.dialog4Data = {}
              this.dialog4Data._complaintFileListShow = []
              this.dialog4Saving = false
            }, 500)
            this.searchSubmit()
          }).catch(() => {
            this.dialog4Saving = false
          })
        }
      })
    },
    elementuiUpListFormat(fileList) {
      const filePathArray = []
      fileList.forEach(f => {
        if (f.response && f.response.result) {
          filePathArray.push({
            name: f.name,
            url: f.response.result
          })
        } else if (f.name && f.url) {
          filePathArray.push({
            name: f.name,
            url: f.url
          })
        }
      })
      return filePathArray
    },
    upFileSuccess(response, file, fileList) {
      if (!this.dialog1Data._fileList) {
        this.dialog1Data._fileList = []
      }
      this.dialog1Data._fileList.push({
        name: file.name,
        url: response.result
      })
    },
    upFile4Success(response, file, fileList) {
      if (!this.dialog4Data._complaintFileList) {
        this.dialog4Data._complaintFileList = []
      }
      this.dialog4Data._complaintFileList.push({
        name: file.name,
        url: response.result
      })
    },
    upFileRemove(file, fileList) {
      this.dialog1Data._fileList = this.elementuiUpListFormat(fileList)
    },
    upFile4Remove(file, fileList) {
      this.dialog4Data._complaintFileList = this.elementuiUpListFormat(fileList)
    },
    upFileError() {
      this.$message.error('上传失败，请稍后再试')
    },
    upFileExceed() {
      this.$message.error('文件数量已达上限')
    },
    upFileBefore(file) {
      const sizeCheck = file.size / 1024 / 1024 < 20
      if (!sizeCheck) {
        this.$message.error('上传文件大小不能超过 20MB')
        return false
      }
      return true
    },
    openFile(file) {
      if (file.url) {
        window.open(this.baseApi + '/file' + file.url)
      } else if (file.response && file.response.result) {
        window.open(this.baseApi + '/file' + file.response.result)
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  ::v-deep .el-input-number .el-input__inner {
    text-align: left;
  }
  ::v-deep .vue-treeselect__control,::v-deep .vue-treeselect__placeholder,::v-deep .vue-treeselect__single-value {
    height: 30px;
    line-height: 30px;
  }
</style>
