<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.dict37" clearable size="small" placeholder="物资类型" style="width: 200px;" class="filter-item">
          <el-option v-for="item in dict37List" :key="item.id" :label="item.value" :value="item.id" />
        </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="960px">
      <el-form ref="dialog1Form" :model="dialog1Data" :hide-required-asterisk="!dialog1Editing" :rules="dialog1Rules" size="mini" label-width="180px" style="margin-right: 80px;">
        <el-row :gutter="20">
          <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-col :span="12">
            <el-form-item label="物资类型：" prop="dict37">
              <span v-show="!dialog1Editing">{{ dialog1Data.dict37Name }}</span>
              <el-select v-show="dialog1Editing" v-model="dialog1Data.dict37" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item in dict37List" :key="item.id" :label="item.value" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌：" prop="brand">
              <span v-show="!dialog1Editing">{{ dialog1Data.brand }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.brand" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号：" prop="model">
              <span v-show="!dialog1Editing">{{ dialog1Data.model }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.model" 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="productionDate">
              <span v-show="!dialog1Editing">{{ dialog1Data.productionDate }}</span>
              <el-date-picker v-show="dialog1Editing" v-model="dialog1Data.productionDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家：" prop="producer">
              <span v-show="!dialog1Editing">{{ dialog1Data.producer }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.producer" 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="number">
              <span v-show="!dialog1Editing">{{ dialog1Data.number }}</span>
              <el-input-number v-show="dialog1Editing" v-model="dialog1Data.number" :precision="4" :controls="false" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位：" prop="numberUnit">
              <span v-show="!dialog1Editing">{{ dialog1Data.numberUnit }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.numberUnit" 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="savePlace">
              <span v-show="!dialog1Editing">{{ dialog1Data.savePlace }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.savePlace" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前状态：" prop="dict38">
              <span v-show="!dialog1Editing">{{ dialog1Data.dict38Name }}</span>
              <el-select v-show="dialog1Editing" v-model="dialog1Data.dict38" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item in dict38List" :key="item.id" :label="item.value" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="质量状况：" prop="dict39">
              <span v-show="!dialog1Editing">{{ dialog1Data.dict39Name }}</span>
              <el-select v-show="dialog1Editing" v-model="dialog1Data.dict39" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item in dict39List" :key="item.id" :label="item.value" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性能参数：" prop="performance">
              <span v-show="!dialog1Editing">{{ dialog1Data.performance }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.performance" 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="liablePerson">
              <span v-show="!dialog1Editing">{{ dialog1Data.liablePerson }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.liablePerson" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话：" prop="liablePersonPhone">
              <span v-show="!dialog1Editing">{{ dialog1Data.liablePersonPhone }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.liablePersonPhone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注信息：" prop="note">
              <span v-show="!dialog1Editing">{{ dialog1Data.note }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.note" maxlength="1000" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="照片：" prop="photoPath">
              <div v-for="file in dialog1Data._fileList" v-show="!dialog1Editing" :key="file.url">
                <el-link type="primary" @click="openFile(file)">{{ file.name }}</el-link>
              </div>
              <el-upload
                v-show="dialog1Editing"
                class="upload-demo"
                action="/api/file/upload"
                multiple
                :headers="httpHeaders"
                :limit="1"
                :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">只能上传jpg/png文件，且不超过20M</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度：" prop="longitude">
              <span v-show="!dialog1Editing">{{ dialog1Data.longitude }}</span>
              <el-input-number v-show="dialog1Editing" v-model="dialog1Data.longitude" :precision="6" :controls="false" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度：" prop="latitude">
              <span v-show="!dialog1Editing">{{ dialog1Data.latitude }}</span>
              <el-input-number v-show="dialog1Editing" v-model="dialog1Data.latitude" :precision="6" :controls="false" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="地图：">
              <AMapSearchPoint :point="mapPoint" @choosePoint="choosePoint" />
            </el-form-item>
          </el-col>
        </el-row>
      </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><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>
    <!--表格-->
    <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="dict37Name" label="物资类型" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="number" label="物资数量" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="numberUnit" label="技术单位" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="savePlace" label="存放场所" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="dict38Name" label="当前状态" align="center" />
      <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 emergencySuppliesApi from '@/api/kd/emergencySupplies'
import dictionaryApi from '@/api/kd/dictionary'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import AMapSearchPoint from '@/components/AMap/AMapSearchPoint'
import { validatePhone } from '@/utils/validate'
const searchParam = {// 默认搜索条件
  page: 1,
  count: 10,
  searchCount: true
}
export default {
  name: 'EEmergencySupplies', // 本页面名
  components: { AMapSearchPoint },
  data() {
    return {
      selectedMine: {},
      httpHeaders: {
        'Authorization': getToken()
      },
      dict37List: [],
      dict38List: [],
      dict39List: [],
      searching: false,
      searchParam: {},
      searchResult: {
        total: 0,
        results: [] // 搜索结果
      },
      dialog1Show: false,
      dialog1Editing: false,
      dialog1Saving: false,
      dialog1Data: {},
      dialog1Rules: {
        name: [{ required: true, message: '请填写' }],
        brand: [{ required: true, message: '请填写' }],
        liablePersonPhone: [{ required: false, trigger: 'blur', validator: validatePhone }]
      },
      editState: 0, // （刚打开窗口时）记录了上次窗口作用；（保存编辑时）记录了当前窗口作用； 0无 1新增 2修改 3查看
      addingData: {}, // 上次正在新增时的内容，下次打开dialog1窗口时记录下来
      dialog2Show: false,
      dialog2Saving: false,
      dialog2Data: {}
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'baseApi'
    ]),
    tableData() {
      // 此处对返回值进行算法重组
      return this.searchResult.results
    },
    mapPoint() {
      if (this.dialog1Data.longitude && this.dialog1Data.latitude) {
        return [this.dialog1Data.longitude * 1, this.dialog1Data.latitude * 1]
      }
      return null
    }
  },
  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')
    // }
    // 字典选项卡
    const dictGroups = [37, 38, 39]
    dictGroups.forEach(i => {
      dictionaryApi.getList({ 'groupCode': i }).then(response => {
        this['dict' + i + 'List'] = response.results
      })
    })
    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
      emergencySuppliesApi.getPage(this.searchParam).then(response => {
        this.searching = false
        this.searchResult = response
      }).catch(() => {
        this.searching = false
      })
    },
    dialog1Submit() {
      this.$refs['dialog1Form'].validate(valid => {
        if (!valid) {
          this.$message.error('请检查填写内容')
          return
        } else {
          this.dialog1Saving = true
          if (this.dialog1Data._fileList) {
            this.dialog1Data.photoPath = JSON.stringify(this.dialog1Data._fileList)
          }
          if (this.editState === 1) { // 新增
            this.dialog1Data.mineType = this.selectedMine.mineType
            this.dialog1Data.mineId = this.selectedMine.id
            emergencySuppliesApi.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) { // 修改
            emergencySuppliesApi.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
      emergencySuppliesApi.getById(id).then(response => {
        this.dialog1Data = response
        if (this.dialog1Data.photoPath) {
          this.dialog1Data._fileList = JSON.parse(this.dialog1Data.photoPath)
          this.dialog1Data._fileListShow = JSON.parse(this.dialog1Data.photoPath) // 数据存放与原始绑定分开，可以防止中途赋值产生的闪烁问题
        }
        this.dialog1Editing = isEdit
        this.dialog1Show = true
      }).catch(() => {
        this.searchSubmit()
      })
    },
    dialog2Submit() {
      this.dialog2Saving = true
      emergencySuppliesApi.del(this.dialog2Data).then(() => {
        this.dialog2Show = false
        this.$message.success('删除成功')
        this.dialog2Data = {}
        this.dialog2Saving = false
        this.searchSubmit()
      }).catch(() => {
        this.dialog2Saving = false
      })
    },
    doDelete(id) {
      emergencySuppliesApi.getById(id).then(response => {
        this.dialog2Data = response
        this.dialog2Show = true
      }).catch(() => {
        this.searchSubmit()
      })
    },
    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
      })
    },
    upFileRemove(file, fileList) {
      this.dialog1Data._fileList = this.elementuiUpListFormat(fileList)
    },
    upFileError() {
      this.$message.error('上传失败，请稍后再试')
    },
    upFileExceed() {
      this.$message.error('文件数量已达上限')
    },
    upFileBefore(file) {
      const isIMG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLtSize = file.size / 1024 / 1024 < 20
      if (!isIMG) {
        this.$message.error('上传图片只能是 JPG/JPEG/PNG 格式')
        return false
      }
      if (!isLtSize) {
        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)
      }
    },
    choosePoint(lnglat) {
      if (lnglat) {
        this.dialog1Data.longitude = lnglat[0]
        this.dialog1Data.latitude = lnglat[1]
      } else {
        this.dialog1Data.longitude = null
        this.dialog1Data.latitude = null
      }
    }
  }
}
</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>
