<!--  -->
<template>
  <div class="con" v-loading.fullscreen.lock="loading">

    <div class="h-header">
      <vcenter>
        <div>
          关键字：
        </div>
        <div class="h-input">
          <el-input v-model="inpuKey" placeholder="输入角色名称"></el-input>
        </div>
        <div>
          <el-button type="primary" @click="search(inpuKey)">查询</el-button>
          <el-button>导出</el-button>
        </div>
      </vcenter>
    </div>
    <div class="h-body">
      <div style="padding:0 20px;">
        <el-button type="primary">新增角色</el-button>
        <el-button>修改权限</el-button>
      </div>
      <el-table height="520" :data="tableData" style="width: 100%;padding:0 20px;">
        <el-table-column
          v-for="(item,i) in tableHeader"
          :key="i"
          :prop="item.name"
          :label="item.label"
        >
          <template slot-scope="scope">
            <span
              @click="view_device(scope.row)"
              class="o-span"
              v-if="item.label==='设备数量'"
            >{{scope['row'].cameraNum}}</span>
            <div class="logo-add" v-else-if="item.label==='加载界面logo'">
              <div @click="showLoadingLogo(scope.row,'scene')">
                <img :src="scope['row'].sceneLogo" alt />
                <span>+</span>
              </div>
            </div>
            <div class="logo-add" v-else-if="item.label==='加载地面logo'">
              <div @click="showLoadingLogo(scope.row,'floor')">
                <img :src="scope['row'].floorLogo" alt />
                <span>+</span>
              </div>
            </div>
            <div class="logo-add" v-else-if="item.label==='背景音乐'">
              <div @click="showLoadingLogo(scope.row,'music')">
                <img :src="scope['row'].bgMusic?require('@/assets/images/icon_mp3.png'):''" alt />
                <span v-if="!scope['row'].bgMusic">+</span>
              </div>
            </div>
            <span v-else-if="item.label==='子账号数量'">{{scope['row'].subNum+scope['row'].num}}</span>
            <div
              class="time-data"
              v-else-if="item.label==='到期时间'"
            >
             <div class="select-data" @click="daoqiDate = scope.row">
               <el-date-picker
                v-model="value1"
                @change="dateChange"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
             </div>
            <span>{{scope.row[item.name]?$base.dateFormat('yyyy-MM-dd', new Date(scope.row[item.name])):'暂无到期时间'}}</span></div>
            <span v-else>{{scope.row[item.name]}}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="p-con">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="size"
          layout="prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

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

const tableHeader = [
  {
    name: 'daihao',
    label: '角色名称'
  },
  {
    name: 'sceneLogo',
    label: '创建人'
  },
  {
    name: 'floorLogo',
    label: '创建时间'
  },
  {
    name: 'lasttime',
    label: '上次修改时间'
  },
  {
    name: 'lasttime',
    label: '备注'
  }
]

let saveTypes = {
  scene: '加载界面logo',
  floor: '加载地面logo',
  music: '背景音乐'
}

