<template>
  <div class="device-layout">
    <div class="d-header">
      <ul class="tab-list">
        <li @click="tabActive = item.id" :class="{active:tabActive === item.id}" v-for="(item,i) in langDevices.tabList" :key="i">
          {{item.name}}({{i===0?allTotal:xiezuoNum}})
        </li>
      </ul>
      <div class="rig-con">
        <div class="btns" v-if="tabActive===4&&!isImgType">
          <span class="button" @click="addDevice"><i class="iconfont icon-jiahao"></i>{{langDevices.add}}</span>
          <span class="button" @click="multCop">{{langDevices.fenpei}}</span>
          <span class="button default" @click="multDel">{{langDevices.unbind}}</span>
        </div>
        <div class="tab-search" :style="{marginRight:isWide?'0':'149px'}">
          <input v-model="searchKey" @keyup.enter="getList(searchKey)" type="text" :placeholder="langDevices.placeholder.searchID">
          <i class="iconfont icon-sousuo" @click="getList(searchKey)"></i>
        </div>
        <div class="main-list" v-if="tabActive===4">
          <i @click="changeType(true)" class="iconfont icon-main_grid" :title="langDevices.pictle" :class="{active:isImgType}"></i>
          <i @click="changeType(false)" class="iconfont icon-main_list" :title="langDevices.listtle" :class="{active:!isImgType}"></i>
        </div>
      </div>
    </div>
    <div class="d-con" v-if="isImgType||tabActive===0">
      <div class="edit-item item" @click="addDevice">
        <div class="plus-con">
          <div class="iconplus">
            <span></span>
            <span></span>
          </div>
          <p>{{langDevices.add}}</p>
        </div>
      </div>

      <template v-if="!loading" >
        <div class="d-item item" :style="{padding:language==='en'?'10px 16px':'10px 24px 10px 30px'}" v-for="(item,i) in mydevice.list" :key="i">
          <template v-if="tabActive===4">
            <div v-if="item.isExpire&&(item.usedSpace<=item.totalSpace)" class="tag expire">{{langDevices.jijiang}}</div>
            <div v-if="item.usedSpace>item.totalSpace" class="tag full">{{langDevices.rongliang}}</div>
          </template>
          <div class="i-left" :style="{marginTop:tabActive===4?'15px':'25px'}">
            <template v-if="tabActive===4">
              <p class="d-id" :title="item.snCode||(item.childName&&item.childName.replace('4DKKPRO_',''))||'--'">S/N: {{item.snCode||(item.childName&&item.childName.replace('4DKKPRO_',''))||'--'}} </p>
              <p class="p-sub" style="padding-left: 26px;" :title="`${item.usedSpaceStr} / ${item.totalSpaceStr}`">
                <img :src="`${$cdn}images/icon-cloud.png`" alt="">
                {{item.usedSpaceStr}} / {{item.totalSpaceStr}}
              </p>
              <div class="capacity">
                <div class="c-line">
                  <div class="active" :style="{width:getBar(item.usedSpace,item.totalSpace),background:getColor(item.usedSpace,item.totalSpace)}"></div>
                </div>
              </div>
              <p class="p-sub">{{langDevices.expand}}{{item.spaceStr||'--'}}</p>
              <p class="p-sub">{{langDevices.expire}}{{item.spaceEndStr||'--'}}</p>
              <p class="p-sub" :title="item.cooperationUserName" v-if="item.cooperationUserName">{{langDevices.xiezuo}}{{item.cooperationUserName||'--'}}</p>

              <div class="oper-con">
                <div class="oper">
                  <div>
                    <span class="spot"></span>
                  </div>
                  <ul :style="{minWidth: language==='en'?'150px': '90px'}">
                    <li @click="$router.push({name:'introduce',params:{id:item.childName}})">
                      {{langDevices.capacity}}
                    </li>
                    <li @click="unbind(item)">{{langDevices.unbind}}</li>
                    <li v-if="item.status !== 0" @click="handleCooperation(item)">{{langDevices.fenpei}}</li>
                  </ul>
                </div>
              </div>
            </template>
            <template v-else>
              <p class="d-id">ID: {{item.childName}}</p>
              <p class="p-sub">剩余点数：{{item.balance}}</p>
              <div class="d-edit" :class="{'dtow-edit':tabActive!==4}">
              <router-link class="primary" :to="{name:'introtow',params:{id:item.childName}}"><span>{{langDevices.recharge}}</span></router-link>
              <div>
                  <span @click="unbind(item)">{{langDevices.unbind}}</span>
              </div>
              </div>
            </template>
          </div>
          <div class="i-right">
            <img @click="gotoScene(item)" :src="tabActive===4?`${$cdn}images/banner_pro.png`:`${$cdn}images/t_product.png`" alt="">
          </div>
        </div>
      </template>
    </div>

    <tableList v-else @selection-change="data=>{selectedArr=data}" :header='tabHeader' :showLine='true' :selection='true' :data='mydevice.list' class="table-list" >
      <div slot-scope="{data}" slot="header">
        {{language==='en'?data.en:data.name}}
      </div>
      <div slot-scope="{data,type,canclick,item}" slot="item" style="width:100%">
        <template v-if="canclick">
          <router-link class="edit" target="_blank" :to="{name:'introduce',params:{id:item.childName}}">{{langDevices.capacity}}</router-link>
          <span class="edit" @click="handleCooperation(item)" v-if="item.status !== 0" >{{langDevices.fenpei}}</span>

        </template>
        <span v-else-if="type==='qingkuang'">{{item.usedSpaceStr}} / {{item.totalSpaceStr}}</span>
        <span v-else>{{data||'-'}}</span>
      </div>
    </tableList>
    <div class="paging" v-if="total">
      <Paging @clickHandle="pageChange" :current="currentPage" :total="total" :equable="pageSize" />
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import Paging from '@/components/Paging'
import tableList from '@/components/table'
import {device} from './idevice'

