<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-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="640px">
      <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="24">
            <el-form-item label="标题：" prop="name">
              <span v-show="!dialog1Editing">{{ dialog1Data.name }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.name" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类型：" prop="dict40Name">
              <span v-show="!dialog1Editing">{{ dialog1Data.dict40Name }}</span>
              <el-select v-show="dialog1Editing" v-model="dialog1Data.dict40" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item in dict40List" :key="item.id" :label="item.value" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述：" prop="detail">
              <span v-show="!dialog1Editing">{{ dialog1Data.detail }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.detail" type="textarea" :rows="3" maxlength="500" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="通知矿山：" prop="_mineIndexList">
              <span v-for="(response,i) in dialog1Data._responseList" v-show="!dialog1Editing" :key="response.id">
                <span v-show="i!=0">，</span>
                <span>{{ response.mineName }}</span>
              </span>
              <el-select v-show="dialog1Editing" v-model="dialog1Data._mineIndexList" :disabled="dialog1Data._mineSelectAll" multiple placeholder="请选择" style="width: 100%;">
                <el-option v-for="mine in mineList" :key="mine.index" :label="mine.name" :value="mine.index" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-show="dialog1Editing" :span="24">
            <el-form-item label="" prop="_mineSelectAll">
              <el-switch v-model="dialog1Data._mineSelectAll" active-text="通知全部矿山" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件：" prop="filesPath">
              <el-link v-for="file in dialog1Data._fileList" v-show="!dialog1Editing" :key="file.url" @click="openFile(file)">{{ file.name }}</el-link>
              <el-upload
                v-show="dialog1Editing"
                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._fileList"
              >
                <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 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="dict40Name" label="类型" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="createDatetime" label="时间" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="detail" label="描述" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="filesPath" label="附件" align="center">
        <template slot-scope="scope">
          <span v-if="!scope.row.filesPath || scope.row.filesPath==='[]'">无</span>
          <span v-else>有</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="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 noticeApi from '@/api/kd/notice'
import mineApi from '@/api/kd/mine'
import dictionaryApi from '@/api/kd/dictionary'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
const searchParam = {// 默认搜索条件
  page: 1,
  count: 10,
  searchCount: true
}
export default {
  name: 'CNotice', // 本页面名
  components: {},
  data() {
    return {
      httpHeaders: {
        'Authorization': getToken()
      },
      mineList: [],
      dict40List: [],
      searching: false,
      searchParam: {},
      searchResult: {
        total: 0,
        results: [] // 搜索结果
      },
      dialog1Show: false,
      dialog1Editing: false,
      dialog1Saving: false,
      dialog1Data: {},
      dialog1Rules: {
        name: [
          { required: true, message: '请填写' }
        ]
      },
      editState: 0, // （刚打开窗口时）记录了上次窗口作用；（保存编辑时）记录了当前窗口作用； 0无 1新增 2修改 3查看
      addingData: {}, // 上次正在新增时的内容，下次打开dialog1窗口时记录下来
      dialog2Show: false,
      dialog2Saving: false,
      dialog2Data: {}
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'user'
    ]),
    tableData() {
      // 此处对返回值进行算法重组
      return this.searchResult.results
    }
  },
  mounted() {
    // 矿山List
    mineApi.getEnableMine().then(response => {
      let i = 1
      response.results.forEach(x => { x.index = i++ })
      this.mineList = response.results
    })
    // 字典
    const dictGroups = [40]
    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
      noticeApi.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.dialog1Data._mineSelectAll) { // 全部矿山
            const mineListParam = []
            this.mineList.forEach(mineItem => {
              mineListParam.push({
                mineType: mineItem.mineType,
                mineId: mineItem.id
              })
            })
            this.dialog1Data.mineList = mineListParam
          } else if (this.dialog1Data._mineIndexList) { // 勾选矿山
            const mineListParam = []
            this.dialog1Data._mineIndexList.forEach(index => {
              mineListParam.push({
                mineType: this.mineList[index - 1].mineType,
                mineId: this.mineList[index - 1].id
              })
            })
            this.dialog1Data.mineList = mineListParam
          }
          if (!this.dialog1Data.mineList || this.dialog1Data.mineList.length === 0) {
            this.$message.error('请选择通知到的矿山')
            this.dialog1Saving = false
            return
          }
          if (this.editState === 1) { // 新增
            noticeApi.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) { // 修改
            noticeApi.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
      noticeApi.getById(id).then(response => {
        this.dialog1Data = response
        noticeApi.getResponseByNoticeId(id).then(response => {
          this.$set(this.dialog1Data, '_responseList', response.results)
        })
        if (this.dialog1Data.filesPath) {
          this.dialog1Data._fileList = JSON.parse(this.dialog1Data.filesPath)
        }
        this.dialog1Editing = isEdit
        this.dialog1Show = true
        this.$nextTick(() => {
          this.$refs['dialog1Form'].clearValidate()
        })
      }).catch(() => {
        this.searchSubmit()
      })
    },
    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 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)
      }
    },
    dialog2Submit() {
      this.dialog2Saving = true
      noticeApi.del(this.dialog2Data).then(() => {
        this.dialog2Show = false
        this.$message.success('删除成功')
        this.dialog2Data = {}
        this.dialog2Saving = false
        this.searchSubmit()
      }).catch(() => {
        this.dialog2Saving = false
      })
    },
    doDelete(id) {
      noticeApi.getById(id).then(response => {
        this.dialog2Data = response
        this.dialog2Show = true
      }).catch(() => {
        this.searchSubmit()
      })
    }
  }
}
</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>