let sceneTypeArr = {
  scene: 'sceneLogo',
  floor: 'floorLogo',
  music: 'bgMusic'
}
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    vcenter
  },
  data () {
    // 这里存放数据
    let dropdownActives = [{
      text: '企业账号',
      id: 'account'
    },
    {
      text: '设备ID',
      id: 'childName'
    }]

    let placeholder = {
      account: '输入企业账号查询',
      childName: '输入设备ID查询'
    }
    return {
      dropdownActives,
      dropdown_active: {
        text: '企业账号',
        id: 'account'
      },
      placeholder,
      fileList: [],
      currentlogo_id: '',
      homepic: '',
      saveTypes,
      saveType: 'scene',
      isAdd: false,
      serverName,
      c_num: '',
      tableData: [],
      tableHeader,
      dialogFormVisible: false,
      chargeVisible: false,
      deviceFormVisible: false,
      loadinglogoVisible: false,
      currentPage: 1,
      num: 1,
      loading: false,
      formLabelWidth: '100px',
      errMsg: '该ID不可用',
      userName: '',
      recharge_id: '',
      daoqiDate: '',
      form_charge: {
        userName: '',
        point: '',
        recharge: ''
      },
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      form_device: {
        d_userName: '',
        d_name: '',
        d_device: []
      },
      size: 10,
      total: 0,
      c_id: null,
      c_subNum: '',
      c_userName: '',
      c_name: '',
      addDevies: [
        {
          value: '',
          isAvailable: false,
          hasCheck: false
        }
      ],
      inpuKey: '',
      value1: ''
    }
  },
  // 监听属性 类似于data概念
  computed: {
    token () {
      return window.localStorage.getItem('zfb_token')
    }
  },
  // 监控data中的数据变化
  watch: {
    currentPage () {
      this.refresh()
    },
    size () {
      this.refresh()
    },
    num (newVal, oldVal) {
      if (newVal > oldVal) {
        this.addDevies.push({
          value: '',
          isAvailable: false,
          hasCheck: false
        })
      } else {
        this.addDevies.pop()
      }
    }
  },
  // 方法集合
  methods: {
    unbind (item) {
      this.$confirm('此操作将解除该设备的绑定, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          method: 'post',
          data: {
            childName: item.childName
          },
          url: '/company/unbindDevice',
          headers: {
            token: window.localStorage.getItem('zfb_token')
          }
        }).then(res => {
          if (res.code === 200) {
            this.$alert('解除成功', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                this.deviceFormVisible = false
                this.refresh()
              }
            })
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    dropClick (item) {
      this.inpuKey = ''
      this.userName = ''
      this.dropdown_active = item
    },
    beforeAvatarUpload (file) {
      const isLt5M = file.size / 1024 / 1024 < 5
      const isMp3 =
        file.type === 'audio/mp3' ||
        file.type === 'audio/x-ms-wma' ||
        file.type === 'audio/wav'

      if (this.saveType === 'music') {
        if (!isMp3) {
          this.$message.error('暂不支持该音频格式')
          return false
        }
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB')
        return false
      }
      return true
    },
    handleChange (file, fileList) {
      if (fileList.length > 1) {
        this.fileList = fileList.slice(-1)
      }
    },
    dateChange (data) {
      // let data1 = new Date(data)
      this.$confirm('此操作将会更新该企业账号的到期时间, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(data)
        this.$http({
          method: 'post',
          data: {
            id: this.daoqiDate.id,
            expirationDate: data
          },
          url: '/company/updateExpirationTime',
          headers: {
            token: window.localStorage.getItem('zfb_token')
          }
        }).then(res => {
          if (res.code === 200) {
            this.$alert('更新成功', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                this.refresh()
              }
            })
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    upload_success (data) {
      this.homepic = data.message
    },
    upload_fail (data) {
      this.$notify.error({
        title: '上传失败',
        message: data.message
      })
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
    },
    _checkInput: function (e) {
      this.form_charge.recharge += ''
      this.form_charge.recharge = this.form_charge.recharge.replace(
        /[^\d]/g,
        ''
      )
      if (
        Number(this.form_charge.recharge) &&
        this.form_charge.recharge > 999999999
      ) {
        this.form_charge.recharge = 999999999
      }
    },
    saveLoadingLogo () {
      if (!this.homepic && this.saveType !== 'music') {
        this.$notify.error({
          title: '保存失败',
          message: '请上传图片'
        })
      } else {
        let params
        if (this.saveType === 'scene') {
          params = {
            id: this.currentlogo_id,
            sceneLogo: this.homepic || null
          }
        } else if (this.saveType === 'music') {
          params = {
            id: this.currentlogo_id,
            bgMusic: this.homepic || ''
          }
        } else {
          params = {
            id: this.currentlogo_id,
            floorLogo: this.homepic || null
          }
        }
        this.$http({
          method: 'post',
          data: params,
          url: '/company/updateCompany',
          headers: {
            token: window.localStorage.getItem('zfb_token')
          }
        }).then(res => {
          if (res.code === 200) {
            this.$alert('保存成功', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                this.loadinglogoVisible = false
                this.refresh()
              }
            })
          } else {
            this.$notify.error({
              title: '保存失败',
              message: res.message
            })
          }
        })
      }
    },
    refresh () {
      this.loading = true
      this.getData()
      this.loading = false
    },
    search (item) {
      this.userName = item
      this.refresh()
    },
    save_reCharge () {
      this.$confirm('此操作将对该账号进行充值, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          let params = {
            id: this.recharge_id,
            point: Number(this.form_charge.recharge)
          }
          this.$http({
            method: 'post',
            data: params,
            url: '/company/addPoint',
            headers: {
              token: window.localStorage.getItem('zfb_token')
            }
          }).then(res => {
            if (res.code === 200) {
              this.$alert('充值成功', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.clearInfo()
                }
              })
            } else {
              this.loading = false
              this.$notify.error({
                title: '充值失败',
                message: res.message
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消充值'
          })
        })
    },
    async show_reCharge (item) {
      this.chargeVisible = true
      this.recharge_id = item.id
      this.form_charge = {
        userName: item.userName,
        point: item.point,
        recharge: ''
      }
    },

    async showLoadingLogo (item, type) {
      console.log(item)
      this.saveType = type
      this.homepic = item[sceneTypeArr[type]] || ''
      this.currentlogo_id = item.id
      this.loadinglogoVisible = true
    },
    async view_device (item, search = false) {
      this.deviceFormVisible = true
      // this.d_subNum = item.subNum
      this.form_device.d_userName = item.userName
      this.form_device.d_name = item.name
      let params = {
        userName: item.userName
      }
      this.form_device.d_device = (await this.$http({
        method: 'post',
        data: params,
        url: '/company/selectCompanyDevice',
        headers: {
          token: window.localStorage.getItem('zfb_token')
        }
      })).message
      setTimeout(() => {
        let items = Array.from(this.$refs.dcon.querySelectorAll('.d-body'))
        let offTop = 0
        items.forEach(item => {
          item.style.background = '#fff'
          let txt = item.querySelectorAll('span')[1].innerText
          if (txt === this.userName.trim() && search) {
            offTop = item.offsetTop - 311
            item.style.background = '#ccc'
          }
        })
        document.querySelector('#dcon').scrollTop = offTop
      }, 0)
    },
    add (item) {
      this.dialogFormVisible = true
      this.c_subNum = item.subNum
      this.c_num = item.num
      this.c_userName = item.userName
      this.c_name = item.name
      this.c_id = item.id
    },
    clearInfo () {
      this.num = 1
      this.addDevies = [
        {
          value: '',
          isAvailable: false,
          hasCheck: false
        }
      ]
      this.dialogFormVisible = false
      this.chargeVisible = false
      this.recharge_id = ''
      this.form_charge = {
        userName: '',
        point: '',
        recharge: ''
      }
      this.refresh()
    },
    canIsave () {
      let temp = []
      for (let i = 0; i < this.addDevies.length; i++) {
        if (this.addDevies[i].isAvailable === true) {
          temp.push(this.addDevies[i].value)
        } else {
          temp = []
          return false
        }
      }
      return temp.join(';')
    },
    save (userName) {
      let params = {
        childName: this.canIsave() || null,
        userName: userName || null,
        id: this.c_id || null,
        subNum: this.c_subNum || null
      }
      this.loading = true
      this.$http({
        method: 'post',
        data: params,
        url: '/company/addDevice',
        headers: {
          token: window.localStorage.getItem('zfb_token')
        }
      }).then(res => {
        if (res.code === 200) {
          this.$alert('添加成功', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.clearInfo()
            }
          })
        } else {
          this.loading = false
          this.$notify.error({
            title: '错误',
            message: res.message
          })
        }
      })
    },
    checkLegal (item) {
      if (item.value) {
        let params = {
          childName: item.value
        }
        this.$http({
          method: 'post',
          data: params,
          url: '/company/checkDevice',
          headers: {
            token: window.localStorage.getItem('zfb_token')
          }
        }).then(res => {
          if (res.code === 200) {
            item.isAvailable = true
          } else {
            item.isAvailable = false
            this.errMsg = '该ID不可用'
          }
          item.hasCheck = true
        })
      } else {
        item.isAvailable = false
        item.hasCheck = true
        this.errMsg = 'ID不能为空'
      }
    },
    async getData () {
      let params = {
        userName: this.userName || ''
      }
      let result
      if (this.dropdown_active.id === 'childName' && this.userName) {
        result = await this.$http({
          method: 'post',
          data: {
            childName: this.userName
          },
          url: '/company/findCompanyDevice',
          headers: {
            token: window.localStorage.getItem('zfb_token')
          }
        })
        let {message, code} = result
        if (message && code === 200) {
          this.view_device(message, true)
        } else {
          this.$notify.error({
            title: '无法找到对应设备'
          })
        }
      } else {
        result = await this.$http({
          method: 'post',
          data: params,
          url: '/company/selectCompanyNum',
          headers: {
            token: window.localStorage.getItem('zfb_token'),
            pageNum: this.currentPage,
            pageSize: this.size
          }
        })
        this.tableData = result.message.list
        this.total = result.message.total
        this.currentPage = result.message.pageNum
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    console.log('mounted')
    this.refresh()
  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang="scss" scoped>
.con {
  .time-data{
    position: relative;
    .select-data{
      position: absolute;
      left: 0;
      top: 0;
      opacity: 0;
      cursor: pointer;
    }
    >span{
      color: #0175dc;
    }
  }
  .ei-num {
    .el-input-number {
      width: 90%;
    }
  }
  .clear-music {
    position: relative;
    text-align: right;
    top: -30px;
    color: #999;
    cursor: pointer;
  }
  .musicIcon {
    width: 100%;
    height: 100%;
    line-height: 1;
    margin-top: 35px;
    img {
      width: 50px;
      height: auto;
    }
    p {
      font-weight: bold;
      font-size: 14px;
      color: #000;
      line-height: 20px;
      height: 20px;
      margin-top: 20px;
    }
  }
  .icon-plus {
    margin-left: 15px;
    width: 40px;
    height: 38px;
    line-height: 38px;
    text-align: center;
    background: #f5f7fa;
    color: #999;
    cursor: pointer;
    font-size: 13px;
    display: inline-block;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    &:hover {
      border: 1px solid #c0c4cc;
    }
  }
  .add-num {
    margin-left: 15px;
    width: 250px;
    .icon-close,
    .icon-correct {
      line-height: 1;
      color: #999;
    }
    input[type="number"]::-webkit-inner-spin-button,
    input[type="number"]::-webkit-outer-spin-button {
      -webkit-appearance: none;
      margin: 0;
    }
  }

  .ei-input {
    width: 100%;
    max-height: 200px;
    overflow-y: auto;
    .input-con {
      display: inline-block;
      width: 45%;
      margin: 2px 5px 2px 0;
      height: 60px;
      position: relative;
      .el-input_err {
        & /deep/ .el-input__inner {
          border: 1px solid #f56c6c;
        }
      }
      .el-input_success {
        & /deep/ .el-input__inner {
          border: 1px solid #67c23a;
        }
      }
      span {
        color: #f56c6c;
        font-size: 12px;
        line-height: 1;
        padding-top: 4px;
        position: absolute;
        left: 0;
      }
    }
  }
  .h-header {
    height: 80px;
    background-color: #fff;
    padding-left: 20px;
    box-shadow: 0 0 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 3px;

    div {
      display: inline-block;
    }

    .h-input {
      width: 220px;
    }
  }

  .h-body {
    width: 100%;
    margin: 30px 0 0;
    padding-top: 20px;
    box-shadow: 0 0 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 3px;
    background-color: #fff;

    .logo-add {
      div {
        cursor: pointer;
        line-height: 40px;
        border: 1px dotted #dcdfe6;
        border-radius: 4px;
        font-weight: bold;
        font-size: 18px;
        display: inline-block;
        width: 40px;
        height: 40px;
        background: #f5f7fa;
        position: relative;
        img {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
        }
        span {
          position: absolute;
          z-index: 100;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
        }
      }
    }

    .o-span {
      color: #0175dc;
      cursor: pointer;
    }

    .p-con {
      width: 100%;
      text-align: right;
      padding: 25px 20px 30px;
    }
  }

  .d-table {
    border: 1px solid #ccc;
    .d-con {
      max-height: 200px;
      overflow-y: scroll;
    }
    .d-header {
      font-weight: bold;
    }
    .d-header,
    .d-body {
      height: 40px;
      line-height: 40px;
      width: 100%;
      border-bottom: 1px solid #ccc;
      &:last-child {
        border: none;
      }
      span {
        text-align: center;
        display: inline-block;
        width: 24%;

      }
      .unbind{
        cursor: pointer;
      }
    }
  }
}
</style>