export default {
  components: {Paging, tableList},
  data () {
    let tabList = [
      {
        name: '四维看看Pro',
        id: 4
      }, {
        name: '四维看看Lite',
        id: 0
      }
    ]
    let isImgType = localStorage.getItem('isImgTypeForDevice') === '' ? true : (localStorage.getItem('isImgTypeForDevice') === 'true')

    return {
      tabHeader: device,
      lock: false,
      selectedArr: [],
      tabList,
      allTotal: 0,
      xiezuoNum: 0,
      tabActive: 4,
      currentPage: 1,
      total: 0,
      isImgType: isImgType,
      searchKey: '',
      pageSize: 8,
      isWide: window.innerWidth > 1300,
      loading: false
    }
  },
  computed: {
    ...mapState({
      language: state => state.language.current,
      token: state => state.user.token,
      langToast: state => state.language.home.toast,
      langDevices: state => state.language.home.manage.myDevices,
      mydevice: state => {
        let type = Object.prototype.toString.call(state.user.mydevice)
        if (type === '[object Object]') {
          return state.user.mydevice
        }
        let condition = state.user.mydevice && state.user.mydevice !== 'null' && type !== '[object Array]'
        return (condition ? JSON.parse(state.user.mydevice) : {})
      }
    })
  },
  watch: {
    currentPage () {
      this.getList()
    },
    tabActive (newVal) {
      this.loading = true
      this.currentPage === 1 ? this.getList() : this.currentPage = 1
    }
  },
  mounted () {
    this.getEMTotal()

    this.getList()
  },
  methods: {
    changeType (status) {
      this.isImgType = status
      localStorage.setItem('isImgTypeForDevice', status)
    },
    checkSelect () {
      let pass = this.selectedArr.length <= 0
      if (pass) {
        return this.$toast.show('warn', `${this.language === 'en' ? 'Please select at least one.' : '请至少勾选一项'}`)
      }
      return true
    },
    multCop () {
      if (this.checkSelect()) {
        let ids = this.selectedArr.map(item => {
          return item.id
        })

        this.$toast.showCooperation({
          ids: ids.join(','),
          type: 'device'
        }, () => {
          this.getList()
        })
      }
    },
    multDel () {
      if (this.checkSelect()) {
        let ids = this.selectedArr.map(item => {
          return item.id
        })

        this.unbind(ids.join(','), true)
      }
    },
    async getEMTotal () {
      let res = await this.$http({
        method: 'post',
        data: {
          cameraType: 0,
          childName: '',
          pageNum: this.currentPage,
          pageSize: this.pageSize
        },
        headers: {
          token: this.token
        },
        url: '/user/camera/list'
      })
      this.xiezuoNum = res.data.data.total
    },
    async handleCooperation (item) {
      this.$toast.showCooperation({
        num: item.id,
        cooName: item.cooperationUserName,
        type: 'device'
      }, () => {
        this.getList()
      })
    },
    gotoScene (item) {
      this.$router.push({
        name: 'scene',
        query: {
          cameraid: item.snCode || item.childName || ''
        }
      })
    },
    getBar (a, b) {
      if (a === 0) {
        return 0
      }
      let temp = (a / b) * 100
      if (temp < 1) {
        return '1%'
      }
      return temp > 100 ? 100 : Math.round(temp) + '%'
    },
    getColor (a, b) {
      let temp = (a / b) * 100
      let point = 80
      let color = ''
      switch (true) {
        case temp < point:
          color = '#1fe4dc'
          break

        default:
          color = '#ff0000'
          break
      }
      return color
    },
    async unbind (item, multi = false) {
      this.$toast.showConfirm('warn', this.langToast['26'], async () => {
        let params = {
        }
        multi ? (params['ids'] = item) : (params['cameraId'] = item.id)
        let res = await this.$http({
          method: 'post',
          data: params,
          headers: {
            token: this.token
          },
          url: '/user/camera/unbind'
        })
        let data = res.data
        if (data.code === 0) {
          return this.$toast.show('warn', this.langToast['33'], () => {
            this.getList()
          })
        }
        return this.$toast.show('error', this.langToast[data.code])
      })
    },
    pageChange (data) {
      this.currentPage = data
    },
    addDevice () {
      let val = this.tabActive === 4 ? 1 : 0
      this.$toast.showBinding(val, () => {
        this.getList()
      })
    },
    async getList (searchKey = '') {
      window.scrollTo(0, 0)

      let params = {
        cameraType: this.tabActive,
        childName: searchKey.trim(),
        pageNum: searchKey ? 1 : this.currentPage,
        pageSize: this.pageSize
      }
      await this.$store.dispatch('getUserDevice', params)

      if (!this.mydevice.total && searchKey) {
        return this.$toast.show('warn', this.language === 'en' ? 'No corresponding device found.' : '没有找到对应的设备', () => {
          this.getList()
        })
      }
      this.pageSize = this.mydevice.pageSize
      this.total = this.mydevice.total || 0
      this.loading = false

      if (!this.lock && !this.allTotal) {
        this.lock = true
        this.allTotal = this.total
      }
    }
  }
}
</script>

