<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-input v-model="searchParam.enterpriseName" clearable size="small" placeholder="所属企业" style="width: 200px;" class="filter-item" />
        <el-input v-model="searchParam.mineName" clearable size="small" placeholder="所属矿山" style="width: 200px;" class="filter-item" />
        <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="searchSubmit">搜索2</el-button>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="searchParamReset">重置</el-button>
        <el-tooltip class="item" effect="dark" content="按当前查询条件导出" placement="top">
          <el-button :loading="exporting" class="filter-item" size="mini" type="info" plain icon="el-icon-download" @click="exportSubmit">导出</el-button>
        </el-tooltip>
      </div>
      <el-button class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="doAdd()">新增</el-button>
      <el-upload
        class="filter-item"
        action="/api/iot-normal-machine/ground-pressure/import"
        multiple
        :data="{mineType:selectedMine.mineType,mineId:selectedMine.id}"
        :headers="httpHeaders"
        :before-upload="beforeImport"
        :on-success="importSuccess"
        :on-error="importError"
        :show-file-list="false"
      >
        <el-button :loading="dialog3Saving" size="mini" type="success" icon="el-icon-upload2">导入</el-button>
      </el-upload>
    </div>
    <!--弹出框1-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog1Show" :title="editState==1?'新增':editState==2?'修改':'查看'" width="960px">
      <el-form ref="dialog1Form" :hide-required-asterisk="!dialog1Editing" :model="dialog1Data" :rules="dialog1Rules" size="mini" label-width="180px" style="margin-right: 80px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属企业：" prop="enterpriseId">
              <span v-show="!dialog1Editing">{{ dialog1Data.enterpriseName }}</span>
              <el-select
                v-model="dialog1Data.enterpriseId"
                placeholder="请选择"
                @change="enterpriseChange"
              >
                <el-option
                  v-for="item in options4enterpriseIdList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属矿山" prop="mineId">
              <span v-show="!dialog1Editing">{{ dialog1Data.mineName }}</span>
              <el-select v-model="dialog1Data.mineId" placeholder="请选择" clearable size="small" class="filter-item" style="width: 200px;">
                <el-option v-for="mine in mineList" :key="mine.index" :label="mine.name" :value="mine.index" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备编号：" prop="code">
              <span v-show="!dialog1Editing">{{ dialog1Data.code }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.code" :disabled="editState==2" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称：" prop="name">
              <span v-show="!dialog1Editing">{{ dialog1Data.name }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.name" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位：" prop="unit">
              <span v-show="!dialog1Editing">{{ dialog1Data.unit }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.unit" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="监测类型：" prop="monitoringType">
              <span v-show="!dialog1Editing">{{ (getMonitoringTypeByCode(dialog1Data.code)||{}).name }}</span>
              <el-input v-show="dialog1Editing" :disabled="true" :value="(getMonitoringTypeByCode(dialog1Data.code)||{}).name" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="一级预警阈值：" prop="thresholdLevel1">
              <span v-show="!dialog1Editing">{{ dialog1Data.thresholdLevel1 }}</span>
              <el-input-number v-show="dialog1Editing" v-model="dialog1Data.thresholdLevel1" :precision="4" :controls="false" style="width: 100%;" :min="0" :max="999999" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级预警阈值：" prop="thresholdLevel2">
              <span v-show="!dialog1Editing">{{ dialog1Data.thresholdLevel2 }}</span>
              <el-input-number v-show="dialog1Editing" v-model="dialog1Data.thresholdLevel2" :precision="4" :controls="false" style="width: 100%;" :min="0" :max="999999" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="三级预警阈值：" prop="thresholdLevel3">
              <span v-show="!dialog1Editing">{{ dialog1Data.thresholdLevel3 }}</span>
              <el-input-number v-show="dialog1Editing" v-model="dialog1Data.thresholdLevel3" :precision="4" :controls="false" style="width: 100%;" :min="0" :max="999999" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="四级预警阈值：" prop="thresholdLevel4">
              <span v-show="!dialog1Editing">{{ dialog1Data.thresholdLevel4 }}</span>
              <el-input-number v-show="dialog1Editing" v-model="dialog1Data.thresholdLevel4" :precision="4" :controls="false" style="width: 100%;" :min="0" :max="999999" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="安装位置：" prop="place">
              <span v-show="!dialog1Editing">{{ dialog1Data.place }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.place" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家：" prop="manufacturer">
              <span v-show="!dialog1Editing">{{ dialog1Data.manufacturer }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.manufacturer" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="X：" prop="x">
              <span v-show="!dialog1Editing">{{ dialog1Data.x }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.x" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Y：" prop="y">
              <span v-show="!dialog1Editing">{{ dialog1Data.y }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.y" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <span style="color: red; font-size: 11px;">* 图纸点选X Y？等确认如何操作时再做。XY现在是String。</span> -->
      </el-form>
      <div v-show="dialog1Editing" 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>
      </div>
      <div>
        <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="580px">
      <div>
        <span>共计成功导入：</span>
        <span style="font-weight: bold;">{{ dialog3Data.successCount + dialog3Data.failCount }}</span>
        <span>条，请核对总数。</span>
      </div>
      <div>
        <span>其中，成功：</span>
        <span style="color: #67C23A;">{{ dialog3Data.successCount }}</span>
        <span>条；失败：</span>
        <span style="color: #F56C6C;">{{ dialog3Data.failCount }}</span>
        <span>条。</span>
      </div>
      <br>
      <div v-if="dialog3Data.failCount">
        <div><span>失败信息：</span></div>
        <br>
        <div v-for="failReason in dialog3Data.failReasonList" :key="failReason.index">
          <span>第{{ failReason.index }}条数据</span>
          <span v-if="failReason.row" style="font-size: 10px;color: #909399;">第{{ failReason.row }}行</span>
          <span v-if="failReason.col" style="font-size: 10px;color: #909399;">第{{ failReason.col }}列</span>
          <span v-if="failReason.data" style="margin-left: 10px; color: #F56C6C;">{{ failReason.data }}</span>
          <span style="margin-left: 10px;">{{ failReason.reason }}</span>
        </div>
      </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="code" label="设备编码" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="enterpriseName" label="所属企业" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="mineName" label="所属矿山" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="unit" label="单位" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="manufacturer" label="生产厂家" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="place" label="安装位置" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="XXX" label="在线状态" align="center" /><!-- TODO -->
      <el-table-column label="操作" width="300px" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" round @click="doEdit(scope.row.id,false)">查看</el-button>
          <el-button size="mini" round @click="doEdit(scope.row.id,true)">修改</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 iotGroundPressureMachineApi from '@/api/kd/iotGroundPressureMachine'
import mineApi from '@/api/kd/mine'
import {getCompanyList} from '@/api/system/user'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import { downloadFile } from '@/utils'

const searchParam = {// 默认搜索条件
  page: 1,
  count: 10,
  searchCount: true,
  mineName: '',
  enterpriseName: ''

}
export default {
  name: 'EIotGroundPressureMachine', // 本页面名
  components: {},
  data() {
    return {
      options4enterpriseIdList: [],
      mineList: [],
      selectedMine: {},
      httpHeaders: {
        'Authorization': getToken()
      },
      searching: false,
      exporting: false,
      searchParam: {},
      searchResult: {
        total: 0,
        results: [] // 搜索结果
      },
      dialog1Show: false,
      dialog1Editing: false,
      dialog1Saving: false,
      dialog1Data: {},
      dialog1Rules: {
        enterpriseId: [{ required: true, message: '请选择' }],
        mineId: [{ required: true, message: '请选择' }],
        code: [{ required: true, message: '请填写' }],
        name: [{ required: true, message: '请填写' }],
        unit: [{ required: true, message: '请填写' }],
        thresholdLevel1: [{ required: true, message: '请填写' }],
        thresholdLevel2: [{ required: true, message: '请填写' }],
        thresholdLevel3: [{ required: true, message: '请填写' }],
        thresholdLevel4: [{ required: true, message: '请填写' }],
        place: [{ required: true, message: '请填写' }],
        manufacturer: [{ required: true, message: '请填写' }],
        x: [{ required: true, message: '请填写' }],
        y: [{ required: true, message: '请填写' }]
      },
      editState: 0, // （刚打开窗口时）记录了上次窗口作用；（保存编辑时）记录了当前窗口作用； 0无 1新增 2修改 3查看
      addingData: {}, // 上次正在新增时的内容，下次打开dialog1窗口时记录下来
      dialog2Show: false,
      dialog2Saving: false,
      dialog2Data: {},
      dialog3Show: false,
      dialog3Data: {},
      dialog3Saving: false
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ]),
    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()
      // 获取企业公司
      getCompanyList({})
      .then((res) => {
        this.options4enterpriseIdList = res.body;
      });
  },
  methods: {
    enterpriseChange(value){
      // 矿山选项卡
      this.getAllMineByEnterpriseId(value)
    },
    getAllMineByEnterpriseId(enterpriseId){
      mineApi.getAllMineByEnterpriseId({
        enterpriseId
      }).then(response => {
        let i = 1
        response.body.forEach(x => { x.index = i++ })
        this.mineList = response.body
      })
    },
    searchParamReset() {
      this.searchParam = JSON.parse(JSON.stringify(searchParam))
    },
    searchSubmit() {
      this.searching = true
      this.searchParam.mineType = this.selectedMine.mineType
      this.searchParam.mineId = this.selectedMine.id
      iotGroundPressureMachineApi.getPage(this.searchParam).then(response => {
        this.searching = false
        this.searchResult = response
      }).catch(() => {
        this.searching = false
      })
    },
    exportSubmit() {
      this.exporting = true
      this.searchParam.mineType = this.selectedMine.mineType
      this.searchParam.mineId = this.selectedMine.id
      iotGroundPressureMachineApi.export(this.searchParam).then(response => {
        downloadFile(response, '冲击地压监测设备', 'xlsx')
        this.exporting = false
      }).catch(() => {
        this.exporting = false
      })
    },
    getMonitoringTypeByCode(code) {
      return iotGroundPressureMachineApi.getMonitoringTypeByCode(code)
    },
    dialog1Submit() {
      this.$refs['dialog1Form'].validate(valid => {
        if (!valid) {
          return
        } else if (!this.getMonitoringTypeByCode(this.dialog1Data.code)) {
          this.$message.error('请正确填写编号，需解析出【监测类型】')
        } else {
          this.dialog1Saving = true
          if (this.editState === 1) { // 新增
            // this.dialog1Data.mineType = this.selectedMine.mineType
            // this.dialog1Data.mineId = this.selectedMine.id
            iotGroundPressureMachineApi.add(this.dialog1Data).then(() => {
              this.dialog1Show = false
              this.$message.success('保存成功')
              setTimeout(() => { // 立即清除会导致输入框Validate一闪变红
                this.dialog1Data = {}
                this.dialog1Saving = false
              }, 500)
              this.searchSubmit()
            }).catch(() => {
              this.dialog1Saving = false
            })
          } else if (this.editState === 2) { // 修改
            iotGroundPressureMachineApi.set(this.dialog1Data).then(() => {
              this.dialog1Show = false
              this.$message.success('修改成功')
              setTimeout(() => { // 立即清除会导致输入框Validate一闪变红
                this.dialog1Data = {}
                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.dialog1Editing = true
      this.dialog1Data = this.addingData // 初始值：上次编辑的内容
      this.dialog1Show = true
      this.$nextTick(() => {
        this.$refs['dialog1Form'].clearValidate()
      })
    },
    doEdit(id, isEdit) {
      this.beforeDialog1Open()
      this.editState = isEdit ? 2 : 3
      iotGroundPressureMachineApi.getById(id).then(response => {
        this.dialog1Data = response
        this.dialog1Editing = isEdit
        this.dialog1Show = true
        this.$nextTick(() => {
          this.$refs['dialog1Form'].clearValidate()
          this.getAllMineByEnterpriseId(this.dialog1Data.enterpriseId)
        })
      }).catch(() => {
        this.searchSubmit()
      })
    },
    dialog2Submit() {
      this.dialog2Saving = true
      iotGroundPressureMachineApi.del(this.dialog2Data).then(() => {
        this.dialog2Show = false
        this.$message.success('删除成功')
        this.dialog2Data = {}
        this.dialog2Saving = false
        this.searchSubmit()
      }).catch(() => {
        this.dialog2Saving = false
      })
    },
    doDelete(id) {
      iotGroundPressureMachineApi.getById(id).then(response => {
        this.dialog2Data = response
        this.dialog2Show = true
      }).catch(() => {
        this.searchSubmit()
      })
    },
    beforeImport() {
      this.dialog3Saving = true
    },
    importSuccess(response, file, fileList) {
      this.dialog3Data = response
      this.dialog3Show = true
      this.searchSubmit()
      this.dialog3Saving = false
    },
    importError(error) {
      this.$message.error('导入失败')
      console.error('导入失败', error)
      this.dialog3Saving = false
    }
  }
}
</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>
