<template>
  <div class="mlt">
    <div>
      <el-form :inline="true" class="orderform" size="mini">
        <el-row>
          <el-form-item>
            <el-input v-model="tag" style="width: 250px" placeholder="请输入酒店设施名称" class="search_tag" clearable/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="btn_search()"><i class="el-icon-search"/> 查询</el-button>
            <el-button @click="btn_clear()"><i class="el-icon-remove-outline"/> 重置</el-button>
            <el-button type="primary" icon="el-icon-plus" @click="addHotelItem">添加</el-button>
            <!--el-button type="primary" icon="el-icon-download" @click="btn_export">导出</el-button-->
          </el-form-item>
        </el-row>
      </el-form>
      <el-table
        id="mngrTable"
        :data="tableData"
        :highlight-current-row="true"
        border>
        <el-table-column
          prop="id"
          label="编号"/>
        <el-table-column
          prop="itemName"
          label="设施名称"/>
        <el-table-column
          prop="icon"
          label="设施图标">
          <template slot-scope="scope">
            <img :src="scope.row.icon" min-width="40" height="40">
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          class-name="table-clsdo">
          <template slot-scope="scope">
            <el-button type="text" @click="editHotelItem(scope.row)">编辑</el-button>
            <el-button type="text" @click="deleteHotelItemConfirm(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mydiv">
        <el-pagination
          :current-page.sync="pageNo"
          :page-sizes="[10, 50, 100, 300,1000]"
          :page-size="pageSize"
          :total="totalDataNumber"
          layout="sizes,total, prev, pager, next"
          class="table-pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>

    </div>
    <!--弹出框-->
    <el-dialog :visible.sync="dialogFormVisiable" title="添加酒店设施">
      <el-form :model="addForm" :rules="rules" :label-width="formLabelWidth" >
        <el-form-item label="酒店设施名称" prop="itemName">
          <el-input v-model="addForm.itemName" placeholder="请输入酒店设施名称" size="mini"/>
        </el-form-item>
        <el-form-item label="酒店设施图标" >
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="photoList"
            list-type="picture-card">
            <i class="el-icon-plus"/>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="addHotelItemCancel">取 消</el-button>
        <el-button size="mini" type="primary" @click="addHotelItemSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogModifyVisiable" title="修改酒店设施" @close="closeDialog">
      <el-form :model="modifyForm" :rules="rules" :label-width="formLabelWidth">
        <el-form-item label="酒店设施名称" prop="itemName">
          <el-input v-model="modifyForm.itemName" placeholder="请输入酒店设施名称" size="mini"/>
        </el-form-item>
        <el-form-item label="酒店设施图标" >
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="photoList"
            list-type="picture-card">
            <i class="el-icon-plus"/>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="updateHotelItemCancel">取 消</el-button>
        <el-button size="mini" type="primary" @click="updateHotelItem">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 点击删除按钮，删除确认框-->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="提示"
      width="30%">
      <span>确定删除选择的酒店设施? </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleClickDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { getToken } from '@/utils/auth'
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
export default {
  name: 'HotelMngr',
  data() {
    return {
      rules: {
        itemName: [{ required: true, message: '请输入酒店设施名称', trigger: 'blur' }]
      },
      tag: '',
      allData: [], // 所有前端分页数据
      tableData: [], // 表格数据 仅展示当前页的数据
      pageNo: 1, // 当前页数
      totalDataNumber: 0, // 总记录数
      pageSize: 10,
      formLabelWidth: '150px', // 弹出框form宽
      dialogFormVisiable: false,
      dialogModifyVisiable: false,
      deleteDialogVisible: false,
      addForm: {
        itemName: '',
        icon: ''
      },
      modifyForm: {
        id: '',
        itemName: '',
        icon: ''
      },
      deleteId: '',
      photoList: [],
      uploadUrl: process.env.UPLOAD_URL,
      uploadHeaders: {
        token: getToken()
      }
    }
  },
  created() {
    this.btn_search()
  },
  methods: {
    btn_search() {
      const vm = this
      axios.get(process.env.BASE_API + '/hotelitem/list', {
        params: {
          tag: this.tag
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.totalDataNumber = 0
          vm.allData = []
          vm.tableData = []
        } else {
          vm.totalDataNumber = parseInt(obj.total)
          if (vm.totalDataNumber > 0) {
            vm.allData = obj.data
            vm.tableData = obj.data.slice(0, vm.pageSize)
          } else {
            vm.allData = []
            vm.tableData = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    btn_clear() {
      this.tag = ''
      this.pageNo = 1
      this.btn_search()
    },
    handleCurrentChange() {
      this.tableData = this.allData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.tableData = this.allData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    },
    addHotelItem() {
      this.dialogFormVisiable = true
    },
    addHotelItemCancel() {
      this.dialogFormVisiable = false
      this.clearForm()
    },
    closeDialog() {
      this.photoList = []
    },
    clearForm() {
      this.addForm.itemName = ''
      this.addForm.icon = ''
      this.photoList = []
      this.modifyForm.id = ''
      this.modifyForm.itemName = ''
      this.modifyForm.icon = ''
    },
    addHotelItemSubmit() {
      const vm = this
      var params = new URLSearchParams()
      if (vm.addForm.itemName === '') {
        this.$message.error('请输入酒店设施名称')
        return
      }
      params.append('itemName', vm.addForm.itemName)
      params.append('icon', vm.addForm.icon)
      axios.post(process.env.BASE_API + '/hotelitem/create', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.pageNo = 1
          vm.btn_search()
        }
        vm.clearForm()
      }).catch(function(error) {
        alert(error)
      })
      this.dialogFormVisiable = false
    },
    editHotelItem(row) {
      this.dialogModifyVisiable = true
      this.modifyForm = row
      this.photoList.push({
        url: row.icon
      })
    },
    updateHotelItemCancel() {
      this.dialogModifyVisiable = false
      this.clearForm()
      this.btn_search()
    },
    updateHotelItem() {
      const vm = this
      var params = new URLSearchParams()
      params.append('id', vm.modifyForm.id)
      params.append('itemName', vm.modifyForm.itemName)
      params.append('icon', vm.modifyForm.icon)
      axios.post(process.env.BASE_API + '/hotelitem/update', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.pageNo = 1
          vm.btn_search()
        }
        vm.clearForm()
      }).catch(function(error) {
        alert(error)
      })
      this.dialogModifyVisiable = false
    },
    deleteHotelItemConfirm(row) {
      this.deleteId = row.id
      this.deleteDialogVisible = true
    },
    handleClickDelete() {
      const vm = this
      var params = new URLSearchParams()
      params.append('id', vm.deleteId)
      axios.post(process.env.BASE_API + '/hotelitem/delete', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.pageNo = 1
          vm.btn_search()
        }
      }).catch(function(error) {
        alert(error)
      })
      this.deleteDialogVisible = false
    },
    handleRemove(file, fileList) {
      this.photoList = fileList
      if (this.dialogModifyVisiable === true) {
        this.modifyForm.icon = ''
      } else {
        this.addForm.icon = ''
      }
    },
    handleSuccess(res, file, fileList) {
      if (res.code === 10000) {
        this.photoList.push({
          url: res.imageUrl
        })
        if (this.dialogModifyVisiable === true) {
          this.modifyForm.icon = this.photoList[0].url
        } else {
          this.addForm.icon = this.photoList[0].url
        }
      } else {
        this.$message.error(res.message)
        fileList.splice(fileList.indexOf(file), 1)
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    btn_export() {
      const that = this
      /* generate workbook object from table */
      var oldTable = document.querySelector('#mngrTable')
      var newTable = document.createElement('div')
      newTable.innerHTML = oldTable.innerHTML
      newTable.querySelectorAll('.table-clsdo').forEach(function(e) {
        e.remove()
      })

      const wb = XLSX.utils.table_to_book(newTable)
      const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), that.itemCnName + '列表.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') { console.log(e, wbout) }
      }
      return wbout
    }
  }
}
</script>

<style scoped>
  .mlt {
    margin-left: 20px;
    margin-top: 20px;
    margin-right: 20px;
  }
</style>