<style lang="scss" scoped>
$theme-color: #1fe4dc;
$font-color: #2d2d2d;

.device-layout{
  margin: 30px 0 30px 0;
  width: 995px;
  color: $font-color;
  .d-header{
    margin-left: 40px;
    height: 30px;
    .tab-list{
      display: inline-block;
      li{
        display: inline-block;
        margin-right: 40px;
        cursor: pointer;
        font-size: 14px;
        line-height: 1.5;
      }
      .active{
        color: $theme-color;
        border-bottom: 1px solid $theme-color;
      }
    }

    .rig-con{
      margin-right: 40px;
      float: right;
      display: flex;
      align-items: center;
      .btns{
        margin-right: 20px;
        .button{
          line-height: 30px;
          height: 30px;
          min-width: 80px;
          padding: 0 10px;
          text-align: center;
          vertical-align: middle;
          font-size: 14px;
          color: #202020;
          margin-left: 10px;
          cursor: pointer;
          .iconfont{
            font-size: 14px;
            margin-right: 4px;
          }
        }
        .default{
          background: #E4E4E4;
        }
      }
      .tab-search{
        float: right;
        position: relative;
        width: 230px;
        padding-left: 10px;
        border: 1px solid #ccc;
        display: flex;
        .iconfont{
          width: 28px;
          height: 28px;
          padding: 6px;
          cursor: pointer;
          background: #e4e4e4;
        }
        input{
          width: 100%;
          font-size: 14px;
          appearance: none;
          line-height: 28px;
          height: 28px;
          border: 0;
        }
      }
      .main-list{
        display: inline-block;
        margin-left: 35px;
        .iconfont{
          cursor: pointer;
          font-size: 20px;
          margin-left: 5px;
        }
        .active{
          color: #1fe4dc;
        }
      }
    }

  }
  .d-con{
    margin-left: 40px;
    display: inline-block;
    .item{
      display: inline-block;
      box-shadow: 0 4px 4px rgba($color: #000000, $alpha: 0.1);
      position: relative;
      width: 280px;
      height: 180px;
      margin: 36px 36px 0 0;
    }
    .edit-item{
      cursor: pointer;
      vertical-align: top;
      .plus-con{
        position: absolute;
        text-align: center;
        transform: translate(-50%,-50%);
        top: 50%;
        left: 50%;
        .iconplus{
          position: relative;
          width: 50px;
          height: 50px;
          margin: 0 auto;
          span{
            position: absolute;
            transform: translate(-50%,-50%);
            top: 50%;
            left: 50%;
            display: inline-block;
            width: 50px;
            height: 6px;
            background: $font-color;
            &:last-child{
              transform: translate(-50%,-50%) rotate(90deg)
            }
          }
        }
        p{
          margin-top: 28px;
          font-weight: bold;
        }
      }
    }
    .d-item{
      padding: 10px 24px 10px 30px;
      position: relative;
      .tag{
        position: absolute;
        top: 0;
        left: 0;
        min-width: 80px;
        height: 18px;
        line-height: 18px;
        font-size: 10px;
        border-radius: 4px 0 18px 0;
        text-align: center;
        color: #fff;
        padding: 0 10px;
      }
      .expire{
        background: #fed228;
      }
      .full{
        background: #f90217;
      }
      .i-left{
        display: inline-block;
        vertical-align: top;
        width: 145px;
        margin-top: 25px;
        .d-id{
          font-size: 14px;
          font-weight: bold;
          margin-bottom: 5px;
          word-break: break-all;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
        }
        .capacity{
          margin: 5px 0;
          .c-line{
            width: 100%;
            height: 10px;
            background-color: #ccc;
            .active{
              background-color:$theme-color;
              height: 100%;
            }
          }
        }
        .p-sub{
          color: #969696;
          font-size: 14px;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
          position: relative;
          img{
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 22px;
            height: 22px;
            vertical-align: middle;
          }

        }
        .d-edit{
          margin-top: 10px;
          font-size: 14px;
          position: absolute;
          bottom: 22px;
          div,a {
            display: inline-block;
            background: #fff;
            color: #000;
            border: 1px solid #777777;
            border-radius: 2px;
            font-size: 12px;
            width: 50px;
            height: 22px;
            line-height: 22px;
            text-align: center;
            vertical-align: middle;
            margin-right: 4px;
            box-sizing: border-box;
            cursor: pointer;
            position: relative;
            span{
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%,-50%);
              width: 100%;
            }
          }
          .primary{
            background: #1fe4dc;
            border: 1px solid #1fe4dc;
          }
        }
        .oper-con{
          flex: 1;
          .oper {
            width: 26px;
            cursor: pointer;
            display: inline-block;
            position: relative;
            line-height: 30px;
            height: 30px;
            font-size: 14px;
            &:hover{
              >ul{
                display: block;
              }
            }
            >div {
              text-align: right;
              display: inline-block;
              width: 100%;
              .spot{
                width: 4px;
                height: 4px;
                display: inline-block;
                background-color: #202020;
                border-radius: 50%;
                position: relative;
                margin-right: 10px;
                &::after,&::before{
                  content: '';
                  position: absolute;
                  width: 4px;
                  height: 4px;
                  display: inline-block;
                  background-color: #202020;
                  border-radius: 50%;
                  left: -8px;
                  top: 50%;
                  transform: translateY(-50%);
                }
                &::before{
                  right: -8px;
                  left: unset;
                }
              }
            }

            >ul{
              display: none;
              position: absolute;
              top: 30px;
              z-index: 9;
              left: 0;
              background: #F7F7F7;
              min-width: 90px;
              box-shadow:0px 1px 6px rgba(0,0,0,0.16);
              >li{
                text-align: left;
                width: 100%;
                line-height: 2.5;
                padding: 0 10px;
                color: #202020;
                &:hover{
                  background-color: #EBEBEB;
                }
              }
            }
            .b_default{
                display: inline-block;
                background: #fff;
                color: #000;
                border: 1px solid #777;
                border-radius: 2px;
                font-size: 12px;
                width: 52px;
                height: 22px;
                line-height: 22px;
                text-align: center;
                vertical-align: middle;
                margin-left: 4px;
                -webkit-box-sizing: border-box;
                box-sizing: border-box;
                cursor: pointer;
                position: relative;
                >span{
                  position: absolute;
                  top: 50%;
                  left: 50%;
                  -webkit-transform: translate(-50%,-50%);
                  transform: translate(-50%,-50%);
                  width: 100%;
                }
            }
          }
        }
        .dtow-edit{
          bottom: 40px;
        }
      }
      .i-right{
        vertical-align: top;
        float: right;
        height: 100%;
        position: relative;
        img{
          height:150px;
          cursor: pointer;
        }
      }
    }
  }
  .table-list{
    width: calc(100% - 80px);
    margin: 30px auto;
  }
  .scene-nothing{
    padding: 42px 0 150px 0;
    text-align: center;
    img{
      padding-bottom: 22px;
      text-align: center;
    }
    div{
      font-size: 16px;
      color: #969696;
      text-align: center;
      width: 230px;
      margin: 0 auto;
    }
  }
   .paging {
    // border-left: #e5e5e5 1px solid;
    height: 100%;
    margin: 40px 0;
    & /deep/ .layout {
      text-align: left;
      margin-top: 0;
      margin-left: 30px;
    }
    & /deep/ .layout a:not(:last-child) {
      margin: 10px 8px;
      font-size: 16px;
      display: inline-block;
      font-weight: 500;
      cursor: pointer;
      user-select: none;
      color: #999;
      position: relative;
      transition: color 0.3s;
    }
    & /deep/ .layout a:last-child {
      position: relative;
      top: -5px;
      display: -ms-inline-flexbox;
      display: inline-flex;
      -ms-flex-align: center;
      align-items: center;
      height: 22px;
      padding: 0 9.6px;
      padding: 0 0.6rem;
    }
    & /deep/ .layout a:last-child::before,
    & /deep/ .layout a:last-child::after {
      content: "";
      display: inline-block;
      will-change: transform;
      transition: transform 0.3s;
    }

    & /deep/ .layout a:not(:last-child).active::after,
    & /deep/ .layout a:not(:last-child).active,
    & /deep/ .layout a:not(:last-child):hover,
    & /deep/ .layout a:not(:last-child):hover::after {
      color: #111111;
      transform: scaleX(1);
    }

    & /deep/ .layout a:not(:last-child)::after {
      content: "";
      height: 3px;
      width: 140%;
      background-color: #111;
      display: block;
      margin-left: -20%;
      margin-top: 3px;
      transform-origin: 50% 50%;
      transform: scaleX(0);
      will-change: transform;
      transition: transform 0.3s;
    }
  }
}
@media screen and (min-width: 2000px) {
  .device-layout {
    width: 75%;
  }
}
@media screen and (max-width: 1700px){
  .device-layout {
    width: 95%;
    .d-con{
      .item{
        width: 280px;
        margin: 36px 36px 0 0;
      }
    }
  }
}

@media screen and (max-width: 1400px){
   .device-layout {
    width: 98%;
    .d-header{
      .tab-search{
        margin-right: 60px!important;
      }
    }
    .d-con{
      .item{
        width: 265px;
        margin: 20px 20px 0 0;
        padding: 10px 16px!important;
      }
    }
  }
}

@media screen and (max-width: 1300px){
   .device-layout {
    width: 100%;
    .d-header{
      .tab-search{
        margin-right: 20px!important;
      }
    }
    .d-con{
      .item{
        width: 235px;
        margin: 10px 11px 0 0;
        padding: 10px 13px!important;
      }
    }
  }
}

</style>
