<!--  -->
<template>
  <div>
    <main-top :crumb="crumbData"></main-top>
    <div class="table-interface">
      <div class="top-body">
        <div class="info-top">
          <div class="info-left"></div>
          <div class="info-right">
            <el-button type="primary"  @click="show('','add')">新增设备</el-button>
          </div>
        </div>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column
            v-for="(item, idx) in data"
            :key="idx"
            :prop="item.prop"
            :label="item.label"
          >
            <template slot-scope="scope">
              <span>{{scope.row[item.prop]}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <span class="o-span" @click="show(scope.row,'edit')">编辑</span>
              <span class="o-span" @click="changeState(scope.row)">{{scope.row.qiyong==='启用'?'停用':'启用'}}</span>
            </template>
          </el-table-column>
          <div class="e-pagination">
            <el-pagination @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="size" layout="prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </el-table>
      </div>
    </div>
    <el-dialog title="新增设备" :visible.sync="dialogFormVisible" width="40%">
      <el-form :model="form">
        <el-form-item label="设备名称：" style="width:50%;" :label-width="formLabelWidth">
          <el-input v-model="form.name" placeholder="请输入设备名称" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="设备ID：" style="width:50%;" :label-width="formLabelWidth">
          <el-input v-model="form.uuid" placeholder="请输入设备ID" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在位置：" :label-width="formLabelWidth">
          <el-select v-model="form.positionId" placeholder="请选择活动区域">
            <el-option v-for="(item,i) in plist" :key="i" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用：" :label-width="formLabelWidth">
            <el-radio-group v-model="form.state">
            <el-radio :label="0" >是</el-radio>
            <el-radio :label="1" >否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"  @click="save">保 存</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

import MainTop from '@/components/main-top'
const crumbData = [
  {
    name: '设备管理',
    id: 10
  }
]

let juese = {
  0: '高级管理员',
  1: '普通管理员'
}

let zt = {
  0: '启用',
  1: '停用'
}

let urlType = {
  add: '/equipment/addEquipment',
  edit: '/equipment/updateEquipment'
}

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    MainTop
  },
  data () {
    // 这里存放数据
    let data = [
      {
        prop: 'id',
        label: '序号'
      },
      {
        prop: 'name',
        label: '设备名称'
      },
      {
        prop: 'uuid',
        label: '设备ID'
      },
      {
        prop: 'positionName',
        label: '所在位置'
      },
      {
        prop: 'qiyong',
        label: '状态'
      }
    ]

    return {
      crumbData,
      data,
      region: 0,
      infoName: '',
      tableData: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        id: '',
        name: '',
        uuid: '',
        positionId: '',
        state: '',
        positionName: ''
      },
      plist: [],
      inputKey: '',
      currentPage: 1,
      size: 10,
      total: 0,
      formLabelWidth: '120px',
      imageUrl: '',
      type: 'add'
    }
  },
  watch: {
    currentPage () {
      this.refresh()
    },
    size () {
      this.refresh()
    },
    region () {
      this.refresh()
    },
    inputKey () {
      this.refresh()
    }
  },
  mounted () {
    this.getPositionList()
    this.refresh()
  },
  methods: {
    goto (item) {
      window.localStorage.setItem('editInfo', JSON.stringify(item))
      this.$router.push({name: 'edit-information', params: {type: 1}})
      this.$bus.$emit('editinfo', item)
    },
    upload_success (data) {
      this.form.head = data.data
    },
    refresh () {
      this.loading = true
      this.getInformation()
      this.loading = false
    },
    handleCurrentChange (val) {
      this.currentPage = val
    },
    save () {
      let {userName, roleId, phone, head, state} = this.form
      let data = {userName, roleId, phone, head, state}

      this.$http.post(urlType[this.type], data).then(res => {
        if (res.code === 0) {
          this.$alert('操作成功', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false
              this.refresh()
            }
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message
          })
        }
      })
    },

    show (item = '', type) {
      this.dialogFormVisible = true
      this.type = type
      this.form = {
        id: '',
        name: '',
        uuid: '',
        positionId: '',
        state: '',
        positionName: ''
      }

      if (type === 'edit') {
        this.form = item
      }
    },
    async getPositionList () {
      let result = await this.$http({
        method: 'post',
        url: '/position/list'
      })

      this.plist = result.data
    },
    changeState (item) {
      let state = item.state === 1 ? 0 : 1
      let data = {
        id: item.id,
        state
      }

      this.$confirm('此操作将导致设备状态发生改变, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.post('/equipment/updateState', data).then(res => {
          if (res.code === 0) {
            this.$alert('修改成功', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                this.refresh()
              }
            })
          } else {
            this.$notify.error({
              title: '错误',
              message: res.msg
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },

    async getInformation () {
      let params = {
        pageNum: this.currentPage,
        pageSize: this.size
      }

      let result = await this.$http({
        method: 'post',
        data: params,
        url: '/equipment/list'
      })

      if (result.code !== 0) {
        return
      }
      this.tableData = result.data.list
      this.total = result.data.total
      this.tableData.forEach(item => {
        item['date'] = this.$base.timestampToTime(item['startTime']) + '至' + this.$base.timestampToTime(item['endTime'])
        item['role'] = juese[item['roleId']]
        item['qiyong'] = zt[item['state']]
      })
    }
  }
}
</script>

<style scoped>
/* 引入公共css类 */
@import url(./style);
</style>
